Create object name from string value?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Jan 21 00:35:54 EST 2010


On Wed, 20 Jan 2010 19:02:49 -0800, Gnarlodious wrote:

> I want to declare several objects from names in a list:
> 
> objects=['object1', 'object2', 'object3', 'object4'] for objectName in
> objects:
> 	objectName=classname()


That's the wrong way to handle the problem. Named objects are only useful 
if you know the name of the object when writing the code. Otherwise, how 
do you know what name to use in the code?


> That fails, and so do these:
> 
> exec(objectName)=classname()
> eval(objectName)=classname()


The right way to solve this problem is with a dictionary:

for name in ["object1", "object2", "object3"]:
    d = {name: classname()}
    print d[name]



but for the record, the way to use exec is like this:

exec("object1 = classname()")

But beware, exec is not only much slower than the alternatives, but it 
risks putting a serious security flaw in your software. As a general 
rule, 9 times out of 10 if you think you want exec, you don't.


-- 
Steven



More information about the Python-list mailing list