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.
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>>)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With