The following function returns None
:
In [5]: def f():
...: pass
So I was not surprised by this output:
In [8]: dis.dis(f)
2 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
In [10]: f.__code__.co_consts
Out[10]: (None,)
Ok, this makes sense. But now, consider the following function:
In [11]: def g():
....: return 1
In [12]: dis.dis(g)
2 0 LOAD_CONST 1 (1)
3 RETURN_VALUE
In [13]: g.__code__.co_consts
Out[13]: (None, 1)
g
does not use None
, so why is it in co_consts
?
The default return value for a function is None
, so it is always inserted. Python doesn't want to have to analyse if you are always going to reach a return statement.
Consider for example:
def foo():
if True == False:
return 1
The above function will return None
, but only because the if
statement is never going to be True
.
In your simple case, it is obvious to us humans that there is just the one RETURN_VALUE
opcode, but to extend this to the general case for a computer to detect is not worth the effort. Better just store the None
reference and be done with it, that one reference is extremely cheap.