[Python-Dev] Classes with ordered namespaces

Eric Snow ericsnowcurrently at gmail.com
Thu Jun 27 08:03:05 CEST 2013


There are two relevant class namespaces in this proposal: definition
namespace and __dict__.  Currently both are dicts.

For class definition namespaces, I'd like to make the default an
OrderedDict.  With the implementation in issue16991, the change is
trivial (basically 1-liners in 2 spots).  This change would make it
unnecessary to write a custom metaclass just for a __prepare__().  PEP
422 alleviates that problem somewhat.  However, I expect OrderedDict
is by far the most common type returned by __prepare__(), so having it
be the default would proportionately reduce the need for people to
write metaclasses or learn about the PEP 422 API.  You may ask what is
the point if they aren't using a metaclass.  That leads to the other
half of the proposal.

Once I have a class, I'd like to know the definition order without
needing a metaclass.  Unfortunately it's not as simple as using the C
OrderedDict (issue16991 again) for tp_dict, etc.  That change is
actually pretty trivial.  However, it causes problems because the
concrete C API (PyDict_*) doesn't play nice with subclasses and the
concrete API is used on class __dict__ all over the place.  The
alternative I propose is to add __definition_order__ or similar to
classes.  It would be a list of the names from the definition
namespace, in definition order (making use of the new default there).
Having a class's __dict__ be ordered isn't important if the definition
order is available somewhere.  Again, using the C OrderedDict, the
change to add __definition_order__ is pretty trivial.

FWIW, Guido already expressed some approval[1].

-eric


[1] http://mail.python.org/pipermail/python-ideas/2013-February/019704.html


More information about the Python-Dev mailing list