'Is there any benefit to annotating `self` or `cls` in Python methods?
As explained in PEP-673, the current (Python 3.10) correct way to add a type annotation to self is somewhat verbose:
from typing import TypeVar
TShape = TypeVar("TShape", bound="Shape")
class Shape:
def set_scale(self: TShape, scale: float) -> TShape:
self.scale = scale
return self
It's clear to me why the TypeVar is needed for methods that return instances of their own class. In this example, set_scale() needs to be annotated -> TShape for linters to understand it may return an instance of specific subclass of Shape, not simply instances of Shape.
It's fairly common, though, for a class to have no use for a TypeVar other than annotating the self parameter to methods. Anecdotally, linters (mypy and Pylance) seem to have no issue inferring correct types if the annotation is left off in this case. The same seems to be true of cls inside classmethod definitions.
In PEP-673, some of the examples omit any annotation of self, even after introducing the new, more convenient Self type of Python 3.11:
from typing import Self
class Shape:
def difference(self, other: Self) -> float: ...
def apply(self, f: Callable[[Self], None]) -> None: ...
The PEP text notes that specifying self: Self in this example would be "harmless", but doesn't clarify whether there's actually any benefit to doing so.
Given the above, is there any reason to bother annotating self or cls in a method's parameter list? I'm considering switching to omitting these even when I have a defined TypeVar anyway for return types -- why bother if the types are obvious to both humans and linters?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
