PEP 562: “The __dir__
function should accept no arguments, and return a list of strings that represents the names accessible on module. If present, this function overrides the standard dir() search on a module.”
Canonical Docs: “The __dir__
function should accept no arguments, and return an iterable of strings that represents the names accessible on module. If present, this function overrides the standard dir() search on a module.”
dir(): “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. […] The resulting list is sorted alphabetically”
There’s a few discrepancies here. The original PEP states that __dir__()
must return a list while the canonical docs changed it to any iterable. Both of them state that “this function overrides the standard dir() search on a module”, which gave me the impression that if I implement __dir__
, builtins.dir
will simply return the output of my implementation.
$ echo "def __dir__(): return 'new_attr', 'deprecated_attr'" > a.py
$ python -q
>>> import a
>>> a.__dir__()
('new_attr', 'deprecated_attr')
>>> dir(a)
['deprecated_attr', 'new_attr']
>>> a.__dir__() == dir(a)
False
Maybe I’m not understanding the docs all too well but the fact that obj.__dir__
and dir(obj)
can give me different results caught me off guard. The only hint of this behaviour is mentioned in the docs for builtins.dir, where it states that the result will be a sorted list, presumably it does something like this (pseudocode):
def dir(obj):
return sorted(obj.__dir__())
This ends up both type casting the original to a list and changing the order (as shown in the example, deprecated_attr is now on the front).
I’m not entirely sure if this is just my failure of understanding the docs or not, so I thought I’ll bring it up. This isn’t really mission critical to my code, so I can live with it but I’m curious to hear some opinions.