+ 2
Updating locals() in python
I know that the docs specify that changes to locals() will have no effect, but im curious to know why. Is there any specific reason behind it? https://code.sololearn.com/cv6F0zIprxNT/?ref=app
11 Antworten
+ 4
Yohanan,
Python bytecode references locals by index, not by name,
therefore all locals must exist at compile-time, then,
function locals are not stored in a dictionary, but an array,
whose indices are determined at compile time from the known locales.
So to modify the locals of a function on the fly is not possible.
+ 12
Yohanan , may be you want to have a look at this article. You will need some time to get it, but do a try:
https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-namespaces-scope/
+ 6
You can’t modify objects in the actual local namespace using the return value from locals():
because, it returns a dictionary that is a current copy of the local namespace, not a reference to it.
Only the globals() returns a reference to the global namespace dictionary, and you could do the same thing using globals():
def f():
globals() ['x'] = 7
globals() ['x'] += 8
print(x)
f()
print(x)
>>>
15
15
+ 4
Regarding your code above, I hope this helps you:
https://code.sololearn.com/c29cAQn720j1/?ref=app
+ 3
Lothar Thanks! Will give it a try
+ 3
Vitaly Sokol, but why doesn't locals() return a reference to the local namespace?
Is there any specific reason behind it?
+ 3
At class scope, locals() must return the local namespace that will be passed to the metaclass constructor.
Variable assignments during code execution in the class scope must change the contents of the returned mapping, and changes to the returned mapping must change the values bound to local variable names in the execution environment (the class creation process will copy the contents to a fresh dictionary that is only accessible by going through the class machinery).
see the documentation:
https://www.python.org/dev/peps/pep-0558/
+ 2
Vitaly Sokol thanks, i guess thats what i needed.
+ 1
But, why do functions use such a non-obvious way of accessing variables?
I mean classes don't do it:
class abc:
locals['a'] = 7
print(abc.a) # prints 7
Is there any deeper reason behind it?
+ 1
Also, if locals() returns a copy of the local scope, then why does it behave a bit differently?
https://code.sololearn.com/cTiakVisvs5u/?ref=app
0
So, all calls to locals() return the same dictionary, but that dictionary is the copy of the local namespace. Am i right?