python - 检索脚本中的可用函数(相同顺序)

标签 python python-3.x

我正在清理一些被污染的数据,我想对其进行一些自动化处理。也就是说,我希望脚本具有一些预定义的清理函数,以便按照如何清理数据的顺序排列,并且我设计了一个装饰器来使用 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/

相关文章:

python - 返回具有多个键的字典中的最大值

python - 发生错误时关闭文件而不保存 - Python

python - 运行 python3 virtualenv 时使用 pip3 与 pip 有什么区别

python - 如何计算 50x20 矩阵的类内散布

python-3.x - 如何从pandas表中获取每个值的百分比?

python - 有没有办法从文本文件中带括号的数字中提取值?

python - pandas:如何使用多索引运行数据透视?

java - Jython - PyObject 的类转换异常

python - "Allocating size to..."在 Gtk.ScrolledWindow 中使用 Gtk.TreeView 时出现 GTK 警告

python - 这个查询有什么问题?