python / python/mypy

Type narrowing when condition is assigned to a variable

Open
#11,979 2 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

Narrowing techniques perform very well when the condition is calculated inside the if condition. When these are made outside, I can understand that mypy cannot guarantee that the narrow will be ok as the boolean value of the condition might be changed before reaching the if statement. However, when the value of this condition is given outside of the if statement but defined as a Final type, the narrow should be working

Minimal code to repdroduce it:

from typing import Optional, Final

def example_func(value: Optional[int] = None):

    condition: Final = value is not None

    if condition: 
        reveal_type(value)  # Revealed type is "Union[builtins.int, None]"
        value = value + 1   # MYPY ERROR

    if value is not None:
        reveal_type(value)  # Revealed type is "builtins.int"
        value = value + 1   # MYPY OK
    return 0

Expected Behavior
The type of value for the first if statement should be builtins.int, as the condition variable should remain with the same value that was previously assigned to it.

Actual Behavior
Narrowed not performed, and thus the type of value is still inferred as Optional[int]

Your Environment

  • Mypy version used: 0.931
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.8.10
  • Operating system and version: Ubuntu 20

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 Python example with mypy 0.931 and inspect the two reveal_type results around the Final condition. Trace the type narrowing behavior for conditions assigned to Final variables; done means the first reveal_type reports builtins.int and the following addition is accepted without weakening the existing direct-condition behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.