Python Forum
modifying variables in local or global space - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: modifying variables in local or global space (/thread-20490.html)



modifying variables in local or global space - Skaperen - Aug-14-2019

you can't modify variables in local space using they dictionary you get from locals() or the reference you can track down from inspect.currentframe(). is there any way to do this, at all? can globals be safely modified since all the documents that touch on this topic seem to focus only on locals?


RE: modifying variables in local or global space - fishhook - Aug-14-2019

(Aug-14-2019, 03:55 AM)Skaperen Wrote: you can't modify variables in local space using they dictionary you get from locals()

but.... I can

>>> l=locals()
>>> l["foo"] = "bar"
>>> print(locals())
{'__spec__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'foo': 'bar', '__package__': None, '__doc__': None, 'l': {...}}



RE: modifying variables in local or global space - Skaperen - Aug-14-2019

by "can't" i meant that you are not supposed to according to Python documentation. it is CPython specific according to one source. another source said it is something about how compiled code accesses the namespace at runtime. yes, if you try, it looks like it works. it works most of the time. it sometimes fails.