setting variables in the local namespace

Mel mwilson at the-wire.com
Tue Oct 13 13:45:59 EDT 2009


Chris Withers wrote:

> - what is so wrong with wanting to set a variable in the local namespace
> based on a name stored in a variable?

What's wrong is that no other statement using the local name space can know 
what that name might be.  It's a documented fact that changing the locals() 
dictionary doesn't feed back to the users of the namespace:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...   foo=0
...   globals()['foo'] = 'bar'
...   return foo
... 
>>> f()
0

For the reasons Gabriel gave outside the thread.

You can actually assign into a local namespace using exec:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def g(s):
...   exec (s)
...   return a
... 
>>> g('a=4')
4

But look at the dependency you'll create between the function's code and the 
incoming data stream:

>>> g('b=5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in g
NameError: name 'a' is not defined


Once you start naming local variables at run-time, you pretty much commit to 
writing the entire function at run-time.  Better to use a dictionary.

	Mel.




More information about the Python-list mailing list