我正在清理一些被污染的数据,我想对其进行一些自动化处理。也就是说,我希望脚本具有一些预定义的清理函数,以便按照如何清理数据的顺序排列,并且我设计了一个装饰器来使用 this solution 从脚本中检索这些函数。 :
from inspect import getmembers, isfunction
import cd # cleaning module
functions_list = [o[0] for o in getmembers(cd) if isfunction(o[1])]
这效果非常好。但是,它确实以不同的顺序检索函数 ( by name )
出于可重复性的目的,请将以下清洁模块视为cd
:
def clean_1():
pass
def clean_2():
pass
def clean_4():
pass
def clean_3():
pass
解决方案输出:
['clean_1', 'clean_2', 'clean_3', 'clean_4']
它需要在哪里:
['clean_1', 'clean_2', 'clean_4', 'clean_3']
主要问题的其他解决方案是可以接受的(尽管考虑了性能)。
最佳答案
你已经成功了一半。您只需根据函数代码对象的第一行 ( [Python 3]: inspect - Inspect live objects ) 对列表进行排序。
请注意,我只在问题中的(简单)示例上尝试过此操作(并且没有进行任何性能测试)。
code.py:
#!/usr/bin/env python3
import sys
from inspect import getmembers, isfunction
import cd # The module from the question that contains the 4 clean_* functions
def main():
member_functions = (item for item in getmembers(cd) if isfunction(item[1]))
function_names = (item[0] for item in sorted(member_functions, key=lambda x: x[1].__code__.co_firstlineno))
print(list(function_names))
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
输出:
e:\Work\Dev\StackOverflow\q054521087>"e:\Work\Dev\VEnvs\py_064_03.06.08_test0\Scripts\python.exe" code.py Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32 ['clean_1', 'clean_2', 'clean_4', 'clean_3']
关于python - 检索脚本中的可用函数(相同顺序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54521087/