generics_self_usage
error
Self type used in an invalid location
PEP 673 defines Self as a special type that refers to the current class. It is only valid in specific locations:
- Method parameter annotations (including self and cls) - Method return type annotations - Class variable annotations inside the class body - Nested within other types at those locations
Invalid locations (detected here):
- Return types or parameter annotations of module-level functions - Module-level variable annotations (bar: Self) - TypeAlias definitions whose RHS contains Self - Base class expressions (class Foo(BarSelf) or class Foo(Self)) - @staticmethod method annotations (no self to bind to) - Method annotations in metaclasses (classes inheriting from type) - Return type annotation when self is explicitly annotated with a TypeVar (e.g. def f(self: TFoo2) -> Self: — binding is ambiguous)
# E — not within a class
def foo(bar: Self) -> Self: ...
bar: Self
class Base:
@staticmethod
def make() -> Self: ... # E — staticmethod has no Self binding
class MyMeta(type):
def __new__(cls, *args: Any) -> Self: ... # E — metaclass
How to handle it
Every rule is on by default — strict is the default, not a cage. You can dial
generics_self_usage down per-file or per-path from your editor or
pyproject.toml, or fix the code
so it type-checks. See the Type System rules and
the complete diagnostic reference.
Canonical URL: https://www.basilisk-python.dev/errors/generics_self_usage