I am was trying to use __new__ to do some customizations to my class but I ran into some mypy errors. The following code is a simplified version.
from abc import ABC, abstractproperty
class A(ABC):
def __new__(cls, x: int) -> 'A':
return super().__new__(cls)
@abstractproperty
def log(self) -> None:
pass
class B(A):
def __new__(cls, x: str) -> 'B':
return super().__new__(cls, int(x))
def log(self) -> None:
print('Hello World')
The mypy errors were as follows:
test.py:5: error: Argument 1 to "__new__" of "object" has incompatible type "Type[A]"; expected "Type[object]"
test.py:13: error: Incompatible return value type (got "A", expected "B")
test.py:13: error: Argument 1 to "__new__" of "A" has incompatible type "Type[B]"; expected "Type[A]"
I had the same issue just recently. I think mypy does not (yet) support the special behavior of __new__().
My workaround is using typing.cast() twice, like this:
def __new__(cls, x: str) -> "B":
return typing.cast(
"B",
super().__new__(
typing.cast(typing.Type[A], cls),
int(x),
),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With