[Python-Dev] Ordering keyword dicts

Ron Adam ron3200 at gmail.com
Mon Jun 10 17:08:46 CEST 2013

On 06/09/2013 10:13 PM, Alexander Belopolsky wrote:
> On Sun, May 19, 2013 at 1:47 AM, Guido van Rossum <guido at python.org
> <mailto:guido at python.org>> wrote:
>     I'm slow at warming up to the idea. My main concern is speed -- since
>     most code doesn't need it and function calls are already slow (and
>     obviously very common :-) it would be a shame if this slowed down
>     function calls that don't need it noticeably.

And we could remove this bit from the docs...

The OrderedDict constructor and update() method both accept keyword
arguments, but their order is lost because Python’s function call semantics
pass-in keyword arguments using a regular unordered dictionary.

> Here is an idea that will not affect functions that don't need to know the
> order of keywords: a special __kworder__ local variable.  The use of this
> variable inside the function will signal compiler to generate additional
> bytecode to copy keyword names from the stack to a tuple and save it in
> __kworder__.

I like the idea of an ordered dict acting the same as a regular dict with 
an optional way to access order.  It also will catch uses of unordered 
dicts in situations where an ordered dict is expected by having the ordered 
key words accessed in a way that isn't available in unordered dicts.

I don't care for a magic local variable inside of a function.

> With that feature, an OrderedDict constructor, for example
> can be written as
> def odict(**kwargs):
>        return OrderedDict([(key, kwargs[key]) for key in __kworder__])

There is two situations where this would matter...  The packing of 
arguments when **kwargs is used in the function definition, and the 
unpacking of arguments when **kwargs is used in the function call.

By having the unpackng side also work with ordered dicts, maybe we could 
then replace the many *very common* occurrences of (*args, **kwargs) with 
just (**all_args) or (***all_args).  :)

It's the unordered nature of dictionaries that requires *args to be used 
along with **kwargs when forwarding function arguments to other functions.

Another variation of this is to have a way to forward a functions 
"signature name space" to another function directly and bypass the 
signature parsing those cases.


More information about the Python-Dev mailing list