newbie wants to eval()

Alex Martelli aleaxit at yahoo.com
Sat Jun 30 17:53:07 EDT 2001


"lynx" <noone at nowhere.net> wrote in message
news:3b3e3e81$0$88189$2c3e98f8 at news.voyager.net...
> i want to iterate over a list of variable names, comparing each in turn
> to a regexp match part, and if the comparison is equal, set the value of
> the variable to the value given in another part of the same regexp
> match; which seems most obviously done with eval().

If it so seems, appearances are deceptive.  eval() evaluates an
EXPRESSION, and variable binding and rebinding is normally done
by assignment, which is a STATEMENT.  In Python expressions and
statements are separate concepts: an expression can always be
used as a statement, but a statement cannot be used as an expression.

You'd need to use the 'exec' statement (shudder), but fortunately
you can easily do better than that, since...:

> one little additional twist is that the variables i'm trying to set are
> globals, defined outside the configuration-file-reading-function itself.
> does this change some argument to the eval(), and if so, how?

Global variables are really attributes of an object, the module
object to be precise.  Setting any object's attributes is most
easily done via built-in function setattr().

So you need a reference to the object that's the module you
want to affect.  Assuming this is the module containing the
function you're writing, simplest may be:
    import sys
    mymod = sys.modules[__name__]
and now mymod is the reference you require.

Now, if your variable x refers to a string that names the variable
you want to set, and y refers to the value you want to bind your
variable to,

    setattr(mymod, x, y)

will do what you require.


Alex






More information about the Python-list mailing list