Generate variables at run time?

Marko junkthis at blueyonder.co.uk
Wed Jan 8 23:10:14 CET 2003


Byron Morgan wrote:
> 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.
>
> Byron

As others have already pointed out you could use dicts or classes for this.
However, you might not be aware that setattr and delattr also work at module
level, so you could also do this:

new_var_name = "abc"
setattr(sys.modules[__name__], new_var_name, "123")

...which obviously creates a variable called abc with the value 123. You can
then delete it with:

delattr(sys.modules[__name__], new_var_name)

I personally don't think this is the most elegant solution and I would
suggest using dictionaries instead, but it does work this way too.

HTH
Marko






More information about the Python-list mailing list