Generate variables at run time?

Mike Meyer mwm at mired.org
Wed Jan 8 11:20:10 EST 2003


"Byron Morgan" <lazypointer at yahoo.com> writes:

> Is there any way in Python to generate a new variable name based on data? I
> have tried the eval() function, but this gets rejected, if the variable
> doesn't already exist.
> 
> There has to be a way to do this, but I can't find it, probaly because I am
> just starting to learn Python.

Creating variables in a namespace you're actually using based on data
is a bad idea. What happens if you collide with a variable name that
you're already using?

For that reason, you're better off using a variable to hold the
namespace. The canonical way to do this is with a dictionary, but you
can use an attribute-less class and setattr to add variables to it if
you really want.

If the goal is to get code executed with some variables set from data,
then you can pass a dictionary of name/value pairs to exec or eval
instead. You can even use the current set of globals trivially. You
can merge in the current locals with a bit of work.

Why don't you tell us what you're trying to do, and we can suggest a
way to solve that problem?

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list