Reputation: 5748
I came across a legacy code base, which is using pass
, and None
interchange, as empty statement.
if True:
pass
if True:
None
Since we prefer to have a consistent style over our code base, we wish to stick with one common standard. We need to choose between pass
and None
.
Python community mostly recommend using pass
as empty statement.
https://stackoverflow.com/a/15081801/1051441
But, is there any side effect if we use None
?
Is there any reason using pass
in favourable over None
as empty statement?
What is the difference between Pass and None in Python talks about difference among the 2. But, it doesn't mention why pass
is preferable over None
as empty statement.
Upvotes: 1
Views: 98
Reputation: 11302
As other answers mentioned, there is no difference in the meaning of the code. Furthermore, recent versions of CPython enables dead code elimination on these kind of examples, and the bytecode is exactly the same in the OP's examples.
However, here's a very slight performance difference, in particular in earlier versions without optimization. Namely, when Python hits the pass
keyword statement, it just jumps over it. But when it hits the None
expression, it loads the value and then discards it, with the implied increment and decrement of reference count. Therefore, the latter should be slightly slower.
Example:
$ python -m timeit -r 10 -n 10000000 -s 'def f(): None' 'f()'
10000000 loops, best of 10: 0.209 usec per loop
$ python -m timeit -r 10 -n 10000000 -s 'def f(): pass' 'f()'
10000000 loops, best of 10: 0.178 usec per loop
Upvotes: 1
Reputation: 6066
Using pass
is better.
Technically, in your example, there is no difference. Both snippets have the same disassembly:
(note that in fact, the function does absolutely nothing. The LOAD CONST None
is for an implicit return statement, returning None
.)
>>> def f():
... if True:
... pass
...
>>> def g():
... if True:
... None
...
>>> dis.dis(f)
3 0 LOAD_CONST 0 (None)
2 RETURN_VALUE
>>> dis.dis(g)
3 0 LOAD_CONST 0 (None)
2 RETURN_VALUE
However, it's important to consider readability of your code. The statement None
and pass
essentially mean different things. pass
is a placeholder, None
is a data value. It is merely a coincidence that having None
by itself does nothing. It is better to code what you mean.
Upvotes: 2
Reputation: 9523
pass
is explicit about what to you want. Python philosophy: Explicit is better than implicit., see the Zen of Python
Some IDEs warn you if you write some code after pass
, but not after None
, so you have an extra check. I don't know why python code doesn't warn about so obvious user error (I doesn't think user will use pass
and write other instructions).
Upvotes: 0