Using an OrderedDict for __dict__ in Python 3 using __prepare__

Christian Heimes lists at cheimes.de
Sun Jan 8 21:46:17 EST 2012


Am 09.01.2012 03:21, schrieb Steven D'Aprano:
> What am I doing wrong?

You aren't doing anything wrong. It's just not possible to have
something different than a dict as a type's __dict__. It's a deliberate
limitation and required optimization. The __prepare__ hook allows to you
have a dict subclass as intermediate dict, but in the end it always
comes down to a dict.

The code in Objects/typeobject.c:type_new() copies the dict:

    /* Initialize tp_dict from passed-in dict */
    type->tp_dict = dict = PyDict_Copy(dict);

PyDict_Copy() takes an instance of a PyDict_Type subclass and always
returns a PyDictObject.

However you can use the __prepare__ hook to *remember* the order of
insertion, see
http://docs.python.org/py3k/reference/datamodel.html#customizing-class-creation

Christian




More information about the Python-list mailing list