python/mypy

Incorrect behavior for functions with keyword-only arguments and **kwargs

jrast opened this issue · 2 comments

jrast commented

Bug Report
mypy reports a arg-type error Argument 2 to "send_command" has incompatible type "**Dict[str, object]"; expected "Optional[float]" [arg-type] for a valid function invocation.

To Reproduce

def send_command(name: str, *, timeout: Optional[float] = None, **params: Any):
    print(name, params, timeout)

send_command("Test", **{"p1": "abc"})

mypy Playground

Expected Behavior
The code above should typecheck without any error.

Actual Behavior
I get the following mypy error:

main.py:7: error: Argument 2 to "send_command" has incompatible type "**Dict[str, str]"; expected "Optional[float]"  [arg-type]

Your Environment

  • Mypy version used: 1.3.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11

See also

I think #11583 might also be somewhat related.

delicb commented

I just bumped into the same problem. After some digging, I found a workaround - create TypedDict with kwargs and explicitly annotate kwargs dict with it. In case of original problem it would look like this: https://mypy-play.net/?mypy=latest&python=3.11&gist=d0a3e2279a7a6147541570967634f0da

This adds a bit of verbosity and for frequently used functions it might be problematic, but maybe it can help someone (I solved my problem, since I have this situation only in one place).