I have a base class with a type hint of float
on a method's return.
In the child class, without redefining the signature, can I somehow update the type hint on the method's return to be int
?
Sample Code
#!/usr/bin/env python3.6
class SomeClass:
"""This class's some_method will return float."""
RET_TYPE = float
def some_method(self, some_input: str) -> float:
return self.RET_TYPE(some_input)
class SomeChildClass(SomeClass):
"""This class's some_method will return int."""
RET_TYPE = int
if __name__ == "__main__":
ret: int = SomeChildClass().some_method("42"). #
ret2: float = SomeChildClass().some_method("42")
My IDE complains about a type mismatch:
This is happening because my IDE is still using the type hint from SomeClass.some_method
.
Research
I think the solution might be to use generics, but I am not sure if there's a simpler way.
Python: how to override type hint on an instance attribute in a subclass?
Suggests maybe using instance variable annotations, but I am not sure how to do that for a return type.
some_method
(the one defined onSomeClass
). Instances ofSomeChildClass
will resolve the method name to that same function object defined onSomeClass
, they don't actually have their own separate implementation which you could annotate separately. Annotations are just an attribute on the function object, it can't really have different annotations depending on how it was resolved through the MRO. – TerminationSomeChildClass
)? – RibbleRET_TYPE = float
class attribute thing, just redefine the method in the child class? – Termination