python / python/mypy

Erroneous arg-type error with Mapping and reversed Mapping

Open
#18,436 1 comment 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

I get an arg-type error in MyPy 1.14.1 on the following code using a Union of inverted collections.abc.Mapping:

from collections.abc import Mapping


def fun(x: Mapping[str, int | None] | Mapping[int | None, str]):
    pass


fun({"a": 1, "b": 2})

fun({"a": 1, "b": 2, "c": None})

fun({1: "a", 2: "b"})

fun({1: "a", 2: "b", None: "c"})

The error is:

mypy_type_error.py:12: error: Argument 1 to "fun" has incompatible type "dict[int, str]"; expected "Mapping[str, int | None] | Mapping[int | None, str]" [arg-type]

That is, MyPy takes issue with the parameters in the third function call. The last call including the None key does not produce an error, though. I'd expect the third call to not show an error, either.

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 by running the reported snippet with MyPy 1.14.1 and compare the four calls. Then trace the argument-type checking and union-of-Mapping handling to find the relevant regression-test area; done means the third call is accepted consistently with the fourth without regressing the other examples.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.