Skip to main content
 首页 » 编程设计

python之Python 中的懒惰评估模块之间

2025年05月04日11虾米哥

我不确定在 Python 中是否可以实现类似的功能,但如果可以的话,它会非常有用(至少在这种情况下对我来说是这样)。

我有一个测试框架,我想在其中将测试配置与测试命令分开。这很有用,因为它允许您混合和匹配配置/测试而无需实际修改任何代码。我基本上只是有一个短运行脚本,它采用配置模块和测试模块的名称,然后加载并运行两者,如下所示:

config = __import__(configmod) 
test = __import__(commandsmod) 
 
config.run(test.commands) 

唯一的问题是我实际上希望测试脚本对配置参数有一些有限的了解。理想情况下,我希望能够在测试/命令模块中执行如下操作:

command1 = MyCommand(arg1, arg2, LazyArg1()) 
command2 = MyCommand(arg1, arg2, LazyArg2()) 
commands = [command1, command2] 

其中 LazyArg1 和 LazyArg2 是在配置模块(或导入配置/命令的运行器模块)中定义的方法。有没有什么办法可以延迟对这些函数的评估,直到它们被实际定义?

我也乐于采用其他方式来达到同样的目的。我唯一的其他想法是让配置模块将字典写入文件,然后让命令模块导入它(假设您只是写出 repr(mydict))。这不是很吸引人……尽管它会起作用。

请您参考如下方法:

Python 是动态类型的,所以这没什么特别的:

配置模块.py:

##### this is configMod.py ##### 
modTestArg1 = "Brian" 
 
def runTest(testMod, *args, **kwargs): 
    testMod.doTest(*args, **kwargs) 

测试模组.py:

##### this is testMod.py ##### 
def doTest(name, address, city="San Francisco"): 
    print "doTest called with name: %s, address: %s, city: %s" % \ 
        (name, address, city) 

controlMod.py

##### this is controlMod.py ##### 
import configMod 
import testMod 
 
configMod.runTest(testMod, configMod.modTestArg1, "123 Fake Street") 

运行它:

python controlMod.py 
doTest called with name: Brian, address: 123 Fake Street, city: San Francisco