python / python/mypy

Checking elements of a `list[str | None]` after discarding the possibility of `None`

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

Nobody has claimed this yet.

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

Description

Bug Report

str_none: list[str | None]
only_str: list[str]
for i in range(len(sequence)):
    if sequence[i] is not None:
        only_str.append(sequence[i]) # Here mypy raises an error due to "incompatible types"

The code above raises the following error Argument 1 to "append" of "list" has incompatible type "str | None"; expected "str".

I've found the following verbose workaround but to my taste its :

str_none: list[str | None]
only_str: list[str]
for i in range(len(sequence)):
    element = sequence[i]
    if element is not None:
        only_str.append(element)

To Reproduce

See code example above.

Expected Behavior

I'm expecting mypy to be able to predict future annotations of sequences with multiple types possible after discarding a specific type in a condition.

Actual Behavior

All is included above.

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: both --strict and none
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.11.5

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 running the minimal reproducer from the issue with mypy 1.5.1 and then trace the type-narrowing behavior for indexed sequence access. Done means the example accepts the narrowed element without the verbose local-variable workaround, with a regression test covering the reported case.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.