Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mypyc ignores custom __new__ without warning #16012

Open
nickdrozd opened this issue Sep 1, 2023 · 0 comments
Open

Mypyc ignores custom __new__ without warning #16012

nickdrozd opened this issue Sep 1, 2023 · 0 comments
Labels
bug mypy got something wrong

Comments

@nickdrozd
Copy link
Contributor

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.

@nickdrozd nickdrozd added the bug mypy got something wrong label Sep 1, 2023
hauntsaninja added a commit to hauntsaninja/mypy that referenced this issue Sep 2, 2023
Fixes python#1020 (comment)
Surprisingly popular comment on a closed issue.

We still issue the warning, but we do trust the return type instead of
overruling it.

Maybe fixes python#16012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant