Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检索脚本中的可用函数(相同顺序)_Python_Python 3.x - Fatal编程技术网

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

Python 检索脚本中的可用函数(相同顺序),python,python-3.x,Python,Python 3.x,我正在清理一些被抹掉的数据,我想让这些数据自动化一点。也就是说,我希望一个脚本有一些预定义的清理函数,按照清理数据的顺序排列,我设计了一个装饰器,使用以下命令从脚本中检索这些函数: 这个效果非常好。但是,它确实以不同的顺序检索函数() 为了再现性目的,考虑以下清洁模块: CD < /代码>: def clean_1(): pass def clean_2(): pass def clean_4(): pass def clean_3(): pass

我正在清理一些被抹掉的数据,我想让这些数据自动化一点。也就是说,我希望一个脚本有一些预定义的清理函数,按照清理数据的顺序排列,我设计了一个装饰器,使用以下命令从脚本中检索这些函数:

这个效果非常好。但是,它确实以不同的顺序检索函数()

为了再现性目的,考虑以下清洁模块:<代码> 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']
主要问题的其他解决方案是可以接受的(不过性能是可以考虑的)

主要问题的其他解决方案是可以接受的(不过性能是可以考虑的)

为了能够定义和导入助手函数而不自动包含它们,可以使用显式列表:

def clean_1():
    pass


def clean_2():
    pass


def clean_4():
    pass


def clean_3():
    pass


cleaners = [
    clean_1,
    clean_2,
    clean_4,
    clean_3,
]
或者一个明确的装饰者:

cleaners = []
cleaner = cleaners.append


@cleaner
def clean_1():
    pass


@cleaner
def clean_2():
    pass


@cleaner
def clean_4():
    pass


@cleaner
def clean_3():
    pass
不过,就按顺序获取常规模块的属性而言,您应该能够在Python 3.7+中使用
\uuu dict\uu

functions_list = [k for k, v in cd.__dict__.items() if isfunction(v)]

你已经走到一半了。您只需要根据函数的代码对象()的第1行对列表进行排序

请注意,我只在问题中的(琐碎的)示例上尝试过这一点(并且没有做任何性能测试)

code.py:

#/usr/bin/env蟒蛇3
导入系统
从inspect import getmembers,isfunction
导入cd#问题中包含4个clean#函数的模块
def main():
member_functions=(getmembers(cd)中的项对应于isfunction中的项(项[1]))
函数名称=(已排序的项的项[0](成员函数,项=lambda x:x[1]。\uuuuu代码\uuuuuu.co\ufirstlineno))
打印(列表(功能名称))
如果名称=“\uuuuu main\uuuuuuuu”:
打印(“Python{:s}on{:s}\n.”格式(sys.version,sys.platform))
main()
输出


为了清晰起见,请查看ast以解析python语法树,是否可以包含
cd
的代码?在这里的问题中始终包含一个空格是很重要的。@ChrisLarson。实际上包括在内。为了重现性,考虑下面的清洁模块:“安德鲁”。我对你的问题做了一个小的修改来澄清,以防其他人错过了参考资料。
functions_list = [k for k, v in cd.__dict__.items() if isfunction(v)]
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']