Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Parameter TypeVar unexpectedly becomes optional when unpacking call results #20219

@exoriente

Description

@exoriente

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions