[Python-ideas] Proto-PEP: Preserving the order of **kwargs in a function.

Andrew Barnert abarnert at yahoo.com
Fri Apr 11 05:20:30 CEST 2014


From: Barry Warsaw <barry at python.org>

Sent: Thursday, April 10, 2014 3:04 PM


> Wouldn't another, much less invasive, much more explicit approach be to not
> squash subclasses of dict when passed into **args?
> 
> IOW, the way to preserve order would be:
> 
>>>>  def foo(**kws):
> ...   print(kws)
> ... 
>>>>  from collections import OrderedDict as od
>>>>  foo(**od(a=1, b=2, c=3))
> OrderedDict([('a', 1), ('c', 3), ('b', 2)])
>>>>  # instead of: {'a': 1, 'c': 3, 'b': 2}


I think your own example shows why this doesn't work. You wanted to pass in a=1, b=2, c=3 by passing it through an OrderedDict… but you ended up passing a=1, c=3, b=2 instead. So you've successfully preserved _an_ order in kws, but not the one you wanted.

(Also, a **kws parameter doesn't get a squashed copy of the **d argument in the first place; it gets a new dict, into which things get copied. And the things that get copied aren't the members of d unless both exist, and there are no members of d that match named parameters, and there are no keyword arguments that don't match named parameters. So, I don't think this suggestion is even a coherent solution, much less a successful one. But you could obviously fix that by saying that, e.g., you create a new type(d) instead of a new dict, and then add things to that normally.)


More information about the Python-ideas mailing list