2

Every object has a __dir__ attribute, will the command stop if extra .__dir__ references are appended?

>>> dir(''.__dir__)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

and,

>>> dir(''.__dir__.__dir__.__dir__.__dir__)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

will it stop when enough '.dir' are appended?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    Well, if you use a heck of a lot of calls to `__dir__`, you'll eventually clutter the memory, and the execution'll possibly stop. – ForceBru Aug 08 '17 at 15:00

1 Answers1

7

You are taking the dir() of the __dir__ attribute, which is a builtin_function_or_method object, which has a __dir__ attribute. So yes, you can chain those __dir__ attribute lookups endlessly, because the result will always be the same; a bound method object:

>>> ''.__dir__.__dir__
<built-in method __dir__ of builtin_function_or_method object at 0x10672cfc0>
>>> ''.__dir__.__dir__.__dir__
<built-in method __dir__ of builtin_function_or_method object at 0x1067361f8>

Every object in Python has a __dir__ attribute, it is always a callable.

Note: the way you strung the attribute lookups keeps a chain of bound method objects alive, so you will eventually run out of memory; each __dir__ method wrapper references the preceding one in their __self__ attribute.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • suffix to repeat any '__someAttribute__' is endless call its returned value's attributes. –  Aug 08 '17 at 15:18
  • May an object not have a `__dir__`? From the docs: "If the object has a method named `__dir__()`, this method will be called", so it seems to be optional. – VPfB Aug 08 '17 at 15:56
  • 1
    @VPfB: `type` and `object` both implement `__dir__`, so in Python 3, **all** objects have that method. Only Python 2 old-style classes lack the attribute. – Martijn Pieters Aug 08 '17 at 15:57