Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

Hi! I have a question regarding the typing of a function with keyword-only arguments:
I have the following function:

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

Which is called like this:

# Valid Calls
kwargs = {"p1": "abc", "timeout": 1.0}
send_command("Test", **kwargs)
send_command("Test", a=1, b=2, timeout=10)
# Invalid Calls
send_command("Test", timeout="not a number")  # Wrong type for timeout

With the typehints as shown above, mypy fails on the first call with Argument 2 to "send_command" has incompatible type "**Dict[str, object]"; expected "Optional[float]" [arg-type]

I tried to fix this by adding the following overloads:

@overload
def send_command(name: str, *, timeout: Optional[float], **params: Any):
    ...

@overload
def send_command(name: str, **params: Any):
    ...

However, with those overloads, mypy no longer detects the wrong type for the timeout parameter (third call from above). What would be the correct typehint for this function?

You must be logged in to vote

Replies: 1 comment · 3 replies

Comment options

Unfortunately, mypy is not great at deriving the best type for the dict literal in this case. Try explicitly annotating the dict:

kwargs: dict[str, Any] = {"p1": "abc", "timeout": 1.0}
You must be logged in to vote
3 replies
@jrast
Comment options

I wanted to avoid this... The function is used all over the place.

But for me one question remains: Why does mypy report this as a error on the timeout parameter? For me it seems like mypy expects that the order is relevant in this case, which is not. For example send_command("Test", **{"p1": "abc"}) also fails with the same error, see mypy Playground.

@erictraut
Comment options

This appears to be a bug in mypy. I recommend reporting it in the mypy issue tracker. It type checks as you would expect with pyright.

@jrast
Comment options

Created a bug report here: python/mypy#15317

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
3 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.