Skip to content

_v can be read and written from the outside of the class so the generic class should be invariant properly. #20501

@hyperkai

Description

@hyperkai

*Memo:

  • mypy --strict test.py
  • mypy 1.19.1
  • Python 3.14.0
  • Windows 11

v can be read and written from the outside of the class so the generic class is invariant properly as shown below:

class Cls[T]:
    v: T = cast(T, 100) # Invariant

cls: Cls[int] = Cls[int]()

# It indicates `Invariant`.
cls1: Cls[float] = cls # Errpr
cls2: Cls[int] = cls   # No error
cls3: Cls[bool] = cls  # Error

# Read & Write
print(cls.v) # No error
cls.v = 200  # No error

Now, _v can be read and written from the outside of the class but the generic class is covariant improperly as shown below so it should be invariant properly:

*Memo:

  • A single leading underscore(_abc) just indicates Internal use so it's not private(Readable & Writable).
class Cls[T]:
    _v: T = cast(T, 100) # Covariant

cls: Cls[int] = Cls[int]()

# It indicates `Covariant`.
cls1: Cls[float] = cls # No error
cls2: Cls[int] = cls   # No error
cls3: Cls[bool] = cls  # Error

# Read & Write
print(cls._v) # No error
cls._v = 200  # No error

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