kwarg unpacking with mypy

Question:

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.

Asked By: user112495

||

Answers:

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)
Answered By: Abdul Niyas P M
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.