What's a standard way to do a no-op in python?

Viewed 144568

I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the code you can see what happens as a result of each option. How do I code the no-op? Currently, I'm doing it like this:

no_op = 0

if x == 0:
    y = 2 * a
elif x == 1:
    z = 3 * b
elif x == 3:
    no_op

(The code is actually quite a bit longer than that, and more complicated. This is just to illustrate the structure).

I don't like using a variable as a no-op, but it's the neatest way I could think of. Is there a better way?

5 Answers

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

You can print an empty string and no line feed to the standard output. This can be handy if a linter prohibits you from using a pass where it is unnecessary, but you need a line for a comment:

print('', end='')  # This does next to nothing

Using this empty print has very little side effects, besides wasted CPU cycles:

$ echo "print('', end='')  # This does next to nothing" > main.py
$ python3 main.py
$ 

Note that using pass here would have been syntactically correct, but linters might complain:

$ echo "pass  # This does next to nothing" > main.py
$ python3 main.py
$ 

a simple practice on my desk just uses a line like this:

dummy = 0

the normal coder (even those which are coming from other common programming languages) will instantly understand it.

Related