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

Bad error message for covariant overriding of a mutable attribute #7109

Open
mthuurne opened this issue Jun 30, 2019 · 3 comments
Open

Bad error message for covariant overriding of a mutable attribute #7109

mthuurne opened this issue Jun 30, 2019 · 3 comments

Comments

@mthuurne
Copy link
Contributor

When I check this with mypy 0.711:

from typing import Callable, Optional

class Base:
    formatter1: Callable[[int], str]
    formatter2: Optional[Callable[[int], str]]
    formatter3: Optional[Callable[[int], str]]
    formatter4: Optional[Callable[[int], str]]

class Sub(Base):
    @staticmethod
    def formatter1(value: int) -> str:
        return str(value)
    @staticmethod
    def formatter2(value: int) -> str:
        return str(value)
    formatter3 = formatter2
    formatter4 = str

It reports:

14: error: Signature of "formatter2" incompatible with supertype "Base"

I would expect all four formatters to be accepted, but for some reason formatter2 is not.

It doesn't make a difference whether I use the old or new semantic analyzer.

@msullivan msullivan added bug mypy got something wrong priority-2-low labels Aug 2, 2019
@ilevkivskyi
Copy link
Member

It looks like mypy already prohibits covariant overriding of mutable attributes if one of them is a method, unlike for variables (see #3208), which is quite funny.

Note however, this is not a bug, this is actually unsafe code:

y = Sub()
x: Base = y

x.formatter2 = None
y.formatter2(42)  # Oops, TypeError: NoneType not callable.

@ilevkivskyi
Copy link
Member

Actually, on the second thought I think we should keep this open for cryptic error message. It should explain that the problem here is mutability in superclass.

@ilevkivskyi ilevkivskyi reopened this Aug 12, 2019
@ilevkivskyi ilevkivskyi changed the title False positive with staticmethod and Optional Callable Bad error message for covariant overriding of a mutable attribute Aug 12, 2019
@mthuurne
Copy link
Contributor Author

Hmm, indeed this is unsafe in general. The way I use this pattern is to define optional operations, so these fields will never be modified at runtime, but there is no way for mypy to know that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants