Python: 将本地定义的函数传递给动态加载的 类,有这方面的成语吗?

Python: Passing locally defined functions into dynamically loaded classes, is there an idiom for this?

我已经编写了一个 launcher/boilerplate python 脚本来处理我正在 运行 进行的一些网络模拟的常见初始化任务。我让它根据 cmdline args 将包含实际测试代码的其他 python 脚本动态加载到 运行(在 类 中定义),并将辅助函数传递到测试电池代码 类 通过 lambda 字典。

只是给你一个想法,辅助函数是这样调用的:

self.helpers['createQueue'](switch=s1, port=3, qid=1, slice=700)
self.helpers['modFlow'](
    switch=s1, cmd='add', tableid=0,
    match='eth_type=0x800,ip_src=10.0.0.1,ip_dst=10.0.0.3',
    actions='nw_dec,output=3,queue=1'
)

澄清一下,一切正常。但我想知道是否有更惯用的方法来解决这个问题。

像这样从字典中调用 lambda 乍一看有点难以接受,我真的不相信这种方法是好的编码实践。

如有任何想法,我们将不胜感激。我正在学习 python,所以目前我对语言和实践的了解有些零散。

你看过unittest module? This provides a framework to handle initializations, and there are options for test discovery吗?我将演示导入目标模块并动态调用其中的每个函数。不要将 lambda 存储在字典中,在常规命名空间(如模块)中使用命名和记录的函数,并使用 dir()getattr():

动态访问它们
import target

class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    def setUp(self):
        self.recreate_for_each_test = foo()

    def test_0(self):
        for name in dir(target): # probably use a try/except block here
            if condition(name) # define this condition 
                getattr(target, name)() # call dynamically

    def test_1(self):
        self.assertEquals(self.recreate_for_each_unit, foo())

    def test_2(self):
        with self.assertRaises(Exception):
             bar()

    def tearDown(self):
        self.recreate_for_each_unit.cleanup()

    @classmethod
    def tearDownClass(cls):
        cls._connection.destroy()

您可能希望使用 try/except 处理异常,并在它们失败的地方获取堆栈跟踪。有关

的更多信息,请参阅此答案