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
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.
source share