[Python-Dev] Classes with ordered namespaces

Nick Coghlan ncoghlan at gmail.com
Thu Jun 27 10:48:47 CEST 2013


On 27 June 2013 16:03, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> 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.

I'd be tempted to kill PEP 422 as not worth the hassle if we did this.
Yes, I count that as a point in favour of the idea :)

> 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.

I think the main concern I would have is whether other implementations
are happy they can provide a suitable ordered dictionary for class
namespace execution.

It's also worth considering what would have to happen for dynamically
created types where the namespace passed in *wasn't* ordered.

It's a plausible way forward, though.

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-Dev mailing list