I would like to pass a dictionary to a method foo
that expects a TypedDict
without explicitly mentioning the type. When I pass the dictionary directly to the method, everything is good. However, when I assign the dictionary to a variable configs
first, mypy complains about incompatible types. Interestingly, PyCharm does not complain about foo(configs)
as long as configs
contains the correct keys and values. I could add type information to configs
at [1] below but wonder if I could improve the typing to make the usage of foo
and Params
less verbose.
from typing import TypedDict
class Params(TypedDict):
a: str
b: str
def foo(config: Params):
pass
foo({"a": "a", "b": "b"}) # Okay
configs = {"a": "a", "b": "b"} # [1]
foo(configs) # error: Argument 1 to "foo" has incompatible type "dict[str, str]"; expected "Params" [arg-type]