namespaces and eval

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Fri May 16 17:08:28 EDT 2008


On 16 mai, 20:44, dave.g1... at gmail.com wrote:
> Suppose I have a function in module X that calls eval e.g,
>
> X.py
> _______
> Def foo(bar):
>         Eval(bar)
> _______
>
> Now eval will be called using the default eval(bar,globals(),locals())
> and globals will pull in anything in module X.
>
> Now I have module Y that calls bar like so
> Y.py
> ________
> from x import *
> def biz():
>         print "Im a silly example!"
> Foo("biz()")
> _______
>
> Python will complain that it cannot find biz because it's not the X
> module.

I'm afraid you're using the wrong tool here. Just try this:

# module x
def foo(bar):
    bar()

# module y
from x import foo
def baaz():
    print "in y.baaz"

foo(baaz)

Remember that in Python, everything (at least, everything you can bind
to a nme) is an object, including functions, classes and modules. And
that every name lives in a namespace, that can be inspected somehow
(using globals() and locals(), but also using getattr() or some
function from the inspect module). IOW, when you think that eval() (or
exec()) is what you need, odds are there's a way better solution.
FWIW, I must have used exec twice and eval thrice in 7+ years of
Python programming - and believe me, I'm not afraid of wizardry and
black magic.





More information about the Python-list mailing list