[Python-3000] PEP for Metaclasses in Python 3000

Jack Diederich jackdied at jackdied.com
Sat Mar 10 01:26:52 CET 2007


On Fri, Mar 09, 2007 at 12:44:36PM -0800, Talin wrote:
> I had a conversation with Guido last night at the Python user's group 
> meeting, and we hashed out some of the details of how metaclasses should 
> work. I've gone ahead and written up a PEP, which I present for your review.
> --------------------------------------------
> PEP: xxx
> Title: Metaclasses in Python 3000
> Version: $Revision$
> Last-Modified: $Date$
> Author: Talin <talin at acm.org>
> Rationale
> 
>      There are two rationales for this PEP, both of which are somewhat
>      subtle.
> 
>      In particular, there is an important body of use cases where it
>      would be useful to preserve the order in which a class members are
>      declared. Ordinary Python objects store their members in a
>      dictionary, in which ordering is unimportant, and members are
>      accessed strictly by name. However, Python is often used to
>      interface with external systems in which the members are organized
>      according to an implicit ordering. Examples include declaration of C
>      structs; COM objects; Automatic translation of Python classes into
>      IDL or database schemas, such as used in an ORM; and so on.
> 
> Alternate Proposals
> 
>      Another good suggestion was to simply use an ordered dict for all
>      classes, and skip the whole 'custom dict' mechanism. This was based
>      on the observation that most use cases for a custom dict were for
>      the purposes of preserving order information. However, this idea has
>      two drawbacks, first because it means that an ordered dict
>      implementation would have to be added to the set of built-in types
>      in Python, and second because it would impose a slight speed (and
>      complexity) penalty on all class declarations.
<heavy snipping>

(I just posted a much expanded class decotator PEP so read that first if
 you haven't already.)

I am a very big fan of ordered dicts in classes.  One possibility is that
suites in classes always store their order in a special dict that keeps a 
side list of key order.  A final invisible class decorator around
every class would then toss out the order and leave only a regular dict.

An advantage is that the order of the keys would be available to both
metaclasses and class decorators.  It would also require no changes in
signature for either.  As far as I can tell ordered dicts are the only
demonstrated use case (and common! looking at any SQL/ORM library).

People that really wanted to maintain order forever could make a copy
of the original order and then implement magic methods to keep the list
up to date.  In my personal use cases I would use the ordering at class 
creation time and then never need it again.

-Jack


More information about the Python-3000 mailing list