In my Enum, i have defined a classmethod for coercing a given value to an Enum member. The given value may already be an instance of the Enum, or it may be a string holding an Enum value. In order to decide whether it needs conversion, i check if the argument is an instance of the class, and only pass it on to int() if it is not. At which point – according to the type hints for the argument 'item' – it must be a string.
The class look like this:
T = TypeVar('T', bound='MyEnum')
class MyEnum(Enum):
A = 0
B = 1
@classmethod
def coerce(cls: Type[T], item: Union[int, T]) -> T:
return item if isinstance(item, cls) else cls(int(item))
mypy fails with:
error: Argument 1 to "int" has incompatible type "Union[str, T]"; expected "Union[str, bytes, SupportsInt, SupportsIndex, _SupportsTrunc]"
Why?