I have a dictionary that I use as my “config”. I don’t change values, so it could be immutable. I use its values as arguments for functions via key indexing, something like this:
from typing import Union
my_config: dict[str, Union[int, float, str]] = {
"timeout": 60,
"precision": 3.14,
"greeting": "Hello",
}
def my_function(arg: int):
print(f"The value is: {arg}")
my_function(arg=my_config["timeout"])
Since mypy is a static type checker, it cannot infer the types inside a dictionary. So it will complain:
Argument “arg” to “my_function” has incompatible type “Union[int, float, str]”; expected “int”
What is the proper way to deal with this situation? Some ideas:
from typing import cast
# type cast before call
my_function(arg=int(my_dict["key1"]))
my_function(arg=cast(int, my_dict["key1"]))
Is there more? What is the preferred way to deal with this? Do I have to go back a step and change my approach of using a dict for my_config
? Maybe use a truly immutable data type in the first place?