[Python-ideas] Let's be more orderly!

Jonathan Eunice jonathan.eunice at gmail.com
Tue May 14 21:53:53 CEST 2013

Python’s nicely evolved its standard data structures. Bringing set into the 
core, adding OrderedDict (and friends), and establishing collections 
ABCs—all these up-level common facilities, broadly improving program 
clarity and correctness.

I’d like Python to take the next step, especially regarding ordering.

Using a compatible, separate implementation for OrderedDict is a fine way 
to gracefully extend the language, but it leaves ordering only 
half-accomodated. Consider:

OrderedDict(a=2, b=3, c=7)


OrderedDict([('a', 2), ('c', 7), ('b', 3)])

The items are immediately disordered, having been jumbled passing through a 
conventional dict. One can initialize using a list of items, of course, but 
that reminds me of the line from NetHack: “You enter what seems to be an 
older, more primitive world.”

Everyone rightly accepts doing a bit more specification for truly “extra” 
data structure features—persistence, say. And if falling back to lists of 
tuples is the best that can be done for ordered structures, well, okay. 
We’ll live with it.

But from an app developer’s point of view, ordering is a basic, essential 
property. It seems like something that should be gracefully accommodated, 
as a built-in, rather than as “an extra” or something that requires falling 
back to Late Medieval Python. kwargs arrived in 1.4, back in 1996, right?

So I propose that kwargs, at least, default to an ordered mapping rather 
than a pure hash mapping. Ideally, {...}  literals would also be ordered. I 
suspect this will be an unpopular idea among implementers, for whom 
unordered dict is a pervasive and long-optimized tool. But this is a 
correctness, or at least a consistency, issue. I don’t see any elegant 
alternative way to initialize ordered data structures unless the modern 
Python initialization idiom(s), esp. kwargs, themselves observe order.

Historically, sort features were usually unstable because that’s easier to 
implement and faster to run. Over time, stable sort has become the norm, 
either as an option (e.g. GNU’s sort --stable, Perl’s use sort 'stable' as 
of 5.8) or implicitly (e.g. Python’s sorted, as of 2.2). Over time, getting 
better results proved more broadly important than getting near-correct 
results faster; and both by code optimization and system improvement, the 
associated time or space cost of stable ordering was mooted. I’d like the 
same to happen for Python mappings. It’s my understanding that Ruby 1.9 has 
recently made this shift.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130514/b673a2c1/attachment.html>

More information about the Python-ideas mailing list