Skip to content

unnecessary-dict-kwargs (PIE804)

Derived from the flake8-pie linter.

Fix is sometimes available.

What it does

Checks for unnecessary dict kwargs.

Why is this bad?

If the dict keys are valid identifiers, they can be passed as keyword arguments directly, without constructing unnecessary dictionary. This also makes code more type-safe as type checkers often cannot precisely verify dynamic keyword arguments.

Example

def foo(bar):
    return bar + 1


print(foo(**{"bar": 2}))  # prints 3

# No typing errors, but results in an exception at runtime.
print(foo(**{"bar": 2, "baz": 3}))

Use instead:

def foo(bar):
    return bar + 1


print(foo(bar=2))  # prints 3

# Typing error detected: No parameter named "baz".
print(foo(bar=2, baz=3))

Fix safety

This rule's fix is marked as unsafe for dictionaries with comments interleaved between the items, as comments may be removed.

For example, the fix would be marked as unsafe in the following case:

foo(
    **{
        # comment
        "x": 1.0,
        # comment
        "y": 2.0,
    }
)

as this is converted to foo(x=1.0, y=2.0) without any of the comments.

References