Typing Self, override and deprecated

suggest change

Three small additions to Python's typing make class hierarchies easier to annotate and maintain:

All three are no-ops or close to it at runtime. Most of their value comes from a type checker, so the examples show what mypy and pyright report. Examples were run with Python 3.13.15, mypy 2.4.0 and pyright 1.1.414. Absolute paths in the checker output were shortened to the file name.

For basics of annotating classes see Class Members and Methods. Overriding itself is covered in Method Overriding, and @classmethod constructors in Class methods alternate initializers.

The problem Self solves

A fluent (chainable) method returns self. Annotating it with the class name looks right, but it breaks in subclasses:

class Shape:
    def __init__(self) -> None:
        self.color = "black"

    def set_color(self, color: str) -> "Shape":
        self.color = color
        return self

class Circle(Shape):
    def __init__(self) -> None:
        super().__init__()
        self.radius = 1.0

    def set_radius(self, r: float) -> "Circle":
        self.radius = r
        return self

c = Circle().set_color("red").set_radius(2.5)
print(type(c).__name__, c.color, c.radius)
Circle red 2.5

The code runs fine, but set_color is declared to return Shape, so the checker forgets that the object is a Circle:

$ mypy s1.py
s1.py:18: error: "Shape" has no attribute "set_radius"  [attr-defined]
Found 1 error in 1 file (checked 1 source file)

$ pyright s1.py
s1.py:18:31 - error: Cannot access attribute "set_radius" for class "Shape"
    Attribute "set_radius" is unknown (reportAttributeAccessIssue)
1 error, 0 warnings, 0 informations

Returning Self

Replace the class name with Self. It means "the type of the object this method was called on":

from typing import Self, reveal_type

class Shape:
    def __init__(self) -> None:
        self.color = "black"

    def set_color(self, color: str) -> Self:
        self.color = color
        return self

class Circle(Shape):
    def __init__(self) -> None:
        super().__init__()
        self.radius = 1.0

    def set_radius(self, r: float) -> Self:
        self.radius = r
        return self

c = Circle().set_color("red").set_radius(2.5)
reveal_type(Circle().set_color("red"))
print(type(c).__name__, c.color, c.radius)
Runtime type is 'Circle'
Circle red 2.5

reveal_type can be imported from typing since Python 3.11. At runtime it prints the actual type to stderr, and type checkers print the inferred type:

$ mypy s2.py
s2.py:21: note: Revealed type is "s2.Circle"
Success: no issues found in 1 source file

$ pyright s2.py
s2.py:21:13 - information: Type of "Circle().set_color("red")" is "Circle"
0 errors, 0 warnings, 1 information

self doesn't need an annotation. The other common place for -> Self is __enter__ in context managers, which usually ends with return self.

The pre-3.11 spelling

Before Self, the same thing needed a TypeVar bound to the class, with self annotated explicitly:

from typing import TypeVar, reveal_type

TShape = TypeVar("TShape", bound="Shape")

class Shape:
    def set_color(self: TShape, color: str) -> TShape:
        self.color = color
        return self

class Circle(Shape):
    pass

reveal_type(Circle().set_color("red"))
Runtime type is 'Circle'

Both checkers infer Circle here too. Self is shorter, needs no module-level TypeVar, and can't be bound to the wrong class by mistake.

Self in class methods and parameters

In a @classmethod, Self is the type of cls(). That makes alternate constructors return the subclass when called on a subclass. In parameters, Self means "the same type as the receiver":

from dataclasses import dataclass
from typing import Self, reveal_type

@dataclass
class Money:
    cents: int

    @classmethod
    def from_str(cls, text: str) -> Self:
        dollars, _, cents = text.partition(".")
        return cls(int(dollars) * 100 + int(cents or 0))

    @classmethod
    def zero(cls) -> Self:
        return cls(0)

    def __add__(self, other: Self) -> Self:
        return type(self)(self.cents + other.cents)

    def __str__(self) -> str:
        return f"${self.cents // 100}.{self.cents % 100:02}"

@dataclass
class Eur(Money):
    def __str__(self) -> str:
        return f"{self.cents // 100},{self.cents % 100:02} EUR"

total = Eur.from_str("12.50") + Eur.from_str("0.75")
reveal_type(total)
print(total, Money.zero())
Runtime type is 'Eur'
13,25 EUR $0.00
$ mypy s4.py
s4.py:29: note: Revealed type is "s4.Eur"
Success: no issues found in 1 source file

Note type(self)(...) and cls(...). A method annotated -> Self has to build the object from the actual class. Hard-coding the class name is an error, because a subclass would get back a base class instance. other: Self also has a consequence you might not expect: the right operand must be the receiver's type or a subtype of it.

from typing import Self

class Money:
    def __init__(self, cents: int) -> None:
        self.cents = cents

    @classmethod
    def zero(cls) -> Self:
        return Money(0)

    def __add__(self, other: Self) -> Self:
        return type(self)(self.cents + other.cents)

class Eur(Money):
    pass

a = Money(100) + Eur(5)
b = Eur(100) + Money(5)
$ mypy s5.py
s5.py:9: error: Incompatible return value type (got "Money", expected "Self")  [return-value]
s5.py:18: error: Unsupported operand types for + ("Eur" and "Money")  [operator]
Found 2 errors in 1 file (checked 1 source file)

$ pyright s5.py
s5.py:9:16 - error: Type "Money" is not assignable to return type "Self@Money"
    Type "Money" is not assignable to type "Self@Money" (reportReturnType)
s5.py:18:5 - error: Operator "+" not supported for types "Eur" and "Money" (reportOperatorIssue)
2 errors, 0 warnings, 0 informations

Money(100) + Eur(5) is fine because an Eur is a Money. Eur(100) + Money(5) is rejected because a plain Money is not an Eur. If mixing is intended, annotate the parameter with the base class (other: Money) and keep -> Self for the return.

Self in attributes

Self also works in attribute annotations, which is handy for recursive structures such as linked lists and trees. Subclasses then get links typed as the subclass:

from dataclasses import dataclass
from typing import Self, reveal_type

@dataclass
class Node:
    value: int
    next: Self | None = None

    def append(self, value: int) -> Self:
        self.next = type(self)(value)
        return self.next

@dataclass
class TracedNode(Node):
    def describe(self) -> str:
        return f"traced {self.value}"

head = TracedNode(1)
head.append(2).append(3)
reveal_type(head.next)
node = head.next
while node:
    print(node.describe())
    node = node.next
Runtime type is 'TracedNode'
traced 2
traced 3
$ mypy s6.py
s6.py:20: note: Revealed type is "s6.TracedNode | None"
Success: no issues found in 1 source file

With next: "Node | None" the checker would reject node.describe(), since a Node has no describe method.

Where Self is not allowed

Self only makes sense where there is an instance or class to refer to. Static methods and module-level functions have neither:

from typing import Self

class Config:
    @staticmethod
    def default() -> Self:
        return Config()

def clone(x: Self) -> Self:
    return x
$ mypy s7.py
s7.py:5: error: Static methods cannot use Self type  [misc]
s7.py:5: error: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]
s7.py:5: note: Consider using the upper bound "Config" instead
s7.py:6: error: Incompatible return value type (got "Config", expected "Self")  [return-value]
s7.py:8: error: Self type is only allowed in annotations within class definition  [misc]
Found 4 errors in 1 file (checked 1 source file)

$ pyright s7.py
s7.py:5:22 - error: "Self" is not valid in this context (reportGeneralTypeIssues)
s7.py:8:14 - error: "Self" is not valid in this context (reportGeneralTypeIssues)
s7.py:8:23 - error: "Self" is not valid in this context (reportGeneralTypeIssues)
3 errors, 0 warnings, 0 informations

For a free function that returns its argument's type, use a type variable (def clone[T](x: T) -> T, see Generics with type parameter syntax (PEP 695)). Self is also not allowed in metaclasses or inside ClassVar[...]. Not every checker reports the ClassVar case, so don't count on it being caught.

@override: catching overrides that no longer override

The classic overriding bug: a base class renames or removes a method, and the subclass's "override" silently becomes a new, unrelated method. Here CachedStorage overrides save:

