Python - 源代码顺序中的inspect.getmembers

时间:2017-11-02 18:37:35

标签: python inspect

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

以下是代码

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

    return list_of_functions.values

当前代码不会按源代码的顺序返回函数对象列表,我想知道是否可以订购它。

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用inspect.findsource按行号排序。来自该函数源代码的Docstring:

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

答案 1 :(得分:4)

我想我想出了一个解决方案。

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))