[Tutor] dynamically executing a statement

Emily Fortuna emily.fortuna at nist.gov
Fri Jul 14 17:10:52 CEST 2006


Hello all,
I am writing a function in which (in its simplified form) I am trying to 
return a list of a specified attribute, given a list of objects.  It is 
best if I write some hypothetical code to explain:
class foo:
	def __init__(self, name, data):
		self.name = name
		self.data = data

def getAttrs(fooObjs, attr):
	return map(lambda item: eval('%s.%s' % (item, attr)), fooObjs)

f = foo('oscar', 'green')
g = foo('bert', 'yellow')
e = foo('ernie', 'orange')
list = [f, e, g]
getNames(list, 'name')
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 2, in getNames
   File "<interactive input>", line 2, in <lambda>
   File "<string>", line 1
     <__main__.foo instance at 0x00F358F0>.name
     ^
SyntaxError: invalid syntax

It seems to me like the issue is that Python is converting my object to 
a string representation before attempting to evaluate the expression. 
However, when I looked at the documenation 
[http://docs.python.org/lib/typesseq-strings.html] (thanks from earlier 
post today), I couldn't find anything that would allow python to 
reference the object itself in a string.  Is there a way (or a different 
method entirely) to do this?
Your help is very much appreciated,
Emily



More information about the Tutor mailing list