class Storage:
    def save(self, key: str, data: bytes) -> None:
        print(f"Storage.save({key!r})")

    def load(self, key: str) -> bytes:
        return b""

class CachedStorage(Storage):
    def save(self, key: str, data: bytes) -> None:
        print(f"CachedStorage.save({key!r}), cache updated")
        super().save(key, data)

s: Storage = CachedStorage()
s.save("a", b"1")
CachedStorage.save('a'), cache updated
Storage.save('a')

Then someone renames Storage.save to put and updates the callers. CachedStorage.save is never called anymore, so the cache is never updated, and there is no error. With @override on the method, the checker catches it:

from typing import override

class Storage:
    def put(self, key: str, data: bytes) -> None:  # renamed from save()
        print(f"Storage.put({key!r})")

class CachedStorage(Storage):
    @override
    def save(self, key: str, data: bytes) -> None:
        print(f"CachedStorage.save({key!r}), cache updated")
        super().put(key, data)

s: Storage = CachedStorage()
s.put("a", b"1")
Storage.put('a')

The output shows the bug: the cache code didn't run. Both checkers report it:

$ mypy o2.py
o2.py:9: error: Method "save" is marked as an override, but no base method was found with this name  [misc]
Found 1 error in 1 file (checked 1 source file)

$ pyright o2.py
o2.py:9:9 - error: Method "save" is marked as override, but no base method of same name is present (reportGeneralTypeIssues)
1 error, 0 warnings, 0 informations

@override also catches typos such as def __repr_(self) or def get_vale(self) that were meant to override something. It doesn't change what is checked about the signature: checkers already verify that every override is compatible with the base method, with or without the decorator.

Requiring @override on every override

@override only helps if you use it consistently. Both checkers can report overrides that are not marked. This is off by default, even in mypy's --strict and pyright's strict mode:

from typing import override

class Base:
    def run(self) -> None: ...
    def stop(self) -> None: ...

    @property
    def name(self) -> str:
        return "base"

    @classmethod
    def create(cls) -> "Base":
        return cls()

class Child(Base):
    @override
    def run(self) -> None:
        print("child run")

    def stop(self) -> None:          # overrides, but not marked
        print("child stop")

    @property
    @override
    def name(self) -> str:
        return "child"

    @classmethod
    @override
    def create(cls) -> "Child":
        return cls()

c = Child.create()
c.run()
c.stop()
print(c.name)
child run
child stop
child

Turn the check on in pyproject.toml:

[tool.mypy]
enable_error_code = ["explicit-override", "deprecated"]

[tool.pyright]
reportImplicitOverride = "error"
reportDeprecated = "warning"
$ mypy o3.py
o3.py:20: error: Method "stop" is not using @override but is overriding a method in class "o3.Base"  [explicit-override]

$ pyright o3.py
o3.py:20:9 - error: Method "stop" is not marked as override but is overriding a method in class "Base" (reportImplicitOverride)

On the command line the mypy flag is --enable-error-code explicit-override. The example also shows how to combine @override with other decorators. Put it closest to the def, below @property, @classmethod or @staticmethod. Checkers accept either order, but the runtime marker described below can only be set on the plain function. The deprecated entries in the config are for the next section.

@override at runtime

At runtime @override returns the function unchanged, after trying to set __override__ = True on it. Tools and tests can read that attribute:

import inspect
from typing import override

class Base:
    def run(self) -> None: ...
    def stop(self) -> None: ...

class Child(Base):
    @override
    def run(self) -> None: ...

    def stop(self) -> None: ...

for name, fn in inspect.getmembers(Child, inspect.isfunction):
    print(name, getattr(fn, "__override__", False))
run True
stop False

Python itself never checks that a base method exists. That check is entirely up to the type checker.

@warnings.deprecated

Before 3.13, deprecating a function meant calling warnings.warn(..., DeprecationWarning, stacklevel=2) inside it, and type checkers didn't know about it. The @deprecated decorator in the warnings module does both: it emits the warning at runtime and tells type checkers to flag every use.

from warnings import deprecated

@deprecated("Use parse_config() instead")
def load_config(path: str) -> dict[str, str]:
    return parse_config(path)

