[Tutor] creating variables at runtime

Paul Sidorsky paulsid@shaw.ca
Wed, 23 Jan 2002 21:58:18 -0700


David Maclagan wrote:

> What I'm wanting to do is create instances of classes, given names
> based on user input
> 
> ie
> userinput = "NARF"
> 
> (something done to userinput) = MyClass(), such that NARF will be an
> instance of MyClass.
> Is such a thing possible? 

This is indeed doable:

>>> class MyClass: pass

>>> userinput = "NARF"
>>> exec(userinput + " = MyClass()")
>>> NARF
<__main__.MyClass instance at 00B59A8C>
>>> 

> Is it Bad and Wrong?

I'm not qualified to comment on the rightness of it, but here's a
technical point of view:

It sounds like the program will probably need to keep track of all of
these names (like NARF) to refer back to them later.  Thus there is now
have a bunch of names and associated with each name is an instance of a
class.  Whenever I get a situation like this, I immediately think
DICTIONARY!  This may be more feasible:

>>> instances = {}
>>> instances[userinput] = MyClass()
>>> instances
{'NARF': <__main__.MyClass instance at 00B6172C>}
>>> instances["NARF"]
<__main__.MyClass instance at 00B6172C>

No munging is required either, other than possibly checking if userinput
is already in instances.keys() (or just instances in Python 2.2) before
storing.

Of course I don't know what the intentions are here, so if some special
requirement is involved then just ignore this part.

-- 
======================================================================
Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/