python / python/mypy

Incompatible types in assignment (expression has type "bool", variable has type "Literal[False]") with nested code

Open
#13,829 0 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

To Reproduce

class Bar:
    def __init__(self, baz: bool) -> None:
        self.baz: bool = baz


def busted(key: int, bar: Bar) -> None:
    b = bar
    if key > 1:
        if b.baz: # No error without this block
            return
        if key != 1:
            baz = b.baz
    if key > 0:
        if key < 5:
            baz = b.baz  # error: Incompatible types in assignment (expression has type "bool", variable has type "Literal[False]")

Expected Behavior
This silly example is the smallest I could trim my real code to. It is a lot of nested if that stores references to bool properties in various levels of nesting. At no point is anything else assigned to the local variable (baz in this example).

Actual Behavior
error: Incompatible types in assignment (expression has type "bool", variable has type "Literal[False]")

Your Environment
mypy --version
mypy 0.981 (compiled: yes)
python --version
Python 3.10.6
Mypy command-line flags: None

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 provided nested-if reproduction with mypy 0.981 on Python 3.10.6 and confirm the Literal[False] assignment error. Trace how the checker infers the type of baz across the conditional branches. Done means the valid bool assignment no longer produces this diagnostic, with regression coverage for the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.