[Python-ideas] Ordered storage of keyword arguments

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Sat Oct 30 02:19:33 CEST 2010

On Fri, Oct 29, 2010 at 1:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> Given that the need to care about the order of keyword arguments is likely
> to be rare, I'd like to see some recipes and/or metaclass helpers  before
> changing the language.

The recipe is more or less directly in PEP 3115 (the PEP which
established the __prepare__ attribute). There's not a lot to it.

>>> class OrderedMetaclass(type):
...     @classmethod
...     def __prepare__(metacls, name, bases): # No keywords in this case
...         return OrderedDict()
...     def __new__(cls, name, bases, classdict):
...         result = type.__new__(cls, name, bases, dict(classdict))
...         result.odict = classdict
...         return result
>>> class OrderedClass(metaclass=OrderedMetaclass):
...     a = 1
...     z = 2
...     b = 3
>>> OrderedClass.odict
OrderedDict([('__module__', '__main__'), ('a', 1), ('z', 2), ('b', 3)])

Thinking about it a little more, if I were making an HTML tree type
metaclass though, I wouldn't want to use an OrderedDict anyway, since
it can't have duplicate elements, and I would want the interface to be
something like:

class body(Tree()):
    h1 = "Hello World!"
    p  = "Lorem ipsum."
    p  = "Dulce et decorum est."
    class div(Tree(id="content")):
        p = "Main thing"
    class div(Tree(id="footer")):
        p = "(C) 2010"

So, I'd probably end up making my own custom kind of dict that didn't
overwrite repeated names.

Of course, for an ORM, you don't want repeated field names, so an
OrderedDict would work.

Anyway, this just goes to show how limited the applicability of
switching to an odict in Python internals is.

More information about the Python-ideas mailing list