Python - inspect.getmembers 源代码顺序

Python - inspect.getmembers in source code order

我正在尝试按照源代码的顺序使用 inspect.getmembers 从模块中获取函数列表。

下面是代码

def get_functions_from_module(app_module):
    list_of_functions = dict(inspect.getmembers(app_module, 
    inspect.isfunction))

    return list_of_functions.values

当前代码不会return按源代码顺序排列的函数对象列表,我想知道是否可以对其进行排序。

谢谢!

您可以使用 inspect.findsource 按行号排序。该函数源代码中的文档字符串:

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."""

这是 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

我的ab.bc.de.t1定义如下:

class B(object):
    def a():
        print 'test'

def c():
    print 'c'

def a():
    print 'a'

def b():
    print 'b'

我尝试检索排序函数时得到的输出如下:

c <function c at 0x00000000362517B8>
a <function a at 0x0000000036251438>
b <function b at 0x0000000036251668>
>>> 

我想我想出了一个解决办法。

def get_line_number_of_function(func):
    return func.__code__.co_firstlineno

def get_functions_from_module(app_module):
        list_of_functions = dict(inspect.getmembers(app_module, 
        inspect.isfunction))

    return sorted(list_of_functions.values(), key=lambda x:
           get_line_number_of_function(x))