Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why can't I modify the current scope within a function using locals()?

Why does creating/modifying a member of locals() not work within a function?

Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> # Here's an example of what I expect to be possible in a function:
>>> a = 1
>>> locals()["a"] = 2
>>> print a
2

>>> # ...and here's what actually happens:
>>> def foo():
...  b = 3
...  locals()["b"] = 4
...  print b
...
>>> foo()
3
like image 391
RobM Avatar asked Mar 21 '26 08:03

RobM


1 Answers

Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the documentation warns.

like image 77
Devin Jeanpierre Avatar answered Mar 23 '26 22:03

Devin Jeanpierre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!