Variable interpolation question
antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Mon Nov 17 20:44:17 CET 2003
Bengt Richter wrote:
> On Mon, 17 Nov 2003 20:47:51 +0300, anton muhin <antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru> wrote:
>>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,
>>>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
>>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'
> Or why use an "== 0" test when just hasattr tests for presence/absence without using up
> a possible value of the attribute for flag purposes?
> Bengt Richter
Of course you're right, I just forgot it and thought that OP wants to
verify attribute's presence as well---mea culpa.
More information about the Python-list