access interactive namespace from module (shared namespace?)

Peter Otten __peter__ at web.de
Sun May 25 06:38:11 EDT 2008


Ulrich Dorda wrote:

> I've got a probably embarrassing trivial problem with namespaces, but
> couldn't solve it myself nor find an answer in the net. Hopefully one of
> you guys can help me.
> 
> What I want to do:
> Use the interactive shell and e.g define the variable a there.
> Then load a module and access a from within.
> 
> e.g file "utest.py"
> 
> def doit():
> print 2*a
> 
> in the shell:
> 
> import utest
> a=3
> utest.doit()  <- I want this to print 2*a, but of course obtain: <type
> exceptions.NameError'>: global name 'a' is not defined
> 
> Any change I do to a in the shell should be seen from the doit() function,
> any variable assignment I do in the doit() function should be seen in the
> shell. I guess it's somehow a namespace sharing.
> 
> Actually the function doit() will contain an eval() function that should
> evaluate a (via a gui) dynamically inserted expression.
> 
> Any one got a clue? (a clue what I try to say and how to help?!)
> 
> Thanks a lot in advance!!

While the sane approach to this is

def doit(a):
    print 2 * a

here is an insane one:

import sys

def f(): pass
function = type(f)

def snatch_globals(f):
    def g(*args, **kw):
        return function(f.func_code, sys._getframe(1).f_globals)(*args,
**kw)
    return g

@snatch_globals
def doit():
    print 2 * a

Peter



More information about the Python-list mailing list