Christian Heimes <li...@cheimes.de> added the comment:

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'>

----------
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue31816>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to