Constant vs variable as index for none-checking List[Optional[...]]
Open
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
Can you explain to me why there is this difference between using a constant and a variable as index for none-checking here?
from typing import List, Optional
my_list: List[Optional[float]] = []
if my_list[0] is not None:
result_1: float = my_list[0] # no error
result_2: float = my_list[1] # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
id_0 = 0
if my_list[id_0] is not None:
result_3: float = my_list[id_0] # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
for i in range(10):
if my_list[i] is not None:
a: float = my_list[i] # error: Incompatible types in assignment (expression has type "Optional[float]", variable has type "float")
- Mypy version used:
0.8000.941 - Mypy command-line flags:
- Mypy configuration options from
mypy.ini(and other config files): - Python version used: python3.6
- Operating system and version: Ubuntu 18.04 in WSL2 (Windows 11)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names no repository files or tests. Reproduce the examples with mypy 0.941, then trace the type narrowing behavior for indexed List[Optional[float]] expressions. Done means the differing constant, variable, and loop-index behavior is explained and, if confirmed as a bug, covered by an appropriate regression test.
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
- 35/100