'Python typing: How to use Generic?
Consider the following example:
import typing
T = typing.TypeVar('T', bound=typing.Union[int, bool, str])
class Test(typing.Generic[T]):
def __init__(self, v: T) -> None:
self.v = v
self.t = type(v)
def parse(self, s: str) -> T:
if self.t == int:
return int(s, base=0)
elif self.t == bool:
return s.lower() != 'false'
elif self.t == str:
return s
else:
raise NotImplementedError()
mypy complains:
test.py:13: error: Incompatible return value type (got "int", expected "T")
test.py:15: error: Incompatible return value type (got "bool", expected "T")
test.py:17: error: Incompatible return value type (got "str", expected "T")
How do I rewrite the code so that mypy understands that T is in this case int/bool/str?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
