Skip to content

Commit

Permalink
Add Self misuse to common issues (python#18261)
Browse files Browse the repository at this point in the history
This has come up at least a half dozen times on the tracker
  • Loading branch information
hauntsaninja authored Dec 10, 2024
1 parent 6427ef1 commit 1497407
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions docs/source/common_issues.rst
Original file line number Diff line number Diff line change
Expand Up @@ -819,3 +819,30 @@ This is best understood via an example:
To get this code to type check, you could assign ``y = x`` after ``x`` has been
narrowed, and use ``y`` in the inner function, or add an assert in the inner
function.

.. _incorrect-self:

Incorrect use of ``Self``
-------------------------

``Self`` is not the type of the current class; it's a type variable with upper
bound of the current class. That is, it represents the type of the current class
or of potential subclasses.

.. code-block:: python
from typing import Self
class Foo:
@classmethod
def constructor(cls) -> Self:
# Instead, either call cls() or change the annotation to -> Foo
return Foo() # error: Incompatible return value type (got "Foo", expected "Self")
class Bar(Foo):
...
reveal_type(Foo.constructor()) # note: Revealed type is "Foo"
# In the context of the subclass Bar, the Self return type promises
# that the return value will be Bar
reveal_type(Bar.constructor()) # note: Revealed type is "Bar"

0 comments on commit 1497407

Please sign in to comment.