Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mypy throws errors when using __new__

Tags:

python

mypy

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]"

like image 480
VBK Avatar asked Feb 02 '26 00:02

VBK


1 Answers

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),
        ),
    )
like image 72
Rahix Avatar answered Feb 03 '26 13:02

Rahix