Skip to content

Commit cba55de

Browse files
committed
gh-113212: Document zero-arg super() inside nested functions and generator expressions
1 parent 3b7e6fd commit cba55de

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Doc/library/functions.rst

+23
Original file line numberDiff line numberDiff line change
@@ -1845,6 +1845,29 @@ are always available. They are listed here in alphabetical order.
18451845
:func:`super`, see `guide to using super()
18461846
<https://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_.
18471847

1848+
.. note::
1849+
By default, if no second argument is provided, :func:`super` uses the first argument
1850+
of the immediately enclosing function definition, which is ``self`` under normal circumstances.
1851+
This may lead to unexpected behaviour if used inside nested functions or generator expressions
1852+
(the latter creates implicit nested functions). The following example will result in an exception::
1853+
1854+
class A:
1855+
def method(self):
1856+
return 1
1857+
1858+
class B(A):
1859+
def method(self):
1860+
return list(super().method() for _ in range(3)) # Expected [1, 1, 1] but TypeError will be raised.
1861+
1862+
In such cases, you should provide arguments explicitly::
1863+
1864+
class A:
1865+
def method(self):
1866+
return 1
1867+
1868+
class B(A):
1869+
def method(self):
1870+
return list(super(B, self).method() for _ in range(3)) # Will return [1, 1, 1].
18481871

18491872
.. _func-tuple:
18501873
.. class:: tuple()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
improve :py:class:`super` error message && document zero-arg :py:class:`super` inside nested
2+
functions and generator expressions

0 commit comments

Comments
 (0)