Python Forum

Full Version: modifying variables in local or global space
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
(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': {...}}
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.