【发布时间】:2020-10-16 09:56:15
【问题描述】:
如何从当前执行位置迭代特定模块中的所有函数?
以下是我迄今为止所做的一些细节:
我创建了一个名为“test_cases”的包,其中包含一个模块“test_cases”,其中包含许多功能。我想创建某种循环来执行 test_case 模块中的每个函数。
main() 的第一行下面是test_cases.test_cases.tc_1(),这只是为了测试我的脚本是否可以调用特定函数并且它可以工作。困扰我的是“循环”方面。
这是我的代码的大致思路:
def main():
# test_cases.test_cases.tc_1()
for _, test in test_cases.test_cases:
test
我读过this post,但答案建议使用for name, val in my_module.__dict__.iteritems():,但是根据PEP 469,iteritems() 不是python 3.8 中__dict__ 的属性(假设我没看错)。我也读过this post,但还不清楚。所以我有点困惑该怎么做。
我正在运行 Windows 10、PyCharm2020.1.2、Python 3.8
编辑 1
这是我的新 main() 函数,items() 用作迭代器。调试时,它似乎会逐步遍历我的test_case 模块的__name__, __doc__, __package__ 等元素(这些元素叫什么?)。然后它会识别我的函数tc_1 并尝试执行它但没有任何反应。我希望它能够运行print() 语句。我在下面附上了我的功能以供参考。这是怎么回事?
def main():
for name, test in test_cases.test_cases.__dict__.items():
if callable(test):
test
# tc_1 is in the test_cases module
def tc_1():
print("TEST CASE ONE EXECUTED")
编辑 2
最后一个问题不包括test 后面的括号。纠正此问题后,循环将按预期工作。以下是参考代码:
def main():
for name, test in test_cases.test_cases.__dict__.items():
if callable(test):
test()
【问题讨论】:
标签: python python-3.x loops module iteration