According to Python's doc, the co_names
attribute on a code
object returns a tuple containing the names of all local variables of the given function, while co_nlocals
returns the number of all local variables.
Taking the following function as an example:
def foo(x, y, z):
pass
foo.__code__.co_names
returns an empty tuple, and that makes sense since the function has no local variables — only arguments.
However, foo.__code__.co_nlocals
returns the value 3
, even though there are no local variables in the function as testified by the co_names
attribute.
foo.__code__.co_names # ()
foo.__code__.co_nlocals # 3
Why is this so?