Skip to content

Mypyc ignores custom __new__ without warning #16012

Open
@nickdrozd

Description

@nickdrozd

Mypyc apprently ignores custom __new__ methods without warning. It would be great if it could abide by the custom __new__, but otherwise a warning / error should be raised.

Example code (see #1020 (comment)):

from __future__ import annotations

class Add:
    l: IntLike
    r: IntLike

    def __new__(cls, l: IntLike, r: IntLike) -> IntLike:  # type: ignore[misc]
        print(f'running __new__ with {l} and {r}')

        return (
            l if r == 0 else
            r if l == 0 else
            super().__new__(cls)
        )

    def __init__(self, l: IntLike, r: IntLike):
        self.l = l
        self.r = r

    def __repr__(self) -> str:
        return f'({self.l} + {self.r})'

    def __add__(self, other: IntLike) -> IntLike:
        return Add(self, other)

IntLike = int | Add

Code for running:

print(f'{Add(1, 5)=}')
print(f'{Add(0, 5)=}')
print(f'{Add(1, 0)=}')

Running this interpreted gives:

running __new__ with 1 and 5
Add(1, 5)=(1 + 5)
running __new__ with 0 and 5
Add(0, 5)=5
running __new__ with 1 and 0
Add(1, 0)=1

Running compiled:

Add(1, 5)=(1 + 5)
Add(0, 5)=(0 + 5)
Add(1, 0)=(1 + 0)

The interpreted and compiled behaviors are different, which is bad.

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