Python-按源代码顺序检查.getmembers

You*_*ung 3 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
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Bah*_*rom 5

您可以使用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."""
Run Code Online (Sandbox Code Playgroud)

这是 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
Run Code Online (Sandbox Code Playgroud)

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

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

def c():
    print 'c'

def a():
    print 'a'

def b():
    print 'b'
Run Code Online (Sandbox Code Playgroud)

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

c <function c at 0x00000000362517B8>
a <function a at 0x0000000036251438>
b <function b at 0x0000000036251668>
>>> 
Run Code Online (Sandbox Code Playgroud)


You*_*ung 5

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

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))
Run Code Online (Sandbox Code Playgroud)