Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Empty dictionary argument is incompatible with union of mappings #14804

Open
tobast opened this issue Feb 28, 2023 · 1 comment
Open

Empty dictionary argument is incompatible with union of mappings #14804

tobast opened this issue Feb 28, 2023 · 1 comment
Labels
bug mypy got something wrong topic-inference When to infer types or require explicit annotations

Comments

@tobast
Copy link

tobast commented Feb 28, 2023

Bug Report

When calling a function that calls for an argument of type Union[Mapping[x,z], Mapping[y,z]], the empty dictionary {} does not type-check.

I encountered this problem when trying to call subprocess.run with an empty environment, that is,

subprocess.run(..., env={})

To Reproduce

The smallest I've been able to reduce this issue to is the following code:

from typing import Optional, Union, Mapping
from os import PathLike


def foo(
    x: Union[
        Mapping[bytes, str],
        Mapping[str, str],
    ]
):
    pass


foo({})

Expected Behavior

I expect this code to type check, as the empty dictionary {} type checks against both sides of the Union — that is, if I remove the Union from the above code and leave only either side, mypy reports no issue.

Actual Behavior

Mypy reports an incompatible type:

test.py:14: error: Argument 1 to "foo" has incompatible type "Dict[<nothing>, <nothing>]"; expected "Union[Mapping[bytes, str], Mapping[str, str]]"  [arg-type]

If I break down the call to foo into

arg = {}
foo(arg)

mypy now complains that arg must be type annotated.

Your Environment

  • Mypy version used: 1.0.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini: none
  • Python version used: 3.10.9
@tobast tobast added the bug mypy got something wrong label Feb 28, 2023
@AlexWaygood AlexWaygood added the topic-inference When to infer types or require explicit annotations label Feb 28, 2023
@wxgeo
Copy link

wxgeo commented Mar 5, 2023

I ran into the same bug today. Minimal example:

def f() -> dict[int, str] | dict[int, float]:
    return {}

error: Incompatible return value type (got "Dict[<nothing>, <nothing>]", expected "Union[Dict[int, str], Dict[int, float]]")

Note that using this in a simple affectation, like d: dict[int, str] | dict[int, float] = {}, will result in the same error message.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-inference When to infer types or require explicit annotations
Projects
None yet
Development

No branches or pull requests

3 participants