Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type checking a method call with a default argument prior to keyword argument dictionary

Given

def f_with_opt(opt_arg: bool | None = None, **kwargs):
    print(f"{opt_arg=}, {kwargs=}")


def function() -> None:
    kwargs = {"foo": "bar"}
    f_with_opt(**kwargs)


if __name__ == "__main__":
    function()


mypy reports

test.py:7:18: error: Argument 1 to "f_with_opt" has incompatible type "**Dict[str, str]"; expected "Optional[bool]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

How can I properly annotate the methods to avoid this error? I’ve taken a look at https://peps.python.org/pep-0612/ but I don’t think it helps in this case. Or does it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Searching a bit I came across this GitHub issue: https://github.com/python/mypy/issues/5382

And so following this issue, you can fix simply by typing your dictionary with dict[str, Any]
Ex:

    kwargs: dict[str, Any] = {"foo": "bar"}

Or you can create a TypedDict, but depending on what you want to do with your dictionary this may seem a bit overkill.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading