Skip to content

__new__ return types are not respected (reported as error and overwritten by the current class) unless the return type is a subclass of the current class #19624

@studyingegret

Description

@studyingegret

new.py:

from typing import cast

class A:
    def __new__(cls) -> int:
        return 1

class B:
    def __new__(cls) -> "C":
        return cast(C, None)

class C(B):
    def __new__(cls) -> B:
        return cast(B, None)

reveal_type(A()) # Expect int (builtin.int)
reveal_type(B()) # Expect C (new.C)
reveal_type(C()) # Expect B (new.B)

Run

mypy new.py --config-file=

(The --config-file= ignores configuration files)

Expected:

new.py:15: note: Revealed type is "builtin.int"
new.py:16: note: Revealed type is "new.C"
new.py:17: note: Revealed type is "new.B"

Actual:

new.py:4: error: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")  [misc]
new.py:12: error: Incompatible return type for "__new__" (returns "B", but must return a subtype of "C")  [misc]
new.py:15: note: Revealed type is "new.A"
new.py:16: note: Revealed type is "new.C"
new.py:17: note: Revealed type is "new.C"
Found 2 errors in 1 file (checked 1 source file)

Environment

  • mypy 1.18.0+dev (compiled: no) (186515f)
    • python -m pip install -e . -C editable_mode=strict
  • Python 3.13.2

Related issues

Same: #1020 #15182 #8330
Related: #14502 #12045 #9045

(Note: Some of these issues are noted as no longer reproducable in the comments. I didn't check their reproducability, but I am able to reproduce this one, which might mean a regression.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions