From 0e936d719a92eca2b264b56b858bf03d6cb3e583 Mon Sep 17 00:00:00 2001 From: sobolevn Date: Sat, 27 Jan 2024 23:17:24 +0300 Subject: [PATCH 1/3] gh-114552: Update `__dir__` method docs: it allows returning an iterable --- Doc/reference/datamodel.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 0a1c1d58558e94..898b5069598b5b 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -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 From 5e77417032f8244d6731f861fb72ee298f9fc58c Mon Sep 17 00:00:00 2001 From: sobolevn Date: Sun, 28 Jan 2024 00:22:08 +0300 Subject: [PATCH 2/3] 2012 --- Doc/reference/datamodel.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 898b5069598b5b..885ee825c12296 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -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. From 965623e8e15476c47ed177ab2805b2fdc8484404 Mon Sep 17 00:00:00 2001 From: sobolevn Date: Sun, 28 Jan 2024 00:58:28 +0300 Subject: [PATCH 3/3] Add a test --- Lib/test/test_builtin.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index fcddd147bac63e..7a3ab2274a58f2 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -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):