Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inspect.getmembers in order?

Tags:

python

inspect.getmembers(object[, predicate])

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

I want to use this method, but I don't want the members to be sorted. I want them returned in the same order they were defined. Is there an alternative to this method?


My use case is creating a form like so:

class RegisterForm(Form):
    username = Field(model_field='username', filters=validators.minlength(3))
    password1 = Field(model_field='password', widget=widgets.PasswordInput)
    password2 = Field(widget=widgets.PasswordInput)
    first_name = Field(model_field='first_name')
    last_name = Field(model_field='last_name')
    address = SubForm(form=AddressForm, model_field='address')

I want the fields to be rendered in the same order they are defined.

like image 612
mpen Avatar asked Sep 04 '25 01:09

mpen


1 Answers

You can dig around to find the line number for methods, not sure about other members:

import inspect

class A:
    def one(self):
        pass

    def two(self):
        pass

    def three(self):
        pass

    def four(self):
        pass

def linenumber_of_member(m):
    try:
        return m[1].__func__.__code__.co_firstlineno
    except AttributeError:
        return -1

a = A()
l = inspect.getmembers(a)
print(l)
l.sort(key=linenumber_of_member)
print(l)

prints:

[('__doc__', None), ('__module__', '__main__'), ('four', <bound method A.four of <__main__.A instance at 0x0179F738>>), ('one', <bound method A.one of <__main__.A instance at 0x0179F738>>), ('three', <bound method A.three of <__main__.A instance at 0x0179F738>>), ('two', <bound method A.two of <__main__.A instance at 0x0179F738>>)]
[('__doc__', None), ('__module__', '__main__'), ('one', <bound method A.one of <__main__.A instance at 0x0179F738>>), ('two', <bound method A.two of <__main__.A instance at 0x0179F738>>), ('three', <bound method A.three of <__main__.A instance at 0x0179F738>>), ('four', <bound method A.four of <__main__.A instance at 0x0179F738>>)]
like image 146
Ned Batchelder Avatar answered Sep 07 '25 13:09

Ned Batchelder