[Tutor] dynamically executing a statement

Kent Johnson kent37 at tds.net
Fri Jul 14 19:05:57 CEST 2006


Emily Fortuna wrote:
> 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. 
>   
Yes, that is correct. When you execute
'%s' % f
you get a string containing a string representation of f. It doesn't 
really make sense (to me, anyway) to talk about referencing "the object 
itself" in a string - a string can't contain a reference, it is just text.

You would have to make a list of *names* for your solution to work, e.g.
list = ['f', 'g', 'e']
Then the eval would be something like eval('f.name') which would work.

But in general it's better to use Python's built-in introspection for 
something like this. Fabrizio has shown one way. I would use a list 
comprehension instead of map and lambda:
def getAttrs(fooObjs, attr):
         return [getattr(item, attr) for item in fooObjs]

(Docs for getattr() and other handy built-in functions are here: 
http://docs.python.org/lib/built-in-funcs.html)

Kent
> 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
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   




More information about the Tutor mailing list