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

Eric V. Smith eric at trueblade.com
Fri Apr 12 13:16:55 EDT 2019


On 4/12/2019 11:29 AM, Rhodri James wrote:
> On 12/04/2019 16:10, Viktor Roytman 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.
> 
> What circumstance do you want to do this in that simply passing the 
> dictionary as itself won't do for?

I don't want to speak for the OP, but I have a similar use case (which 
is why I wrote calllib). My use case is: I have number of callables that 
I don't control. I also have a dict of parameters that the callables 
might take as parameters. I want to call one of the callables, passing 
only the subset of parameters that that particular callable takes.

Eric


More information about the Python-ideas mailing list