python / python/mypy

Incorrect constraint inference for unions with nested generics

Open
#9,435 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

🐛 Bug Report

From my search, it looks like an issue similar to #6417, but happening to unions of generic and nested generic.
mypy has troubles with inferring a proper constraint and passing a nested generic to function that should accept such nested generic fails.
The issue can be worked around with @overloads.

To Reproduce

Minimum reproduction:

from typing import List, TypeVar, Union

_T = TypeVar("_T")


def func(param: Union[List[_T], List[List[_T]]]) -> _T:
    ...

func([1])
func([[1]])

A more real-live example of where this is an issue is tornado's gen function (overloads there are the part of workaround for this issue):
https://github.com/tornadoweb/tornado/pull/2909/files

Expected Behavior

No errors.

Actual Behavior

main.py:10: error: Argument 1 to "func" has incompatible type "List[List[int]]"; expected "Union[List[<nothing>], List[List[<nothing>]]]"

Your Environment

  • Mypy version used: 0.781
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.8.5
  • Operating system and version: Windows 10

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 main.py and verify the differing behavior for func([1]) and func([[1]]) under mypy. Trace the constraint inference path for Union[List[_T], List[List[_T]]] and compare it with the related issue #6417 and the overload workaround in the linked Tornado pull request. Done means both calls type-check without 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.