Is it possible to pass an OrderedDict instance to a function which uses the **kwargs
syntax and retain the ordering?
What I'd like to do is :
def I_crave_order(**kwargs):
for k, v in kwargs.items():
print k, v
example = OrderedDict([('first', 1), ('second', 2), ('third', -1)])
I_crave_order(**example)
>> first 1
>> second 2
>> third -1
However the actual result is:
>> second 2
>> third -1
>> first 1
ie, typical random dict ordering.
I have other uses where setting the order explicitly is good, so I want to keep **kwargs
and not just pass the OrderedDict as a regular argument
As of Python 3.6, the keyword argument order is preserved. Before 3.6, it is not possible since the
OrderedDict
gets turned into adict
.The first thing to realize is that the value you pass in
**example
does not automatically become the value in**kwargs
. Consider this case, wherekwargs
will only have part ofexample
:Or this case, where it will have more values than those in example:
Or even no overlap at all:
So, what you're asking for doesn't really make sense.
Still, it might be nice if there were some way to specify that you want an ordered
**kwargs
, no matter where the keywords came from—explicit keyword args in the order they appear, followed by all of the items of**example
in the order they appear inexample
(which could be arbitrary ifexample
were adict
, but could also be meaningful if it were anOrderedDict
).Defining all the fiddly details, and keeping the performance acceptable, turns out to be harder than it sounds. See PEP 468, and the linked threads, for some discussion on the idea. It seems to have stalled this time around, but if someone picks it up and champions it (and writes a reference implementation for people to play with—which depends on an
OrderedDict
accessible from the C API, but that will hopefully be there in 3.5+), I suspect it would eventually get into the language.By the way, note that if this were possible, it would almost certainly be used in the constructor for
OrderedDict
itself. But if you try that, all you're doing is freezing some arbitrary order as the permanent order:Meanwhile, what options do you have?
Well, the obvious option is just to pass
example
as a normal argument instead of unpacking it:Or, of course, you can use
*args
and pass the items as tuples, but that's generally uglier.There might be some other workarounds in the threads linked from the PEP, but really, none of them are going to be better than this. (Except… IIRC, Li Haoyi came up with a solution based on his MacroPy to pass order-retaining keyword arguments, but I don't remember the details. MacroPy solutions in general are awesome if you're willing to use MacroPy and write code that doesn't quite read like Python, but that isn't always appropriate…)
When Python encounters the
**kwargs
construct in a signature, it expectskwargs
to be a "mapping", which means two things: (1) to be able to callkwargs.keys()
to obtain an iterable of the keys contained by the mapping, and (2) thatkwargs.__getitem__(key)
can be called for each key in the iterable returned bykeys()
and that the resulting value is the desired one to be associated for that key.Internally, Python will then "transform" whatever the mapping is into a dictionary, sort of like this:
This looks a little silly if you think that
kwargs
is already adict
-- and it would be, since there is no reason to construct a totally equivalentdict
from the one that is passed in.But when
kwargs
is not necessarily adict
, then it matters to bring its contents down into a suitable default data structure so that the code which carries out the argument unpacking always knows what it's working with.So, you can mess with the way a certain data type gets unpackaged, but because of the conversion to
dict
for the sake of a consistent arg-unpacking-protocol, it just happens that placing guarantees on the order of argument unpacking is not possible (sincedict
doesn't keep track of the order in which elements are added). If the language of Python brought**kwargs
down into anOrderedDict
instead of adict
(meaning that the keys' order as keyword args would be the order in which they are traversed), then by passing either anOrderedDict
or some other data structure wherekeys()
respects some kind of ordering, you could expect a certain ordering on the arguments. It's just a quirk of the implementation thatdict
is chosen as the standard, and not some other type of mapping.Here's a dumb example of a class that can "be unpacked" but which always treats all unpacked values as 42 (even though they aren't really):
Then define a function to print the unpacked contents:
and make a value and try it out:
This customized delivery of key-value pairs (here, dumbly always returning 42) is the extent of your ability to tinker with how
**kwargs
works in Python.There is slightly more flexibility for tinkering with how
*args
gets unpackaged. For more on that see this question: < Does argument unpacking use iteration or item-getting? >.This is now the default in python 3.6.
It's not possible to do it before as noted by the other answers.