python / python/mypy

Parameter TypeVar unexpectedly becomes optional when unpacking call results

Open
#20,219 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-context
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When calling a generic function mypy unexpectedly introduces optionality in the TypeVar when the result is unpacked and raises an error on a perfectly valid function call:

from typing import Iterable


def fun[T](values: Iterable[T], value: list[T]) -> tuple[T | None, T | None]:
    ...
    return None, None


values: Iterable[int]
my_list: list[int]

result = fun(values, my_list)  # works fine
m, n = result

a, b = fun(values, my_list)  # raises error in mypy

Mypy error:

main.py:15: error: Argument 2 to "fun" has incompatible type "list[int]"; expected "list[int | None]"  [arg-type]

This has something to do with the return type of the function being a tuple of optional T's. If the return type is not a union with None or not a tuple, the error disappears.

To reproduce

Here is playground gist of the example: gist

Expected Behavior

In the example I expect both calls to be approved by mypy. Also, I don't expect unpacking to influence what arguments can given in a function call, at least not in this case.

Actual Behavior

mypy raises an error on the second call.

Your Environment

I used mypy playground to confirm this error in various versions:

  • Mypy version used: 1.17.1 1.18.2 master branch
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12 3.13 3.14

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 generic-function example in the issue and run it against mypy with the reported Python versions and configurations. Trace type inference for tuple unpacking and optional TypeVars; done means both calls are accepted without introducing an incompatible list[int | None] expectation.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.