[Tutor] Creating an Identifier or Object Name from a String?

Daniel Yoo dyoo at cs.wpi.edu
Sat Feb 10 23:04:51 CET 2007


>> I thought when I read the 2002 thread with the subject (Creating an 
>> Identifier or Object Name from a String?), that I had found a solution 
>> to my problem.

Wait.  But what was the solution you ended with?  If the conclusion of 
that thread was to use eval(), then that was the wrong lesson, and you 
needed to read more.  *grin*


Read the thread in its entirety:

    http://mail.python.org/pipermail/tutor/2002-June/014923.html

The resolution should have been: don't use eval to dynamically create 
variable names from string.  Rather, keep all the new instances in a 
dictionary that's keyed by those strings.  Avoid eval unless you really 
understand what you're doing.


Avoid the very real dangers in eval():

* It's inconvenient.  You can't create variables like with names that
   you'd like:

#################################################################
>>> class Person:
...     def __init__(self, name):
...         self.name = name
...
>>> names = ['carmen sandiego', 'eva_luator']
>>> for n in names:
...     exec("%s = Person('%s')" % (n, n))
...
Traceback (most recent call last):
   File "<stdin>", line 2, in ?
   File "<string>", line 1
     carmen sandiego = Person('carmen sandiego')
                   ^
SyntaxError: invalid syntax
#################################################################

because Python's variable names are not allowed to have spaces in them.


In contrast:

############################
>>> people = {}
>>> for n in names:
...     people[n] = Person(n)
...
>>> people.keys()
['carmen sandiego', 'eva_luator']
#############################

just works, and anyone with elementary knowledge of dictionaries will know 
exactly what this is doing.  The code ends up simpler because it 
eliminates the need to construct some string to eval or execute that 
quotes its arguments correctly.


* It's insecure.  See:
   http://mail.python.org/pipermail/tutor/2004-December/033844.html



More information about the Tutor mailing list