0

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?

coderboy
  • 1,710
  • 1
  • 6
  • 16
  • A function parameter is exactly the same thing as a local variable, except that it already has a value when the function starts executing. – jasonharper Nov 24 '20 at 17:29
  • Probably the names are in `co_varnames` – fdermishin Nov 24 '20 at 17:29
  • @user13044086 The names do show up in ```co_varnames```, but according to the doc, ```co_nlocals``` returns the number of local variables, and so if ```co_names``` doesn't show anything, then ```co_nlocals``` should return ```0```. – coderboy Nov 24 '20 at 17:31
  • 1
    [CPython PR still open since 2017](https://github.com/python/cpython/pull/2743) – wim Nov 24 '20 at 17:35
  • I just read that it was a documentation error. These errors do a lot than can be stated. – coderboy Nov 24 '20 at 17:36

0 Answers0