Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

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

Merged
merged 3 commits into from
Feb 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Doc/reference/datamodel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1988,8 +1988,8 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.

.. method:: object.__dir__(self)

Called when :func:`dir` is called on the object. A sequence must be
returned. :func:`dir` converts the returned sequence to a list and sorts it.
Called when :func:`dir` is called on the object. An iterable must be
returned. :func:`dir` converts the returned iterable to a list and sorts it.


Customizing module attribute access
Expand All @@ -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,
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
function overrides the standard :func:`dir` search on a module.

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,14 @@ def __dir__(self):
self.assertIsInstance(res, list)
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)
class Foo(object):
def __dir__(self):
Expand Down