inspect.getmembers in order?

后端 未结 6 1893
栀梦
栀梦 2021-01-01 10:54
inspect.getmembers(object[, predicate])

Return all the members of an object in a list of (name, value) pairs sorted by nam

6条回答
  •  时光说笑
    2021-01-01 11:33

    I don't think Python 2.6 has a __prepare__ method, so I can't swap out the default dict for an ordered one. I can, however, replace it using a metaclass and the __new__ method. Instead of inspecting line numbers, I think its easier and more efficient to just use a creation counter.

    class MetaForm(type):
        def __new__(cls, name, bases, attrs):
            attrs['fields'] = OrderedDict(
                sorted(
                    [(name, attrs.pop(name)) for name, field in attrs.items() if isinstance(field, Field)],
                    key=lambda t: t[1].counter
                )
            )
            return type.__new__(cls, name, bases, attrs)
    
    class Form(object):
        __metaclass__ = MetaForm
    
    class Field(object):
        counter = 0
        def __init__(self):
            self.counter = Field.counter
            Field.counter += 1
    

提交回复
热议问题