In languages like Python, you have two types of 'things' being evaluated: expressions and statements. Expressions are, well, expressions, which evaluate to something. For instance 1
, 1+1
, or f(x)
are all expressions, evaluating to something.
By comparison, statements are not 'returning' anything, instead, they 'act on the environment'. For instance, x=3
sets the variable x
to the value 3
. def f(x): return x + 1
sets the value of f
to a function. That doesn't 'evaluate' to anything, that modifies the current environment where things are evaluated.
With this in mind, you sometimes need an empty statement. For syntactic reasons, there are places in Python where you need a statement, but if you don't want anything to happen here, you might want to express that what happens is precisely 'nothing'. One way would be to evaluate an expression and do nothing with it:
def f():
1
But a casual glance at that might suggests that this function returns 1
: instead, you can use pass
as explicitely stating: 'do nothing':
def f():
pass
Now, there's another catch: I mentioned earlier that f(x)
is an expression. But in the two examples above, I've not put any return
, so what do these evalute to ? The answer is: a function call returns (i.e. evaluates to) None
, unless specified otherwise. So:
def f():
pass
def g(x):
if x > 2:
return x
def h():
return None
f() # None
g(3) # 3 -> we explicitely say `return x`
g(1) # None -> no return specified for that path
h() # None -> we explicitely say `return None`
Others have mentioned that pass can be used in other places (e.g. within empty classes, in exception handling...). The reason for this is that all of these require some statement, and pass
allows to specify an empty one. This, combined with the fact that a function returns None
except specified otherwise, leads to the behaviour you observe (although they are conceptually different).