Re-ordered to avoid top-posting...

On 12/04/2019 18:50, Viktor Roytman wrote:
On Friday, April 12, 2019 at 12:57:43 PM UTC-4, 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"],
      )

Hang on, I missed this first time around. This gives you exactly the same problem:

        Python 3.6.7 (default, Oct 22 2018, 11:32:17)
        [GCC 8.2.0] on linux
        Type "help", "copyright", "credits" or "license" for more information.
        >>> def func(*, a):
        ...     pass
        ...
        >>> d = {"a":1, "b":2}
        >>> func(**d)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: func() got an unexpected keyword argument 'b'
        >>> func(a=d["a"], b=d["b"])
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: func() got an unexpected keyword argument 'b'
        >>>

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?

Any time I am using a function from a library that accepts keyword
arguments. For example, an ORM model constructor that accepts fields as
keyword arguments (like Django).

That's not the same issue at all, if I'm understanding you correctly. In any case, surely you need to do some validation on your dictionary of keyword arguments? Otherwise you are setting yourself up for a world of pain. If you do that, you should take the opportunity to decide what to do with invalid keys.

--
Rhodri James *-* Kynesim Ltd
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to