New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unexpected behaviour of dir()
after implementation of __dir__
#75997
Comments
When defining a custom __dir__ method in a class, calling dir() on Example and more detail here |
dir() and __dir__ work as designed and documented: https://docs.python.org/3/reference/datamodel.html?highlight=__dir__#object.\_\_dir__ Called when dir() is called on the object. A sequence must be returned. dir() converts the returned sequence to a list and sorts it |
Alright. Are there any other magic methods that do some post-processing on a custom implementation of them ? I couldn't think of one, which is why this behaviour appeared odd to me. |
https://docs.python.org/3/library/functions.html#dir also states that "The resulting list is sorted alphabetically." The section has an example where __dir__ returns an unsorted list but dir() returns a sorted list: >>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter'] Since the primary purpose of dir() is convenient use for humans, sorting makes perfectly sense. If you need tight control over order of values, you should make your object iterable instead or provide another method. Several dunder methods perform some sort of post-processing or post-check: >>> class Example:
... def __bool__(self): return 2
...
>>> bool(Example())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __bool__ should return bool, returned int
>>> class MyInt(int):
... pass
...
>>> type(MyInt(1))
<class '__main__.MyInt'>
>>> class Example:
... def __int__(self):
... return MyInt(1)
...
>>> int(Example())
1
>>> type(int(Example()))
<class 'int'> |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: