1

I have a function, that accepts inputs of different types, and they all have default values. For example,

def my_func(a: str = 'Hello', b: bool = False, c: int = 1):
    return a, b, c

What I want to do is define the non-default kwargs in a dictionary, and then pass this to the function. For example,

input_kwargs = {'b': True}
result = my_func(**input_kwargs)

This works fine in that it gives me the output I want. However, mypy complains giving me an error like:

error: Argument 1 to "my_func" has incompatible type "**Dict[str, bool]"; expected "str".

Is there any way to get around this. I don't want to manually enter the keywords each time, as these input_kwargs would be used multiple times across different functions.

user112495
  • 184
  • 9

1 Answers1

2

You can create a class (by inheriting from TypedDict) with class variables that match with my_func parameters. To make all these class variables as optional, you can set total=False.

Then use this class as the type for input_kwargs to make mypy happy :)

from typing import TypedDict

class Params(TypedDict, total=False):
    a: str
    b: bool
    c: int

def my_func(a: str = 'Hello', b: bool = False, c: int = 1):
    return a, b, c

input_kwargs: Params = {'b': True}
result = my_func(**input_kwargs)
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • Thanks, this worked for me, but it turns out it is only required if there are missing parameters. By using the suggested `TypedDict`, the more specific ``` Missing positional arguments "a", "b", "c" ``` is shown, which helps tracking it down – Nicola Nov 12 '22 at 13:43
  • Mypy sometimes doesn't understand the pythonic way. I simply prefer a `# type: ignore`. https://stackoverflow.com/questions/49220022/how-can-mypy-ignore-a-single-line-in-a-source-file . – Eduardo Lucio Dec 21 '22 at 18:58