exec and globals and locals ...
jfong at ms4.hinet.net
jfong at ms4.hinet.net
Thu Sep 19 23:23:43 EDT 2019
>>> x = 3
>>> def foo():
... exec("print(globals(), locals()); x = x + 1; print(globals(), locals())")
...
>>> foo()
{'foo': <function foo at 0x021C3468>, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__spec__': None, 'x': 3} {}
{'foo': <function foo at 0x021C3468>, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__spec__': None, 'x': 3} {'x': 4}
>>> def goo():
... print(globals(), locals())
... x = x + 1
... print(globals(), locals())
...
>>> goo()
{'foo': <function foo at 0x021C3468>, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None, '__name__': '__main__', '__spec__': None, 'goo': <function goo at 0x021C3420>, 'x': 3} {}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in goo
UnboundLocalError: local variable 'x' referenced before assignment
>>>
Can't figure out what makes it different:-(
--Jach
More information about the Python-list
mailing list