I created a dataclass Foo, which accepts any type that can be converted to int:
import dataclasses
@dataclasses.dataclass
class Foo:
a: int
def __post_init__(self):
# Here `self.a` is converted to int, so this class accepts any type that can be converted to int
self.a = int(self.a)
# mypy error: Argument 1 to "Foo" has incompatible type "str"; expected "int",
foo = Foo("1")
print(foo)
print(foo.a + 2)
Output:
Foo(a=1)
3
However, mypy reports the below error:
error: Argument 1 to "Foo" has incompatible type "str"; expected "int"
If I fix the type of Foo.a to Union[str, int], mypy reports another error:
error: Unsupported operand types for + ("str" and "int")
How to write a dataclass whose type of the field and the init argument are different?