I'm getting returned a list with objects that have multiple attributes like so:
results = q.fetch(5)
for p in results:
print "%s %s, %d inches tall" % (p.first_name, p.last_name, p.height
Is it possible to iterate over these attributes so I can do something like for x in p
. I want to check the value of each one, but I don't want to create a huge block of IF statements.
You can subclass the original variable type, and define your own cunning iter(self) function, to get what you want. e.g. to change the way a dictionary iterates:-
I warn against doing this. There are rare exceptions where it's warranted, but almost all the time it's better avoiding this sort of hackish solution. If you want to though, you could use
vars()
to get a dictionary of attributes and iterate through it. As @Nick points out below, App Engine uses properties instead of values to define its members so you have to usegetattr()
to get their values.Demonstration of what
vars()
does:To get a list of properties on a model class, call
Model.properties()
(orinstance.properties()
- it's a class method). This returns a dictionary mapping property names to Property class instances; you can fetch the value of the properties by doing getattr(instance, name).If you're using
Expando
, there's alsoinstance.dynamic_properties()
, which returns a list of dynamically defined properties on that object.With the assumption that the object you get back from
q.fetch(5)
having a__dict__
attribute, you can simply usepprint
to display your information.Or alternatively, if it has something that can be converted to a dictionary, a similar notation would work
I would suggest though, that this isn't a good approach to take, but it does hold for debugging code easily.