Information about In-functions Variables Besides locals() Dictionary

Viewed 75

This code, as expected, raises an UnboundLocalError.

x = 3

def f():
    print("locals: " + str(locals()))
    if x==3:
        print("x is 3!")
    x = 1

f()

However, as we can see from the output, locals() is an empty dictionary at the beginning:

locals: {}
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/try/scatch.py", line 10, in <module>
    f()
  File "C:/Users/user/PycharmProjects/try/scatch.py", line 6, in f
    if x==3:
UnboundLocalError: local variable 'x' referenced before assignment

From what I gathered, locals dictionary holds all of the information about the in-functions variables that Python knows. Clearly, this is not the case: there must be some information about the variables inside of the function besides locals().

My question is - what is this information exactly? Can we access at the beginning of the function to the list of the variables inside it?

2 Answers

The answer you're looking for in CPython is f.__code__.co_varnames documented in the inspect module.

>>> def f():
...     print(f.__code__.co_varnames)
...     x = 1
...     y = 2
>>> f()
('x', 'y')

While f.__code__.co_varnames (as pointed out in orlp's answer) works, here's way to find local assignments with AST:

import inspect,ast

x = 3

def find_ass_in_func(func):
    f_src = inspect.getsource(f)
    f_ast = ast.parse(f_src)
    return find_ass_in_src(f_ast.body)
def find_ass_in_src(bodies):
    ass = set()
    for b in bodies:
        if isinstance(b, ast.Assign):
            ass |= set(t.id for t in b.targets)
        if(hasattr(b, "body")):
            ass |= find_ass_in_src(b.body)
    return ass

def f():
    print("locals: " + str(locals()))
    print("local variables:", find_ass_in_func(f))
    if x==3:
        print("x is 3!")
        x = 5
        y = 6 # just for demonstration purpose
    x = 1

f()

Output:

locals: {}
local variables: {'x', 'y'}
Traceback (most recent call last):
  File "test.py", line 27, in <module>
    f()
  File "test.py", line 21, in f
    if x==3:
UnboundLocalError: local variable 'x' referenced before assignment
Related