python / python/mypy

Add "is invariant" warning to Set as well as List for situations where a Collection should be used

Open
#16,631 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

mypy has a lovely warning about List being invariant in situations like this:

ls: List[int] = [1, 2, 3]

def process(stuff: List[Union[int, str]]):
    ...

process(ls)  # type error here, w/ nice explanation of invariance and suggestion to use Sequence

However, it does not have the same warning when Set is used in the same way:

s: Set[int] = {1, 2, 3}

def process(stuff: Set[Union[int, str]]):
    ...

process(s)  # merely states that the type is incompatible, no mention of invariance

Would be nice if the same warning mechanism could trigger here, suggesting Collection.

Pitch

Hopefully this is a simple widening of a rule that's special-cased for lists to get sets too? Not sure if other types like Dict/Tuple might be included too; I haven't tested them. If it's a lot of effort probably not worth it.

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 locating the existing List invariance warning and its tests; the issue does not name specific files or entry points. Extend the same warning behavior to Set and verify that the diagnostic explains invariance and suggests Collection, as shown in the example.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.