Python · correctness
prefer-self-type-annotation
python:prefer-self-type-annotation Annotate fluent methods and alternate constructors with `Self`.
- Code
- SARJ078
- Default
- error
- Fix
- none
- Languages
- python
Why
`Self` preserves the concrete subclass type, while naming the enclosing class narrows inherited return types incorrectly.
Fix
Import `Self` from `typing` and use it as the return annotation.
Before / after
Executed by this rule’s unit tests.
Before
Fluent method names its enclosing class
class Builder:
def set_name(self, name: str) -> "Builder":
self.name = name
return self
After
Fluent method preserves subclass type
from typing import Self
class Builder:
def set_name(self, name: str) -> Self:
self.name = name
return self
Limits
- Only methods that directly return `self` or classmethods that directly return `cls(...)` are analyzed.
- Annotations naming other classes and methods without a return annotation are excluded.