in python what\'s the difference between dir()
function and __dir__
attribute in python?
&
It's worth pointing out that the __dir__
on many objects cannot be customized, so if you call it directly there is no opportunity to place a shim/wrapper in there.
It's easy to replace the builtin dir
and give it some special powers if you need to. Tricks like this can be very useful when debugging.
dir
calls __dir__
internally:
In [1]: class Hello():
...: def __dir__(self):
...: return [1,2,3]
...:
In [2]: dir(Hello())
Out[2]: [1, 2, 3]
The docs explain it:
If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.
If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().
dir calls __dir__
method if it is present,
from python documentation :
dir([object])¶ Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
If the object has a method named
__dir__()
, this method will be called and must return the list of attributes. This allows objects that implement a custom__getattr__()
or__getattribute__()
function to customize the waydir()
reports their attributes.If the object does not provide
__dir__()
, the function tries its best to gather information from the object’s__dict__
attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom__getattr__()
.