[Python-ideas] Syntax for allowing extra keys when unpacking a dict as keyword arguments

Nathaniel Smith njs at pobox.com
Fri Apr 12 14:55:30 EDT 2019

I don't think it's possible to make this work reliably. In particular, it's
an important feature of python that you can make wrappers that pass through
arguments and are equivalent to the original function:

def original(a=0):

def wrapper(*args, **kwargs):
    return original(*args, **kwargs)

Right now these can be called in exactly the same ways. But with the
proposal they would become different:

# ok
original(***{"a": 1, "b": 2})
# raises TypeError
wrapper(***{"a": 1, "b": 2})

The problem is that the extra star gets lost when passing through the

In this case you might be able to fix this by using functools.wraps to fix
up the signature introspection metadata, but that doesn't work in more
complex cases (e.g. when the wrapper adds/removes some args while passing
through the rest). In Python, signature introspection is a best-effort
thing, and IME not super reliable.


On Fri, Apr 12, 2019, 08:11 Viktor Roytman <viktor.roytman at gmail.com> wrote:

> Currently, unpacking a dict in order to pass its items as keyword
> arguments to a function will fail if there are keys present in the dict
> that are invalid keyword arguments:
>     >>> def func(*, a):
>     ...     pass
>     ...
>     >>> func(**{'a': 1, 'b': 2})
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     TypeError: func() got an unexpected keyword argument 'b'
> The standard approach I have encountered in this scenario is to pass in
> the keyword arguments explicitly like so
>     func(
>         a=kwargs_dict["a"],
>         b=kwargs_dict["b"],
>         c=kwargs_dict["c"],
>     )
> But this grows more cumbersome as the number of keyword arguments grows.
> There are a number of other workarounds, such as using a dict
> comprehension to select only the required keys, but I think it would be
> more convenient to have this be a feature of the language. I don't know
> what a nice syntax for this would be, or even how feasible it is.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190412/d5bb9d58/attachment-0001.html>

More information about the Python-ideas mailing list