Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Overriding callable attribute with method not caught by [mutable-override] #18052

Description

@brianschubert

Bug Report

Follows from #12569, #3208

Mypy has an optional error code mutable-override that checks for unsafe overrides of mutable attributes:

class Parent:
    x: float

class Child(Parent):
    x: int  # E: Covariant override of a mutable attribute (base class "Parent" defined the type as "float", expression has type "int")  [mutable-override]

However, this error isn't emitted when overriding a callable attribute with a method:

from typing import Callable

class Parent:
    func: Callable[[str], None]

class Child(Parent):
    def func(self, x: object) -> None: pass  # no error

This allows dubious code like the following to pass type checking:

def foo(x: str) -> None:
    assert isinstance(x, str)
    
def modify_parent(x: Parent) -> None:
    x.func = foo 
    
c = Child()
modify_parent(c)
c.func(1)  # boom!

Your Environment

  • Mypy version used: master (1.14.0+dev.2b033cbd7)
  • Mypy command-line flags: --strict --enable-error-code=mutable-override
  • Mypy configuration options from mypy.ini (and other config files): N/A (empty)
  • Python version used: 3.12.7

Activity

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

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