[Tutor] atr in dir Vs. hasattr

Steven D'Aprano steve at pearwood.info
Wed Mar 16 14:12:18 CET 2011

Tim Johnson wrote:
>  What is the difference between using
>  hasattr(object, name)
>  and
>  name in dir(object)
>  ?

Did you read the Fine Manual?


"The default dir() mechanism behaves differently with different types of 
objects, as it attempts to produce the most relevant, rather than 
complete, information: ...
Note: Because dir() is supplied primarily as a convenience for use at an 
interactive prompt, it tries to supply an interesting set of names more 
than it tries to supply a rigorously or consistently defined set of 
names, and its detailed behavior may change across releases."

And here's an example:

 >>> class C(object):
...     pass
 >>> hasattr(C, '__eq__')
 >>> '__eq__' in dir(C)


More information about the Tutor mailing list