In python you must have a block
after the if expression :
(see the syntax guide). A block may either be a simple statement (single expression after the colon) or an indented series of one or more statements
.
This basically boils down to: "What is a valid statement?" If you follow the chain of what a valid statement can be; even just an atom
is a valid statement. This is what you are experiencing as an atom includes most literals like an empty string ""
, a number, an empty dictionary, the various singletons None
, True
, False
, Ellipsis
, etc.
The keyword "pass" was included in the language for the exact purpose of doing nothing in a place where you are required by the syntax to have a block. All other suggestions and options given may work, but were not included in the language for that purpose. It is merely a side effect of how other things happen to work. Most of the examples will cause extra (if small) processing and memory overhead, where "pass" is correctly optimized by the interpreter to do nothing.
You may find people saying "you shouldn't be using pass" or "it's bad to have pass in your code". This comes from the idea that you shouldn't ever be doing nothing because it's wasted computation. For example, if you only need the else
block of an if
statement, it may be more advisable to change it to if not
. It is also a common pattern to find pass in try: except:
blocks, and it is generally not advisable to just do nothing when an error is caught.
This does not mean pass doesn't have perfectly legitimate use cases. I particularly use pass all the time when laying out classes and functions I haven't written yet. This allows me to sketch out a class before implementing everything while still being able to run quick tests without syntax errors. When you think you're done with your code it's then trivial to do a quick "ctrl-f" to find any leftover pass
statements for things I may have said "I'll get to it later" initially. One could even argue this is a bit lax, as it's a little better to actually raise a NotImplemented
error if you hit an unfinished area, and I've been trying to swtich, but thats almost 3x the number of keystrokes ;)