[Tutor] creating variables at runtime

alan.gauld@bt.com alan.gauld@bt.com
Sun, 27 Jan 2002 19:45:36 -0000


> Is is possible in python to create variables at runtime?

Yes. But...

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

I would very strongly recommend using a dictionary instead:

myClasses = {}   # empty dict

for class in range(5):
   name = raw_input('Gimme a name ')
   myClasses[name] = MyClass()

Now we have 5 named instances of MyClass in 
myClasses dictionary. We access like so:

for name in myClasses.keys(): print name  # show me the names

name = raw_input('Which one? ')
print myClasses[name]

and so on...

[ FWIW Thats pretty much what Python does under the 
covers when you create variables in your code - it 
sticks them in a sdictionary. When you use dir() you 
ask Python to list the names... ]


Alan g