What is None in the co_consts attribute of a code object?

The following function returns None :

 In [5]: def f(): ...: pass 

Therefore, 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, that 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 doesn't use None , so why is it in co_consts ?

+7
python python-internals
source share
1 answer

The default return value for the None function is therefore always inserted. Python doesn't want to parse if you always get a return statement.

Consider, for example:

 def foo(): if True == False: return 1 

The above function will return None , but only because the if will never be True .

In your simple case, it is obvious to us that there is only one RETURN_VALUE operation RETURN_VALUE , but to expand it, the general case of detecting a computer is not worth the effort. It’s better to just keep the None link and make it that one link is very cheap.

+7
source share

All Articles