Skip to content

Commit

Permalink
pythongh-113212: Document zero-arg super() inside nested functions …
Browse files Browse the repository at this point in the history
…and generator expressions
  • Loading branch information
WolframAlph committed Dec 20, 2023
1 parent 09d3ddb commit 4973555
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Doc/library/functions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <descriptor>`
in a parent or sibling class.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
improve :py:class:`super` error message && document zero-arg :py:class:`super` inside nested
functions and generator expressions

0 comments on commit 4973555

Please sign in to comment.