def parse_config(path: str) -> dict[str, str]:
    return {"path": path}

print(load_config("app.toml"))
print(getattr(load_config, "__deprecated__"))
d1.py:10: DeprecationWarning: Use parse_config() instead
  print(load_config("app.toml"))
{'path': 'app.toml'}
Use parse_config() instead

The message is required, and it is stored in __deprecated__. The warning points at the caller's line (d1.py:10), not at the line inside the decorator.

Type checkers don't report deprecations by default. In mypy enable the deprecated error code. In pyright set reportDeprecated, which is already an error in strict mode. Without it, editors that use pyright or Pylance still show deprecated names with a strikethrough.

$ mypy --enable-error-code deprecated d1.py
d1.py:10: error: function d1.load_config is deprecated: Use parse_config() instead  [deprecated]
d1.py:11: error: function d1.load_config is deprecated: Use parse_config() instead  [deprecated]
Found 2 errors in 1 file (checked 1 source file)

$ pyright d1.py        # with reportDeprecated = "warning"
d1.py:10:7 - warning: The function "load_config" is deprecated
    Use parse_config() instead (reportDeprecated)
d1.py:11:15 - warning: The function "load_config" is deprecated
    Use parse_config() instead (reportDeprecated)
0 errors, 2 warnings, 0 informations

The checker flags every reference to the name, not only calls. That is why line 11 is reported too.

Classes, methods and overloads

@deprecated works on classes, where it warns when the class is instantiated or subclassed, and on methods. It also works on individual @overload signatures. This lets you deprecate one way of calling a function while keeping the others:

from typing import overload
from warnings import deprecated

@deprecated("LegacyClient is deprecated, use Client")
class LegacyClient:
    def __init__(self, url: str) -> None:
        self.url = url

class Client:
    def __init__(self, url: str) -> None:
        self.url = url

    @deprecated("fetch_json() is deprecated, use get()")
    def fetch_json(self, path: str) -> dict[str, object]:
        return {}

    @overload
    def get(self, path: str) -> bytes: ...
    @overload
    @deprecated("passing timeout as int is deprecated, pass a float")
    def get(self, path: str, timeout: int) -> bytes: ...
    @overload
    def get(self, path: str, timeout: float) -> bytes: ...
    def get(self, path: str, timeout: float | None = None) -> bytes:
        return b""

old = LegacyClient("https://example.com")
c = Client("https://example.com")
c.fetch_json("/users")
c.get("/users")
c.get("/users", 5)
c.get("/users", 5.0)
d2.py:27: DeprecationWarning: LegacyClient is deprecated, use Client
  old = LegacyClient("https://example.com")
d2.py:29: DeprecationWarning: fetch_json() is deprecated, use get()
  c.fetch_json("/users")
$ mypy --enable-error-code deprecated d2.py
d2.py:27: error: class d2.LegacyClient is deprecated: LegacyClient is deprecated, use Client  [deprecated]
d2.py:29: error: function d2.Client.fetch_json is deprecated: fetch_json() is deprecated, use get()  [deprecated]
d2.py:31: error: overload def (self: d2.Client, path: str, timeout: int) -> bytes of function d2.Client.get is deprecated: passing timeout as int is deprecated, pass a float  [deprecated]
Found 3 errors in 1 file (checked 1 source file)

$ pyright d2.py        # with reportDeprecated = "warning"
d2.py:27:7 - warning: The class "LegacyClient" is deprecated
    LegacyClient is deprecated, use Client (reportDeprecated)
d2.py:29:3 - warning: The method "fetch_json" in class "Client" is deprecated
    fetch_json() is deprecated, use get() (reportDeprecated)
d2.py:31:3 - warning: The method "get" in class "Client" is deprecated
    passing timeout as int is deprecated, pass a float (reportDeprecated)
0 errors, 3 warnings, 0 informations

The deprecated overload is only reported by the type checker. At runtime there is a single get implementation and Python doesn't know which overload a call matched, so c.get("/users", 5) emits no warning. To warn at runtime too, check isinstance(timeout, int) inside get and call warnings.warn yourself.

Who sees the runtime warning

