python / python/mypy

Suggest making protocol attribute read-only if invariance causes conflict

Open
#6,002 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

good-second-issue priority-1-normal topic-protocols topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

If a concrete attribute has a narrower type than protocol attribute, mypy will complain (adapted from #5998):

prog.py:59: error: Argument 1 to "f" has incompatible type "C"; expected "Proto"
prog.py:59: note: Following member(s) of "C" have conflicts:
prog.py:59: note:     name: expected "Optional[str]", got "str"

It could help if mypy would suggest making the protocol attribute read-only (property or final attribute), which is often the right thing to do.

We already generate a related suggestion to use a covariant collection type when using an invariant collection causes type incompatibility.

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 tracing the existing suggestion for using a covariant collection type when invariant collections cause incompatibility. Add a corresponding suggestion for making a conflicting protocol attribute read-only, and verify the diagnostic with regression coverage for the example shown.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.