python / python/mypy

Errors when calling a function that has **kwargs and default value parameter (non-trivial type)

Open
#8,862 0 comments 18 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-calls
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Hello, when I declare a function that has **kwargs along with another parameter with a default value, mypy reports errors when trying to call this function without the default argument.

Repro

def foo(option: bool = None, **kwargs):
    pass

def bar(option: str = '', **kwargs):
    pass


d = {'test': True}

foo(**{'test': True})
foo(**d)
foo(other_option=True, option=True, **d)
foo(option=True, **{'test': True})

bar(**{'test': True})  # Error
bar(**d)  # Error
bar(other_option=True, **d)  # Error
bar(option='Hello, world!', **{'test': True})

Mypy output:

test.py:15: error: Argument 1 to "bar" has incompatible type "**Dict[str, bool]"; expected "str"
test.py:16: error: Argument 1 to "bar" has incompatible type "**Dict[str, bool]"; expected "str"
test.py:17: error: Argument 2 to "bar" has incompatible type "**Dict[str, bool]"; expected "str"
Found 3 errors in 1 file (checked 1 source file)

Other failing inputs

From my observations: default parameters with {bool, int, float} types work fine (like the foo function). But if the default parameter has type of any of the following types:

  • Custom classes
  • Enums
  • bytes
  • str

mypy will report errors.

Expected result

foo and bar should behave the same way (e.g. no errors).

Versions

mypy 0.770 and Python 3.8.2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the reported reproducer with the current mypy test setup and trace how calls using **kwargs are checked when another parameter has a non-trivial default type. Add regression coverage for the shown bar calls and confirm they produce no errors while incompatible explicit arguments remain diagnosed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.