You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
mypy does not infer that a string Literal is a str in the context of a dict or Mapping #18494
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):
Activity
sterliakov commentedon Jan 20, 2025
Mappingis invariant in key type, soMapping[Literal['a'], str]can't be assigned toMapping[str, str].See, for example, an old python/typing#273 for discussion of this limitation.