creating variable in root namespace from module

Duncan Booth duncan.booth at invalid.invalid
Fri Mar 10 16:40:09 EST 2006


MakaMaka wrote:

> Ok, I figured it out.  Thanks for your help guys.  If anybody else is
> searching this group looking for the answer, you want the
> sys._getframe() function.
> 
> sys._getframe(1).f_locals['a'] = 1
> 
> if you put the above in a function in a module, it creates a variable
> 'a' in the namespace of whatever calls the function in the module.  I
> know this may make people cringe, but since I'm trying to basically
> create a language, of which python is a subset, it's actually exactly
> what I need to do.
> 

Err, no. Actually it doesn't:

>>> import sys
>>> def f():
    sys._getframe(1).f_locals['a'] = 1

    
>>> def g():
    a = 0
    print a
    f()
    print a

    
>>> g()
0
0
>>> a = 42
>>> f()
>>> a
1
>>> 

Code like that may sometime update the caller's namespace, but for local 
variables it will usually have no effect. Also, any effect it does have may 
vary wildly across different Python implementations or versions.

In short, don't do that.



More information about the Python-list mailing list