From 4973555d982f9427cd9ae80bf7f1ce960b7956c4 Mon Sep 17 00:00:00 2001 From: Yan Yanchii Date: Wed, 20 Dec 2023 09:11:18 +0100 Subject: [PATCH] gh-113212: Document zero-arg `super()` inside nested functions and generator expressions --- Doc/library/functions.rst | 24 +++++++++++++++++++ ...-12-20-08-54-54.gh-issue-113212.62AUlw.rst | 2 ++ 2 files changed, 26 insertions(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2023-12-20-08-54-54.gh-issue-113212.62AUlw.rst diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index c731b6fd3332753..cd736297c0a1e36 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -1822,6 +1822,30 @@ are always available. They are listed here in alphabetical order. super().method(arg) # This does the same thing as: # super(C, self).method(arg) + .. warning:: + By default, if no second argument is provided, :func:`super` uses first argument + of immediately enclosing function definition which is `self` under normal circumstances. + This may lead to unexpected behaviour if used inside nested functions or generator expressions + as the latter creates implicit nested function. Following example will result in exception:: + + class A: + def method(self): + return 1 + + class B(A): + def method(self): + return list(super().method() for _ in range(3)) # Expected [1, 1, 1] but TypeError will be raised. + + In such cases, you should provide arguments explicitly:: + + class A: + def method(self): + return 1 + + class B(A): + def method(self): + return list(super(B, self).method() for _ in range(3)) # Will return [1, 1, 1]. + In addition to method lookups, :func:`super` also works for attribute lookups. One possible use case for this is calling :term:`descriptors ` in a parent or sibling class. diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-12-20-08-54-54.gh-issue-113212.62AUlw.rst b/Misc/NEWS.d/next/Core and Builtins/2023-12-20-08-54-54.gh-issue-113212.62AUlw.rst new file mode 100644 index 000000000000000..f9c9d843b279fd3 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-12-20-08-54-54.gh-issue-113212.62AUlw.rst @@ -0,0 +1,2 @@ +improve :py:class:`super` error message && document zero-arg :py:class:`super` inside nested +functions and generator expressions