How to annotate class Methods to return only instances of their class or subclass in python (original) (raw)
I have a class method that can return the instance of its class or subclass (depending on the
arguments), but not instance of the supertype.
How to add annotations here?
from typing import *
class A:
@classmethod
def meth(cls): # Type annotation here
# Can return instance of A, B or C class
...
class B(A):
@classmethod
@override
def meth(cls): # Type annotation here
# Can return instance of B or C class, but not A
...
class C(B):
@classmethod
@override
def meth(cls): # Type annotation here
# Can return only instance of C
...
I know that I can just add -> 'A'
, -> 'B'
, -> 'C'
annotations to these methods, but this class is intended for subclassing by library user, I need to force user’s subclasses to be annotated to return only subclasses of them.
JoBe (JoBe) June 7, 2025, 10:59pm 2
Is this a duplicate?
davidism (David Lord) Unlisted June 7, 2025, 11:38pm 3
t1m013y (Timofey Fomin) June 8, 2025, 8:32am 4
Re-asked this because Return type Self: returning subclass - #5 by t1m013y was about how does typing.Self
work and this is about how to make what I was thinking typing.Self
does.
carljm (Carl Meyer) June 9, 2025, 5:32pm 6
Then these methods should all be annotated to return typing.Self
– that’s exactly what it enforces. Which makes this a duplicate of the other thread.