I want to change the dir()
output for my class. Normally, for all other objects, it's done by defining own __dir__
method in their class. But if I do this for my class, it's not called.
class X(object):def __dir__():raise Exception("No!")>>>dir(X)
['__class__', '__delattr__', '__dict__',....
How can I change the dir()
output for class?
That's because dir
calls the __dir__
of the type of the input (equivalent to: type(inp).__dir__(inp)
). For instances of a class it will call the classes __dir__
but if called on a class it will call the __dir__
of the meta-class.
class X(object):def __dir__(self): # missing self parameterraise Exception("No!")dir(X()) # instance!
# Exception: No!
So if you want to customize dir
for your class (not instances of your class) you need to add a metaclass for your X
:
import sixclass DirMeta(type):def __dir__(cls):raise Exception("No!")@six.add_metaclass(DirMeta)
class X(object):passdir(X)
# Exception: No!