Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

typing.Self

Refer to the current class as specialized for the receiver, so inherited fluent methods preserve the subclass in static analysis.

Version: Python 3.14; repository image, production runtime not attested

Syntax

def reset(self) -> Self: ...

Refer to the current class as specialized for the receiver, so inherited fluent methods preserve the subclass in static analysis.

A class method can also return Self when it constructs an instance with cls. Returning a fixed base-class instance from an inherited method violates that promise for subclass callers.

Python does not enforce the annotation.

Examples

from typing import Self
class Box:
    @classmethod
    def empty(cls) -> Self:
        return cls()
    def reset(self) -> Self:
        return self
    def wrong(self) -> Self:
        return Box()
class Crate(Box):
    pass
item = Crate.empty()
print(type(item).__name__, item.reset() is item, type(item.wrong()).__name__)

Result

Crate True Box

Python does not enforce the annotation.

Sources