You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以Pythonic低耦合方式处理全局Context对象的共享与标识问题

符合Python风格的低耦合解决方案

核心思路:通过组合关系替代上下文传递

让Test实例持有其所属TestSuite的引用,既可以共享TestSuite的runtime,又能明确自身的测试数据和索引,同时保留单一全局context的设计初衷。

修改后的代码实现

TestSuite类

class TestSuite(object):
    def __init__(self, context):
        self.context = context
        # 创建Test时传入自身引用、测试数据及索引
        self._tests = [
            Test(self, test_data, idx) for idx, test_data in enumerate(context["tests"])
        ]

    @property
    def runtime(self):
        try:
            return RuntimeFactory.create_runtime(self.context)
        except Exception as e:
            # 替换print为规范的异常抛出,便于上层处理
            raise ValueError("runtime_id is missing or invalid") from e

Test类

class Test(object):
    def __init__(self, test_suite, test_data, index):
        self.test_suite = test_suite
        self.test_data = test_data  # 当前测试的专属数据
        self.index = index          # 明确当前测试的索引

    @property
    def runtime(self):
        # 直接复用TestSuite的runtime,实现全局共享
        return self.test_suite.runtime

    @property
    def context(self):
        # 按需组合全局上下文与当前测试数据,保持单一context的设计
        combined_context = self.test_suite.context.copy()
        combined_context["current_test"] = self.test_data
        combined_context["test_index"] = self.index
        return combined_context

方案优势

  • 低耦合:Test仅依赖TestSuite的公开接口(runtime和context属性),无需知晓内部实现细节
  • 扩展性强:多层结构(如测试包含子输入列表)时,子组件只需持有上层组件的引用,即可逐层获取共享资源,无需修改所有类的上下文结构
  • 符合单一职责:TestSuite管理全局上下文和共享资源,Test专注于自身测试逻辑,分工清晰
  • 规范异常处理:替换原有的print输出为异常抛出,符合Python错误处理的最佳实践

内容的提问来源于stack exchange,提问作者Ahasanul Haque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:35:20