python / python/mypy

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

Open
#20,501 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug pending
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

*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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the report from test.py with mypy --strict under the stated mypy 1.19.1 and Python 3.14.0 versions. Trace how mypy infers variance for generic classes with public and single-underscore attributes. Done means the _v example is treated as invariant while preserving the shown valid and invalid assignments.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.