Skip to content

Dict unpacking type checks don't consider **kwargs #17642

Closed

Description

@dinatamas

Bug Report:

In the below example (playground gist), mypy behaves differently with respect to **kwargs:

def func(x: bool = False, **kwargs):
    print(x, kwargs)

# This is accepted by mypy.
func(y="y")

# This is flagged by mypy.
data = {"y": "y"}
func(**data)

The error is Argument 1 to "func" has incompatible type "**dict[str, str]"; expected "bool" [arg-type]. This is incorrect because the function has **kwargs, so the dict / function call should be considered type correct.

Your Environment:

  • Mypy version used: latest (1.11.1)
  • Mypy command-line flags: -
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.12

Activity

  1. added
    bug
    on Aug 4, 2024
  2. added
    topic-type-context
    on Oct 15, 2024
  3. dinatamas commented on Dec 1, 2024

    @dinatamas
    Author

    I have overlooked that data may specify x.

    def func(x: bool = False, **kwargs):
        print(x, kwargs)
    
    data = {"x": "a"}
    func(**data)  # warning

    Since mypy has no way to know the content of the dictionary (unless it's a TypedDict or frozendict), it is correct to flag this function call.

    If func only expects strings, mypy accepts this.

    def func(x: str = "text", **kwargs):
        print(x, kwargs)
    
    data = {"x": "a", "y": "b"}
    func(**data)  # ok

    It also accepts this if x is explicitly provided.

    def func(x: bool = False, **kwargs):
        print(x, kwargs)
    
    data = {"y": "b"}
    func(x=True, **data)  # ok
  4. dinatamas commented on Dec 1, 2024

    @dinatamas
    Author

    Hence mypy's behavior is correct and I'm closing this ticket.

  5. added a commit that references this issue on Mar 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugtopic-type-context

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions