Why does python VM have co_names instead of using co_consts?

The code object generated by the Python compiler contains a tuple of constants used in instructions (named co_consts ), as well as a tuple containing names (named co_names ).

Why are there two different lists? Would it be easier to just use co_consts for names too?

+5
source share
2 answers

Consider the following function.

 def f(x): x += n return x * 4 

Here x is a local name, its value may change. 4 - constant. Its value will never change. However, this is still an object, and it is better to cache them, rather than creating a new object every time you need it. Finally, n is a global reference. The string "n" is stored by the function, so it can be used as a key to extract n from the global context of the function.

 >>> f.__code__.co_nlocals # just 1 (for x) 1 >>> f.__code__.co_consts (None, 4) >>> f.__code__.co_names ('n',) >>> "n" in f.__globals__ and globals() is f.__globals__ True 

The reason for storing names and constants separately for introspection purposes. The only real reason for merging tuples would be memory efficiency, although it would only bring you one object and one pointer to each function. Consider the following function.

 def g(): return "s" * n 

If a tuple containing consts was combined with a tuple containing names, then you (and not the virtual machine) could not determine what values ​​were used to access global variables and which were function constants.

+6
source

I know this answer looks like 11 months, but because of my messing around, it seems the following happens:

To access co_names in bytecode, LOAD_GLOBAL (code name index) is used, and this pushes a link to the desired co_names onto the stack, for example, its indirect

To access co_consts in bytecode, LOAD_CONST (co consts index) is used, and this pushes the actual value stored in the desired co_consts onto the stack, for example, its direct

I'm not sure if it is directly related to the python level, but at the bytecode level its profound difference

+1
source

Source: https://habr.com/ru/post/1212085/


All Articles