python / python/mypy

Failure to narrow down type of elements of Tuple

Open
#9,159 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

false-positive feature priority-2-low topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

  • Are you reporting a bug, or opening a feature request?
    kind of both

  • Please insert below the code you are checking with mypy,

from typing import Optional, Tuple, TypeVar

_T = TypeVar("_T")
_U = TypeVar("_U")


def promote_optional(tup: Tuple[Optional[_T], Optional[_U]]) -> Optional[Tuple[_T, _U]]:
    for val in tup:
        if val is None:
            return None
    return tup

def promote_optional2(tup: Tuple[Optional[_T], Optional[_U]]) -> Optional[Tuple[_T, _U]]:
    if tup[0] is None:
        return None
    if tup[1] is None:
        return None
    return tup
  • What is the actual behavior/output?
/tmp/mwe.py:11: error: Incompatible return value type (got "Tuple[Optional[_T], Optional[_U]]", expected "Optional[Tuple[_T, _U]]")
/tmp/mwe.py:19: error: Incompatible return value type (got "Tuple[Optional[_T], Optional[_U]]", expected "Optional[Tuple[_T, _U]]")
Found 2 errors in 1 file (checked 1 source file)
  • What is the behavior/output you expect?
    Mypy should accept the code.

  • What are the versions of mypy and Python you are using?
    mypy 0.782

I want to turn a Tuple[Optional...] to an Optional[Tuple], because the whole tuple is worthless if it contains any None. Unfortunately Mypy seems to be unable to detect that I checked all elements of the tuple for being 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 with the minimal reproduction in /tmp/mwe.py and run it against mypy to confirm the current errors. Trace how mypy narrows tuple element types after the None checks; done means both promote_optional functions are accepted with no incompatible return-type errors.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.