[Tutor] Issue with iterating within lists, objects and functions

Kent Johnson kent37 at tds.net
Fri Aug 3 13:06:19 CEST 2007


Andy Cheesman wrote:
> for thing in ["top", "right", "bottom", "left"]:
> 	eval("self." + thing).append("fish")

You don't need to use eval() here, use getattr() instead:
getattr(self, thing).append('fish')

> 	eval("self." + thing +"_extra")
> 	eval("self." + thing) = external_function(eval("self." + thing)) #This
> falls

It would help if you said *how* it fails - the specific error message 
and traceback. I guess it is failing on the left side of the assignment, 
not the function call. The result of eval("self." + thing) is the value 
of self.thing, not an assignable reference. You should use getattr() and 
setattr() here:

new_value = external_function(getattr(self, thing))
setattr(self, thing, new_value)

or in one line if you like:
setattr(self, thing, external_function(getattr(self, thing)))

http://docs.python.org/lib/built-in-funcs.html

Kent


More information about the Tutor mailing list