Variable interpolation question
anton muhin
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Mon Nov 17 12:47:51 EST 2003
Andrew Fabbro wrote:
> This is probably a beginner's question, but I'm stuck...please be kind
> to an ex-perler ;)
>
> How do I do something like this:
>
> for attr in dir(some_obj):
> if ( some_obj.attr == 0 ):
> print "Missing data: %s field %s" % ( some_obj.name,
> some_obj.attr)
>
> Of course, this gives
> "AttributeError: foo instance has no attribute 'attr'"
>
> I really don't want to use exec/eval, as that slows things down
> dramatically.
>
> Help?
>
> Thanks.
>
> -Drew
You are probably looking for hasattr/getattr functions:
for attr in dir(some_obj):
if hasattr(some_obj, attr) and getattr(some_obj, attr) == 0:
print 'blah...'
of course, it could be shorter:
....
if getattr(some_obj, attr, 0) == 0:
print 'blah'
regards,
anton.
More information about the Python-list
mailing list