Mypy can't correctly infer nested union types in some situations

Open
#3,935 4 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

Start by running the issue's good, bad, and good2 examples with mypy and compare the inferred types for the list literal and concatenation. Trace the nested union and list inference path, then add a regression test showing that bad() is accepted without the cast while existing type-checking behavior remains intact.

Written by the indexing model from the issue text.

Description

topic-union-types

I'm not sure what the cause is here, but I documented some simple examples of this issue. I would expect all of these examples to pass the type checker, but one fails peculiarly. I wouldn't be surprised if this is the result of an existing issue, but I couldn't find it.

from typing import cast, List, Union

Scalar = Union[str, float]


def good() -> List[Scalar]:
    return ["foo", 1.0]


def bad(params: List[Scalar]) -> List[Scalar]:
    # error: Incompatible return value type (got List[object], expected
    # List[Union[str, float]])
    # error: Unsupported operand types for + (List[object] and
    # List[Union[str, float]])
    return ["foo", 1.0] + params


def good2(params: List[Scalar]) -> List[Scalar]:
    return cast(List[Scalar], ["foo", 1.0]) + params
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.