[Python-ideas] Ordered storage of keyword arguments

Antoine Pitrou solipsis at pitrou.net
Fri Oct 29 11:38:41 CEST 2010


Le vendredi 29 octobre 2010 à 11:15 +0200, M.-A. Lemburg a écrit :
> 
> Would other Python implementations be able to provide the
> same information ?

Probably, yes.

> Can this be generalized to arbitrary classes ?

In CPython, it could be done by modifying the default __build_class__
function (which always gets called regardless of metaclasses and other
stuff). Of course, it won't work if the metaclass forbids setting
attributes on the class object.

Here's a pure Python prototype:


import builtins, types

_old_build_class = builtins.__build_class__

def __build_class__(func, name, *bases, **kwds):
    cls = _old_build_class(func, name, *bases, **kwds)
    # Extract the code object used to create the class namespace
    co = func.__code__
    cls.__deforder__ = tuple(n for n in co.co_names
                             if n in cls.__dict__)
    return cls

builtins.__build_class__ = __build_class__

class C: 
    y = 5
    z = staticmethod(len)
    def x():
        pass

print(C.__deforder__)





More information about the Python-ideas mailing list