gh-114552: Update __dir__ method docs: it allows returning an iterable (#114662)

This commit is contained in:
Nikita Sobolev 2024-02-10 11:34:23 +03:00 committed by GitHub
parent b2d9d134dc
commit e19103a346
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 11 additions and 3 deletions

View file

@ -1988,8 +1988,8 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
.. method:: object.__dir__(self) .. method:: object.__dir__(self)
Called when :func:`dir` is called on the object. A sequence must be Called when :func:`dir` is called on the object. An iterable must be
returned. :func:`dir` converts the returned sequence to a list and sorts it. returned. :func:`dir` converts the returned iterable to a list and sorts it.
Customizing module attribute access Customizing module attribute access
@ -2009,7 +2009,7 @@ not found on a module object through the normal lookup, i.e.
the module ``__dict__`` before raising an :exc:`AttributeError`. If found, the module ``__dict__`` before raising an :exc:`AttributeError`. If found,
it is called with the attribute name and the result is returned. it is called with the attribute name and the result is returned.
The ``__dir__`` function should accept no arguments, and return a sequence of The ``__dir__`` function should accept no arguments, and return an iterable of
strings that represents the names accessible on module. If present, this strings that represents the names accessible on module. If present, this
function overrides the standard :func:`dir` search on a module. function overrides the standard :func:`dir` search on a module.

View file

@ -611,6 +611,14 @@ class BuiltinTest(unittest.TestCase):
self.assertIsInstance(res, list) self.assertIsInstance(res, list)
self.assertTrue(res == ["a", "b", "c"]) self.assertTrue(res == ["a", "b", "c"])
# dir(obj__dir__iterable)
class Foo(object):
def __dir__(self):
return {"b", "c", "a"}
res = dir(Foo())
self.assertIsInstance(res, list)
self.assertEqual(sorted(res), ["a", "b", "c"])
# dir(obj__dir__not_sequence) # dir(obj__dir__not_sequence)
class Foo(object): class Foo(object):
def __dir__(self): def __dir__(self):