DeprecationWarning follows the normal warning filters. By default it is shown only when the warning is attributed to code in __main__. Here a library module geo.py deprecates a function, and also still calls it internally:

# geo.py
from warnings import deprecated

@deprecated("distance_km() is deprecated, use distance(unit='km')")
def distance_km(a: tuple[float, float], b: tuple[float, float]) -> float:
    return distance(a, b, unit="km")

def distance(a: tuple[float, float], b: tuple[float, float], unit: str = "km") -> float:
    d = ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5
    return d if unit == "km" else d * 0.621371

def route_length(points: list[tuple[float, float]]) -> float:
    # library code that still uses the old function internally
    return sum(distance_km(p, q) for p, q in zip(points, points[1:]))
# app.py
import geo

print(geo.distance_km((0, 0), (3, 4)))
print(geo.route_length([(0, 0), (3, 4), (6, 8)]))
$ python app.py
app.py:3: DeprecationWarning: distance_km() is deprecated, use distance(unit='km')
  print(geo.distance_km((0, 0), (3, 4)))
5.0
10.0

$ python -W default::DeprecationWarning app.py
app.py:3: DeprecationWarning: distance_km() is deprecated, use distance(unit='km')
  print(geo.distance_km((0, 0), (3, 4)))
geo.py:13: DeprecationWarning: distance_km() is deprecated, use distance(unit='km')
  return sum(distance_km(p, q) for p, q in zip(points, points[1:]))
5.0
10.0

$ python -W error::DeprecationWarning app.py
Traceback (most recent call last):
  File "app.py", line 3, in <module>
    print(geo.distance_km((0, 0), (3, 4)))
          ~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
  File "C:\...\Python313\Lib\warnings.py", line 636, in wrapper
    warn(msg, category=category, stacklevel=stacklevel + 1)
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
DeprecationWarning: distance_km() is deprecated, use distance(unit='km')

The call from app.py (the main script) is shown by default. The library's internal call, attributed to geo.py, is hidden unless you enable it with -W default, which shows each location once, or with PYTHONWARNINGS. -W error turns the warning into an exception. pytest shows deprecation warnings in its summary, and filterwarnings = ["error"] makes them fail the test run, as described in Testing in CI.

Choosing the warning category

category picks the warning class (the default is DeprecationWarning), and stacklevel adjusts which frame the warning points at. category=None disables the runtime warning entirely, and the deprecation then exists only for type checkers:

import warnings
from warnings import deprecated

@deprecated("old_api() will be removed in 3.0", category=FutureWarning)
def old_api() -> int:
    return 1

@deprecated("only flagged by type checkers", category=None)
def quiet_api() -> int:
    return 2

@deprecated("Plugin is deprecated, subclass BasePlugin")
class Plugin:
    pass

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    old_api()
    quiet_api()

    class MyPlugin(Plugin):  # subclassing also warns
        pass

for w in caught:
    print(f"{w.category.__name__}: {w.message}")
FutureWarning: old_api() will be removed in 3.0
DeprecationWarning: Plugin is deprecated, subclass BasePlugin

FutureWarning is shown to everyone by default, so it suits deprecations aimed at end users of an application. DeprecationWarning is for developers who call your library.

Older Python versions: typing_extensions

All three names are available in the typing_extensions package: Self since 4.0, override since 4.4 and deprecated since 4.5. They work the same way on older Pythons, and type checkers treat them like the standard library versions:

import sys

from typing_extensions import Self, deprecated, override

class Base:
    def clone(self) -> Self:
        return type(self)()

    def name(self) -> str:
        return "base"

class Child(Base):
    @override
    def name(self) -> str:
        return "child"

@deprecated("use Child")
class Old(Base):
    pass

print(sys.version.split()[0], Child().clone().name())
Old()
te.py:22: DeprecationWarning: use Child
  Old()
3.10.11 child

This was run with Python 3.10 and typing_extensions 4.16.0. Code that supports both old and new versions often uses conditional imports. Type checkers understand the sys.version_info checks:

import sys

if sys.version_info >= (3, 13):
    from warnings import deprecated
else:
    from typing_extensions import deprecated

if sys.version_info >= (3, 12):
    from typing import override
else:
    from typing_extensions import override

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents