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

声明返回list的Python函数,如何处理异常场景并规避PyCharm提示?

问题分析

你的函数类型注解声明返回list,但else分支里的return没有返回任何值(等价于返回None),违反了类型约定,所以PyCharm会提示错误。要规范实现,有两种可行方案:

方案1:返回空列表(符合类型注解,函数正常结束)

保持函数返回list类型,文件不存在时打印提示后返回空列表,和JSON解析错误的分支逻辑保持一致:

import os
import json

def read_json_files(file: str) -> list:
    if os.path.exists(file):
        with open(file, "r") as f:
            try:
                read_data = json.load(f)
                return read_data
            except json.JSONDecodeError as e:
                print(f"{e}: the json had some errors, returning an empty list")
                return []
    else:
        print("the json doesn't exist, returning an empty list")
        return []  # 改为返回空列表,匹配list类型注解

方案2:直接终止程序(不返回值,强制退出)

如果你的需求是文件不存在时直接终止整个程序(而非让函数返回),可以使用sys.exit(),但需要导入sys模块。这种情况下函数不会执行到返回步骤,也就不会违反类型注解:

import os
import json
import sys

def read_json_files(file: str) -> list:
    if os.path.exists(file):
        with open(file, "r") as f:
            try:
                read_data = json.load(f)
                return read_data
            except json.JSONDecodeError as e:
                print(f"{e}: the json had some errors, returning an empty list")
                return []
    else:
        print("the json doesn't exist, program will exit")
        sys.exit(1)  # 用非0状态码表示异常退出,直接终止程序

注意:方案2比较激进,仅适合必须依赖该文件存在才能继续运行的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 23:29:51