[Python-Dev] PEP 372 -- Adding an ordered directory to collections ready for pronouncement
ncoghlan at gmail.com
Wed Mar 4 13:25:42 CET 2009
Lie Ryan wrote:
How about making odict ordered by insertion order, then provide an
> optional argument for defining sorter? This optional argument must be a
> function/lambda/callable object and must be the first argument.
As the PEP mentions (and Hrvoje brought up again already in this
thread), a hash table (i.e. dict) probably isn't the right data
structure to use as the basis for an "always sorted" container.
In-memory databases, balanced trees, etc, etc.
Further, unlike a more general "sorted" dictionary, an insertion ordered
dict already has specific use cases in the standard library.
ConfigParser will use it by default in 2.7/3.1 and namedtuple._asdict()
is being changed in those versions to return an OrderedDict so that
iterating over the result of _asdict() will process the fields in the
same order as iterating over the tuple itself.
It is also being added because an insertion ordered dictionary was the
primary example for the new metaclass __prepare__ method introduced by
PEP 3115. Adapting the example from that PEP:
# The metaclass
def __prepare__(metacls, name, bases): # No keywords in this case
def __new__(cls, name, bases, classdict):
# Note that we replace the classdict with a regular
# dict before passing it to the superclass, so that we
# don't continue to record the order after the class
# has been created.
result = type.__new__(cls, name, bases, dict(classdict))
result.member_names = list(classdict.keys())
# An instance of the metaclass
# This dummy example uses types directly, but something
# like struct module format codes may make more sense
field1 = int
field2 = float
field3 = customType
trailingField = str
Unlike a normal class definition, the order of the field definitions in
structure matters, and in the example above, this information is
preserved by the metaclass. This can greatly simplify the process of
defining types where the order of the fields matters (e.g. so the values
can be serialised in the correct order for a binary translation of some
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev