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

Skip to content

Commit e19103a

Browse files
authored
gh-114552: Update __dir__ method docs: it allows returning an iterable (#114662)
1 parent b2d9d13 commit e19103a

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

Doc/reference/datamodel.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1988,8 +1988,8 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
19881988

19891989
.. method:: object.__dir__(self)
19901990

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

19941994

19951995
Customizing module attribute access
@@ -2009,7 +2009,7 @@ not found on a module object through the normal lookup, i.e.
20092009
the module ``__dict__`` before raising an :exc:`AttributeError`. If found,
20102010
it is called with the attribute name and the result is returned.
20112011

2012-
The ``__dir__`` function should accept no arguments, and return a sequence of
2012+
The ``__dir__`` function should accept no arguments, and return an iterable of
20132013
strings that represents the names accessible on module. If present, this
20142014
function overrides the standard :func:`dir` search on a module.
20152015

Lib/test/test_builtin.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,14 @@ def __dir__(self):
611611
self.assertIsInstance(res, list)
612612
self.assertTrue(res == ["a", "b", "c"])
613613

614+
# dir(obj__dir__iterable)
615+
class Foo(object):
616+
def __dir__(self):
617+
return {"b", "c", "a"}
618+
res = dir(Foo())
619+
self.assertIsInstance(res, list)
620+
self.assertEqual(sorted(res), ["a", "b", "c"])
621+
614622
# dir(obj__dir__not_sequence)
615623
class Foo(object):
616624
def __dir__(self):

0 commit comments

Comments
 (0)