eval

Alex Martelli alex at magenta.com
Fri Jul 7 05:18:54 EDT 2000


Johannes Zellner <johannes at zellner.org> wrote in message
news:Pine.LNX.4.21.0007070112170.6842-100000 at krispc6.physik.uni-karlsruhe.de
...
    [snip]
> And how do I define the scope where exec evaluates ?

    exec "whateveryouwant" in whateverdictionaryyouwanttouse

or if you want to use different dictionaries for globals and locals,

    exec "whateveryouwant" in aglobaldict,alocaldict

> E.g.
>
> def generator(x):
>   eval 'def '+x+'(y): print "fred"'

I'm confused.  eval is a function (which also takes dictionaries
for globals and locals as 2nd and 3rd args, as well as the
expression as the 1st arg) and does not support this syntax.
Why would you want to use eval rather than exec here, anyway?


> and after calling
> >>> generator('lola')
> I want to be able to use
> >>> lola('lolita')

Decide which module you want to affect and use its __dict__.

For example, if your generator must inject names as pseudo-builtins,
you might make it work with something like:

def generator(x):
    import __builtin__
    exec 'def '+x+'(y): print "fred"' in __builtin__.__dict__


Alex






More information about the Python-list mailing list