Skip to content

Subclass may unsoundly restrict an instance variable type #13828

Closed as not planned
@andersk

Description

@andersk

Bug Report

Mypy allows an instance variable annotation on a subclass to restrict the variable’s type in a way that’s incompatible with the superclass. This is unsound and should be forbidden.

To Reproduce

class A:
    def __init__(self, x: object) -> None:
        self.x = x

class B(A):
    x: int

B("string").x + 1

https://mypy-play.net/?mypy=latest&python=3.10&gist=00ef5dbb43039cac3d1672b3ece3029a&flags=strict

Mypy doesn’t give any errors, but should, because this fails at runtime with TypeError: can only concatenate str (not "int") to str.

Expected Behavior

mypy should complain about x: int.

Actual Behavior

No mypy errors.

Your Environment

  • Mypy version used: 0.981
  • Mypy command-line flags: --strict
  • Python version used: 3.10.7

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