Skip to content

mypy does not infer that a string Literal is a str in the context of a dict or Mapping #18494

Description

@msto

Bug Report

Mypy reports an arg-type error when passing a dictionary with Literal keys to a function typed to receive a dictionary with str keys, even when all such literals are strings.

To Reproduce

fromcollections.abcimportMappingfromtypingimportLiteraldeffoo(mapping: dict[str, str]) ->None:
passdefbar(mapping: Mapping[str, str]) ->None:
passmapping: dict[Literal["key"], str] = {"key": "value"}
foo(mapping) # E: Argument 1 to "foo" has incompatible type "dict[Literal['key'], str]"; expected "dict[str, str]" [arg-type]bar(mapping) # E: Argument 1 to "bar" has incompatible type "dict[Literal['key'], str]"; expected "Mapping[str, str]" [arg-type]

Expected Behavior

Since the literal "key" is a string, I expected mypy to report no error here.

Actual Behavior

Mypy reported the arg-type errors described in the above reprex.

Your Environment

  • Mypy version used: 1.14.1
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
     strict_optional = true
    strict_equality = true
    check_untyped_defs = true
    disallow_incomplete_defs = true
    disallow_untyped_calls = true
    disallow_untyped_decorators = true
    disallow_untyped_defs = true
    no_implicit_optional = true
    warn_no_return = true
    warn_redundant_casts = true
    warn_return_any = true
    warn_unreachable = true
    warn_unused_configs = true
    warn_unused_ignores = true
    enable_error_code = "ignore-without-code"
    
  • Python version used: 3.12.8

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