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

如何修改Python代码避免判断特定用户时触发KeyError?

解决方案

原代码的问题在于直接通过键名取值(x["healthy"]),当参数未传入时会触发KeyError,不符合需求中"只要至少一个参数为0(或未传入,因为未传入等价于不满足为1的条件)就返回false"的逻辑。我们可以通过dict.get()方法避免键不存在的错误,同时调整判断逻辑来满足需求。

修改后的代码

import pytest


def function(x: dict) -> str:
    try:
        name = x["name"]
        if name in ["max", "alex"]:
            # 用get方法获取参数,未传入时默认值为0
            healthy = x.get("healthy", 0)
            tall = x.get("tall", 0)
            rich = x.get("rich", 0)
            # 只要任意一个参数不为1,就返回false
            if healthy != 1 or tall != 1 or rich != 1:
                return "false"
            return "true"
        return "true"
    except KeyError:
        return "input_is_missing"


class TestEvaluate:
    false = "false"
    true = "true"
    input_is_missing = "input_is_missing"

    @pytest.mark.parametrize(
        "inputs, expected",
        [
            # Test 1
            (
                {
                    "name": "max",
                    "healthy": 0,
                },
                false,
            ),
            # Test 2
            (
                {
                    "name": "max",
                    "tall": 0,
                },
                false,
            ),
            # Test 3
            (
                {
                    "name": "max",
                    "healthy": 1,
                    "tall": 0,
                },
                false,
            ),
            # 新增测试用例:三个参数都为1,返回true
            (
                {
                    "name": "alex",
                    "healthy": 1,
                    "tall": 1,
                    "rich": 1,
                },
                true,
            ),
            # 新增测试用例:缺少rich参数,返回false
            (
                {
                    "name": "max",
                    "healthy": 1,
                    "tall": 1,
                },
                false,
            ),
            # 新增测试用例:name不存在,返回input_is_missing
            (
                {
                    "healthy": 1,
                    "tall": 1,
                    "rich": 1,
                },
                input_is_missing,
            ),
        ],
    )
    def test_valid_inputs(self, inputs, expected):
        assert function(inputs) == expected

修改说明

  • 避免KeyError:使用x.get(key, default)方法获取healthy、tall、rich参数,当参数未传入时默认值设为0,既不会触发键不存在的错误,也符合需求中"非1即返回false"的逻辑。
  • 简化判断逻辑:将三个独立的if判断合并为一个or条件,只要任意参数不为1就返回false,代码更简洁高效。
  • 保留原有错误处理:仍通过try-except捕获name参数缺失的情况,返回"input_is_missing",保持原代码的错误处理行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:55:39