I have the following situation: a parent class Format
and some child classes, for example FormatA
and FormatB
:
import abc
class Format(abc.ABC):
def to_formatA(self):
raise NotImplementedError()
def to_formatB(self):
raise NotImplementedError()
...
class FormatA(Format):
def to_formatA(self):
return self
def to_formatB(self):
return FormatB()
class FormatB(Format):
def to_formatA(self):
return FormatA()
def to_formatB(self):
return self
What is the best way to apply typing annotations?
My Attempt:
import abc
from typing import TypeVar
TFormat = TypeVar("TFormat", bound="Format")
TFormatA = TypeVar("TFormatA", bound="FormatA")
TFormatB = TypeVar("TFormatB", bound="FormatB")
class Format(abc.ABC):
def to_formatA(self) -> TFormatA:
raise NotImplementedError()
def to_formatB(self) -> TFormatB:
raise NotImplementedError()
class FormatA(Format):
def to_formatA(self) -> TFormatA:
return self
def to_formatB(self) -> TFormatB:
return FormatB()
class FormatB(Format):
def to_formatA(self) -> TFormatA:
return FormatA()
def to_formatB(self) -> TFormatB:
return self
MyPy gives me different errors:
- for each class,
to_formatA
andto_formatB
methods give:
error: A function returning TypeVar should receive at least one argument containing the same TypeVar
Type Hint for self
?
- for row 21 and 33, respectively:
error: Incompatible return value type (got "FormatA", expected "TFormatA")
error: Incompatible return value type (got "FormatB", expected "TFormatB")