The dir()of a class can be customized by creating a special function which returns a user-defined list, so why does it not maintain the order I specified? Here’s an example:
>>> class C(object):
... def __dir__(self):
... return ['a', 'c', 'b']
...
>>> c = C()
>>> dir(c)
['a', 'b', 'c']
Why is dir() seemingly sorting my list and returning ['a', 'b', 'c'] rather than ['a', 'c', 'b']?
Oddly (to me), calling the member function directly yields the expected results:
>>> c.__dir__()
['a', 'c', 'b']
This is by definition of the
dir()built-in. It explicitly alphabetizes the list of names:Help on built-in function dir in module __builtin__: dir(...) dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.