Skip to content

Error using list with union #9555

@woile

Description

@woile

Bug Report

Given a list of union types, if a list with one of the accepted types in the union is used, mypy throws an error.

I've tried following the link suggested in the error message, but I'm just describing types, no inference, as shown in the docs. Also I'm not sure I understand the issue properly. I've tried searching, but, I didn't find any help, and I'm not sure how to describe it better in order to search, sorry if it was published already.

This behavior was not happening before, we got some new PRs that failed CI because of this recently.

To Reproduce

from typing import List, Union, Dict, Any

names: List[str] = ["mike", "wazowski"]


def what(items: List[Union[str, Dict[str, Any]]]):
    ...

what(names)

Expected Behavior

No error, because List[str] is one of the accepted values of List[Union[str, Dict[str, Any]]]

Actual Behavior

Argument 1 to "what" has incompatible type "List[str]"; expected "List[Union[str, Dict[str, Any]]]"
"List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance

Your Environment

  • Mypy version used:
mypy==0.770
mypy-extensions==0.4.3
  • Mypy command-line flags: mypy src/
  • Mypy configuration options from mypy.ini (and other config files):
[mypy]
files = src, tests
ignore_missing_imports = true
disallow_untyped_decorators = True
disallow_subclassing_any = True
warn_redundant_casts = True
warn_unused_ignores = True
warn_unused_configs = True
  • Python version used: 3.7.6
  • Operating system and version: Ubuntu 20.04.1 LTS x86_64

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions