python / python/mypy

Incorrect type narrowing when unpacking union of tuple on an existing variable

Open
#12,915 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-0-high topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When unpacking a tuple with Union types over existing variables, some of the types disappear.

To Reproduce

import random


def foo() -> tuple[int, None] | tuple[int, str]:
    if random.choice((True, False)):
        return 0, None
    return 5, "thing"


res = None

status, res = foo()
reveal_type(res)  # builtins.str

Expected Behavior

res should be an Optional[str], not a str.

Actual Behavior

The Optional gets lost in the assignment.

Your Environment

  • Mypy version used: 0.950
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10
  • Operating system and version: Manjaro Linux x86_64 5.15.41-1-MANJARO

This may be related to #9731, but I'm not sure about it.

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

The issue names no repository file or test; start by running the provided reproducer with mypy 0.950 on Python 3.10 and review related issue #9731. Trace tuple-unpacking assignment and type narrowing, with completion shown when reveal_type(res) reports Optional[str] rather than str.

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
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.