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

mypy incorrectly allows overriding parent attribute #15455

Closed
jfgauron opened this issue Jun 16, 2023 · 1 comment
Closed

mypy incorrectly allows overriding parent attribute #15455

jfgauron opened this issue Jun 16, 2023 · 1 comment
Labels
bug mypy got something wrong

Comments

@jfgauron
Copy link

jfgauron commented Jun 16, 2023

Bug Report

mypy permits overriding attributes of parent class if the child attribute is compatible with the parent attribute. This breaks Liskov Substitution Principle.

To Reproduce

from typing import Literal

class Parent:
  x: Literal["a", "b", "c"]

  def __init__(self, x: Literal["a", "b", "c"]) -> None:
    self.x = x

class Child(Parent):
  x: Literal["a"]

  def foo(self) -> Literal["a"]:
    return self.x

child = Child("c") # no error from mypy
x = child.foo()

# reveal_type(x) # Revealed type is "Literal['a']
print(x) # outputs "c"

https://mypy-play.net/?mypy=latest&python=3.11&gist=37e7f5a43c649a9ea5d6f0a9253d7e07

Expected Behavior

I believe mypy shouldn't allow overriding class attributes in child class, even with a type that is "compatible" with the parent attribute. Otherwise we can get into funny cases such as:

my_list: list[Parent] = [Child("a")]
my_list[0].x = "c"

Actual Behavior

I got no error from mypy. Running python -m mypy --strict main.py printed:

Success: no issues found in 1 source file

Your Environment

  • Mypy version used: 1.3.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10.6
@jfgauron jfgauron added the bug mypy got something wrong label Jun 16, 2023
@hauntsaninja
Copy link
Collaborator

hauntsaninja commented Jun 16, 2023

Duplicate of #3208

I think the dropbox folks found this was too strict to have on by default in practice. mypy is strict about this with protocols (which is good) and folks still file issues about that somewhat regularly. Anyway that^ issue is where to discuss

@hauntsaninja hauntsaninja marked this as a duplicate of #3208 Jun 16, 2023
@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Jun 16, 2023
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

2 participants