[Tutor] atr in dir Vs. hasattr

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

Tom Zych wrote:

> I suppose there must be some reliable way to get a list of *all* an
> object's attributes, but I don't see it.

Nope, there isn't, because Python allows classes to define arbitrary 
attributes at runtime.

 >>> import random
 >>> class Funny:
...     def __getattr__(self, name):
...        if name == 'weird' and random.random() < 0.5:
...            return "Yes, that's very strange."
...        else:
...            raise AttributeError
 >>> f = Funny()
 >>> f.weird
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 6, in __getattr__
 >>> f.weird
"Yes, that's very strange."

Then add in __getattribute__, inheritance from superclasses, 
metaclasses, custom dictionary types for __dict__ (Python 3 only), and 
descriptors, and, well, there really isn't a guaranteed list of attributes.


More information about the Tutor mailing list