按照它们在文件中出现的顺序获取Python模块中所有函数的名称列表?

时间:2012-01-24 00:17:57

标签: python reflection

globals函数返回包含模块中函数的字典,dir函数返回一个列表,其中包含模块中函数的名称,但它们按字母顺序排列或在字典里。

有没有办法按照它们在文件中出现的顺序获取模块中所有函数的名称?

2 个答案:

答案 0 :(得分:2)

这是我的解决方案。将源文件作为字符串读入,过滤掉以def开头的行,去掉前导空格并提取第一个空格和第一个左边的子字符串。

def extract_fns(filename):
    with open(filename) as f:
        lines = f.readlines()
        return [line.split(' ', 1)[1].split('(')[0] for line in lines
            if line.strip().startswith('def')]

答案 1 :(得分:0)

当我有这样的需要时,我使用了装饰师。

def remember_order(func, counter=[0]):
    func._order = counter[0]
    counter[0] += 1
    return func

@remember_order
def foo():
    print "foo"

@remember_order
def bar():
    print "bar"

@remember_order
def baz():
    print "baz"

是的,您必须单独装饰每个功能。正如他们所说,明确比隐含更好,并且因为你做了一些不自然的事情,所以尽可能明白地说出它是好的。

现在您想按照定义的顺序获取所有修饰函数吗?

import sys
module = sys.modules[__name__]   # get reference to current module
# you could also use a reference to some other module where the functions are

# get the functions in the order defined
funcs = sorted((func for func in
              (getattr(module, name) for name in dir(module))
              if callable(func) and hasattr(func, "_order")),
              key = lambda func: func._order)

# call them in that order
for func in funcs:
    func()

但是按字母顺序给它们命名会更容易......