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

Python中if-else分支下assert报错后执行指定if块代码如何实现

实现方案

核心思路

把第4层if下的日志打印逻辑抽离为独立公共函数,在断言分支增加AssertionError异常捕获,触发异常时调用该公共函数即可。

完整实现代码

import sys
import json

def step_impl(context, status, exp_date, owner, reg_date, man_yr, vchl_make, vchl_code):
    # 抽离公共的日志写入逻辑,避免代码重复
    def log_od_plans():
        print("empty response")
        json_data = context.payload
        # 用with上下文管理器管理文件写入,避免原代码全局修改stdout导致后续所有打印都写入日志的问题
        with open("OD_Plans.log", "a") as log_file:
            log_file.write(f"Previous Policy Status= {status}\n")
            log_file.write(f"expiry date= {exp_date}\n")
            log_file.write(f"Owner= {owner}\n")
            log_file.write(f"Registration Date= {reg_date}\n")
            log_file.write(f"Manufacturing Year= {man_yr}\n")
            log_file.write(f"Veichle Maker= {vchl_make}\n")
            log_file.write(f"Maker Code= {vchl_code}\n")
            log_file.write(json.dumps(json_data, indent=2) + "\n")

    if context.conv_exp_date < context.conv_expnd_date:
        if context.conv_reg_date >= '01-09-2018':
            if man_yr == context.expctd_manu_year:
                if not context.json_response:
                    log_od_plans()
                else:
                    try:
                        assert context.json_response is not None
                        assert float(context.json_response[0]['base_premium']) > float(1)
                        assert float(context.json_response[0]['total_premium']) > float(1)
                        assert float(context.json_response[0]['tax']) > float(1)
                        print(context.json_response[0]["tax"])
                    except AssertionError:
                        # 断言触发时执行日志写入
                        log_od_plans()
                        # 若需要保留原有断言的报错特性,保留下方raise,不需要则删除即可
                        raise
            else:
                pass
        else:
            pass
    else:
        pass

改动说明

  • 所有原有逻辑保留不变,仅增加了异常捕获和公共函数抽离,不会影响原有正常分支的执行
  • 可自主选择断言触发写日志后是否抛出异常,适配不同的测试场景需求

内容的提问来源于stack exchange,提问作者Apratim Chaudhuri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:36:02