[Tutor] Convert string to variable name

Alan Gauld alan.gauld at freenet.co.uk
Thu Jan 27 10:21:51 CET 2005


> This is something I've been trying to figure out for some time.  Is
> there a way in Python to take a string [say something from a
> raw_input] and make that string a variable name?  I want to to this
so
> that I can create class instances on-the-fly, using a user-entered
> string as the instance name.

This comes up regularly from beginners and is nearly always a bad
idea!

The easy solution is to use a dictionary to store the instances.
See the OOP topic in my tutor for an example using bankAccounts
as the objects...

> could accomplish something similar using a plain old dictionary, but
I
> was playing around with the OOP stuff and thought it might be a neat
> thing to try out.

A Dictionary is best. The problem is, once you create your new
variables none of the rest of your code knows aout them so
how can it access them. And what if someone enters a name that
is being iused elsewhere in your code? You will overwrite a
real variable with this new object! Very tricky to control.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list