Reputation: 705
In the following wrapped function:
def info(self):
a = 4
def _inner():
b = 5
print ('LOCALS',locals())
print ('GLOBALS', globals())
_inner()
It prints the following in python3.6
:
LOCALS {'b': 5}
GLOBALS {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'info': <function info at 0x1029d3598>}
Why isn't a
, the free variable, included in the _inner
locals()
? From the docs it says:
locals()
Update and return a dictionary representing the current local symbol table. Free variables are returned by
locals()
when it is called in function blocks, but not in class blocks.
Additionally, are class variables always hidden from locals()
? For example:
class X:
b = 2
def info(self):
a = 3
print (locals())
>>> X().info()
{'a': 3, 'self': <__main__.X object at 0x102aa6518>}
Upvotes: 1
Views: 680
Reputation: 136
Free variables are returned, the docs aren't wrong… but a free variable only exists for the inner function if it's used in it. Otherwise it's not loaded into the local scope. Try adding a simple b += a
right after b = 5
and you're gonna see LOCALS {'b': 9, 'a': 4}
printed, just the way you expected.
As for class (and instance) variables, the above applies all the same, but with one caveat: these variables must be accessed through the self
(or cls
) object and that is what will show up in locals()
instead.
Upvotes: 2