Search code examples
pythonmypykeyword-argument

kwarg unpacking with mypy


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.


Solution

  • 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)