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

Lucas Bourneuf lucas.bourneuf at inria.fr
Fri Apr 12 12:17:28 EDT 2019


Hello !

I made *fief*, a small python package allowing just that using a decorator:

    from fief import filter_effective_parameters as fief

    @fief
    def func(a, b):
        # some implementation

    # and then, use it as you want to:
    func(**MY_BIG_CONFIG_DICT_WITH_MANY_WEIRD_KEYS)

The code is quite simple. You may want to use it, with modifications (i didn't touch the code for months, maybe years ; it could probably be improved now).
Link: https://github.com/aluriak/fief

The code:

def filter_effective_parameters(func):
    """Decorator that filter out parameters in kwargs that are not related to
    any formal parameter of the given function.
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        formal_parameters = frozenset(signature(func).parameters.keys())
        return func(*args, **{
            arg: value
            for arg, value in kwargs.items()
            if arg in formal_parameters
        })
    return wrapper

Best regards,
--lucas



----- Mail original -----
> De: "Viktor Roytman" <viktor.roytman at gmail.com>
> À: "python-ideas" <python-ideas at googlegroups.com>
> Envoyé: Vendredi 12 Avril 2019 18:01:43
> Objet: Re: [Python-ideas] Syntax for allowing extra keys when unpacking a dict as keyword arguments

> I could see this being an option, but to someone unfamiliar with it, it
> might seem strange that * unpacks iterables, ** unpacks dicts, and *** is a
> special thing only for keyword arguments that mostly behaves like **.
> 
> On Friday, April 12, 2019 at 11:26:37 AM UTC-4, Bruce Leban wrote:
>>
>>
>> On Fri, Apr 12, 2019, 8:12 AM Viktor Roytman <viktor... at gmail.com
>> <javascript:> wrote:
>>
>>>
>>>     >>> func(**{'a': 1, 'b': 2})
>>>     Traceback (most recent call last):
>>>       File "<stdin>", line 1, in <module>
>>>     TypeError: func() got an unexpected keyword argument 'b'
>>>
>>
>> Perhaps func(***kws)?
>>
>> I think this is a real problem given the frequent convention that you can
>> freely add fields to json objects with the additional fields to be ignored.
>>
> 
> _______________________________________________
> 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/


More information about the Python-ideas mailing list