python / python/mypy

Feature proposal: Warn when narrowing to a mutable type

Open
#11,384 7 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

I often encourage people to use "immutable" types for function parameters, as a way to indicate that the passed data structures won't be mutated by the function. Of course that isn't a guarantee, but a nice indication that can make it easier to reason about code like this:

vals = [1, 2, 3]
operation(vals)
print(vals)  # What is vals here?

If operation is typed with Sequence we can usually assume that vals isn't mutated by it. However, right now it wouldn't be a type error for operation to be implemented like this, which breaks that indication.

def operation(vals: Sequence[int]) -> None:
    assert isinstance(vals, list)
    vals += [3, 4, 5]

Here's the above example on mypy playground.

Pitch

I think it would be a valuable feature for mypy to warn when it narrows from a known immutable type such as Sequence to a known mutable type such as list.

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 with the linked mypy playground example and review how narrowing from Sequence to list is currently handled. Done means mypy can identify this narrowing from a known immutable type to a known mutable type and emit the proposed warning without changing unrelated narrowing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.