hasattr() or "x in y"?

Chris Angelico rosuav at gmail.com
Fri Mar 11 17:04:46 EST 2016


On Sat, Mar 12, 2016 at 8:53 AM, Charles T. Smith
<cts.private.yahoo at gmail.com> wrote:
> On Fri, 11 Mar 2016 21:44:27 +0000, Charles T. Smith wrote:
>
>> From the performance point of view, which is better: - hasattr()
>> - x in y
>>
>> TIA
>> cts
>
>
> I just realized that "in" won't look back through the class hierarchy...
> that clearly makes them not interchangable, but given we're only
> interested in the current dict...

They're still completely different - hasattr looks at attributes, but
the 'in' operator looks at the object's members (in the case of a
dictionary, the keys). There is a broad similarity between
"hasattr(obj, attrname)" and "attrname in obj.__dict__", but if you're
doing the latter, you have other problems than performance; attributes
should be looked up as attributes, not as dictionary members.

ChrisA



More information about the Python-list mailing list