For an example of how to apply Brian’s answer:
- with a
TypeVar
:
from typing import TypeVar
AnyA = TypeVar("AnyA", bound="A")
class A:
def __init__(self):
print("A")
self.hello = "hello"
@classmethod
def bobo(cls: type[AnyA]) -> AnyA:
return cls()
class B(A):
def __init__(self):
print("B")
super().__init__()
self.world = "world"
reveal_type(B.bobo()) # B
- with
Self
:
from typing import Self
class A:
def __init__(self):
print("A")
self.hello = "hello"
@classmethod
def bobo(cls) -> Self:
return cls()
class B(A):
def __init__(self):
print("B")
super().__init__()
self.world = "world"
reveal_type(B.bobo()) # B
If your version of Python doesn’t have Self
yet, you can use the typing-extensions package, which serves as backport for some typing features:
- from typing import Self
+ from typing_extensions import Self