Variable interpolation question
Bengt Richter
bokr at oz.net
Mon Nov 17 14:21:28 EST 2003
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,
>> 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'
>
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?
BTW, The OP might want to note that in general
for attr in dir(some_object):
if getattr(some_obj, attr, 0) == 0:
...
is not the same as (untested)
objdict = vars(some_obj) # vars raises exception if there's no some_obj.__dict__
for attr in objdict:
if objdict[attr] == 0:
...
or, safer, (untested)
objdict = getattr(some_object, '__dict__', {})
for attr in objdict:
if objdict[attr] == 0:
...
or (untested)
for attr in getattr(some_object, '__dict__', {}): ...
if some_obj.__dict__[attr] == 0: ...
...
I.e., dir chases down all the inherited stuff, and getattr invokes all the magic
associated with attribute access, such as properties, whereas just using
some_obj.__dict__ bypasses that.
Regards,
Bengt Richter
More information about the Python-list
mailing list