Quantcast
Channel: User Hubro - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Why doesn't parameter type "Dict[str, Union[str, int]]" accept value of type "Dict[str, str]" (mypy)

$
0
0

I have a type for a dictionary of variables passed to a template:

VariablesDict = Dict[str, Union[int, float, str, None]]

Basically, any dictionary where the keys are strings and the values are strings, numbers or None. I use this type in several template related functions.

Take this example function:

def render_template(name: str, variables: VariablesDict):    ...

Calling this function with a dictionary literal works fine:

render_template("foo", {"key": "value"})

However, if I assign the dictionary to a variable first, like this:

variables = {"key": "value"}render_template("foo", variables)

Mypy gives an error:

Argument 2 to "render_template" has incompatible type "Dict[str, str]"; expected "Dict[str, Union[int, float, str, None]]"

It seems to me that any value of type Dict[str, str] should be safe to pass to a function that expects a parameter of type Dict[str, Union[int, float, str, None]]. Why doesn't that work by default? Is there anything I can do to make this work?


Viewing all articles
Browse latest Browse all 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>