You can sort by line numbers using inspect.findsource
. Docstring from the source code of that function:
def findsource(object):
"""Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An OSError
is raised if the source code cannot be retrieved."""
Here's an example in Python 2.7:
import ab.bc.de.t1 as t1
import inspect
def get_functions_from_module(app_module):
list_of_functions = inspect.getmembers(app_module, inspect.isfunction)
return list_of_functions
fns = get_functions_from_module(t1)
def sort_by_line_no(fn):
fn_name, fn_obj = fn
source, line_no = inspect.findsource(fn_obj)
return line_no
for name, fn in sorted(fns, key=sort_by_line_no):
print name, fn
My ab.bc.de.t1
is defined as follows:
class B(object):
def a():
print 'test'
def c():
print 'c'
def a():
print 'a'
def b():
print 'b'
And the output I get when I try retrieving sorted functions is below:
c <function c at 0x00000000362517B8>
a <function a at 0x0000000036251438>
b <function b at 0x0000000036251668>
>>>