How to use the pass statement
I am in the process of learning Python and I have reached the section about the pass
statement. The guide I'm using defines it as being a null statement that is commonly used as a placeholder.
I still don't fully understand what that means though. What would be a simple/basic situation where the pass
statement would be used and why would it be needed?
Suppose you are designing a new class with some methods that you don't want to implement, yet.
class MyClass(object):
def meth_a(self):
pass
def meth_b(self):
print "I'm meth_b"
If you were to leave out the pass
, the code wouldn't run.
You would then get an:
IndentationError: expected an indented block
To summarize, the pass
statement does nothing particular, but it can act as a placeholder, as demonstrated here.
Python has the syntactical requirement that code blocks (after if
, except
, def
, class
etc.) cannot be empty. Empty code blocks are however useful in a variety of different contexts, such as in examples below, which are the most frequent use cases I have seen.
Therefore, if nothing is supposed to happen in a code block, a pass
is needed for such a block to not produce an IndentationError
. Alternatively, any statement (including just a term to be evaluated, like the Ellipsis
literal ...
or a string, most often a docstring) can be used, but the pass
makes clear that indeed nothing is supposed to happen, and does not need to be actually evaluated and (at least temporarily) stored in memory.
-
Ignoring (all or) a certain type of
Exception
(example fromxml
):try: self.version = "Expat %d.%d.%d" % expat.version_info except AttributeError: pass # unknown
Note: Ignoring all types of raises, as in the following example from
pandas
, is generally considered bad practice, because it also catches exceptions that should probably be passed on to the caller, e.g.KeyboardInterrupt
orSystemExit
(or evenHardwareIsOnFireError
– How do you know you aren't running on a custom box with specific errors defined, which some calling application would want to know about?).try: os.unlink(filename_larry) except: pass
Instead using at least
except Error:
or in this case preferablyexcept OSError:
is considered much better practice. A quick analysis of all Python modules I have installed gave me that more than 10% of allexcept ...: pass
statements catch all exceptions, so it's still a frequent pattern in Python programming. -
Deriving an exception class that does not add new behaviour (e.g., in SciPy):
class CompileError(Exception): pass
Similarly, classes intended as abstract base class often have an explicit empty
__init__
or other methods that subclasses are supposed to derive (e.g.,pebl
):class _BaseSubmittingController(_BaseController): def submit(self, tasks): pass def retrieve(self, deferred_results): pass
-
Testing that code runs properly for a few test values, without caring about the results (from
mpmath
):for x, error in MDNewton(mp, f, (1,-2), verbose=0, norm=lambda x: norm(x, inf)): pass
-
In class or function definitions, often a docstring is already in place as the obligatory statement to be executed as the only thing in the block. In such cases, the block may contain
pass
in addition to the docstring in order to say “This is indeed intended to do nothing.”, for example inpebl
:class ParsingError(Exception): """Error encountered while parsing an ill-formed datafile.""" pass
-
In some cases,
pass
is used as a placeholder to say “This method/class/if-block/... has not been implemented yet, but this will be the place to do it”, although I personally prefer theEllipsis
literal...
in order to strictly differentiate between this and the intentional “no-op” in the previous example. (Note that the Ellipsis literal is a valid expression only in Python 3)For example, if I write a model in broad strokes, I might write
def update_agent(agent): ...
where others might have
def update_agent(agent): pass
before
def time_step(agents): for agent in agents: update_agent(agent)
as a reminder to fill in the
update_agent
function at a later point, but run some tests already to see if the rest of the code behaves as intended. (A third option for this case israise NotImplementedError
. This is useful in particular for two cases: Either “This abstract method should be implemented by every subclass, and there isn't a generic way to define it in this base class”, or “This function, with this name, is not yet implemented in this release, but this is what its signature will look like”)
Besides its use as a placeholder for unimplemented functions, pass
can be useful in filling out an if-else statement ("Explicit is better than implicit.")
def some_silly_transform(n):
# Even numbers should be divided by 2
if n % 2 == 0:
n /= 2
flag = True
# Negative odd numbers should return their absolute value
elif n < 0:
n = -n
flag = True
# Otherwise, number should remain unchanged
else:
pass
Of course, in this case, one would probably use return
instead of assignment, but in cases where mutation is desired, this works best.
The use of pass
here is especially useful to warn future maintainers (including yourself!) not to put redundant steps outside of the conditional statements. In the example above, flag
is set in the two specifically mentioned cases, but not in the else
-case. Without using pass
, a future programmer might move flag = True
to outside the condition—thus setting flag
in all cases.
Another case is with the boilerplate function often seen at the bottom of a file:
if __name__ == "__main__":
pass
In some files, it might be nice to leave that there with pass
to allow for easier editing later, and to make explicit that nothing is expected to happen when the file is run on its own.
Finally, as mentioned in other answers, it can be useful to do nothing when an exception is caught:
try:
n[i] = 0
except IndexError:
pass