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?
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')