DEBUG.WIKI
搬瓦工;先看线路,再选 VPS;CN2 GIA · 对应线路套餐;查看线路 →
RackNerd;$21.99/年 · 1GB KVM
京东云;让 AI 进入真实业务;零售 · 物流 · 客服 · 硬件;查看方案 →

解决 Python 报错 TypeError NoneType object is not subscriptable

分析 Python 访问字典键或列表索引时报 NoneType is not subscriptable 的空值根因,提供安全防御与 walrus 操作符处理方案。

问题现象

Python 程序执行过程中抛出未捕获的类型异常:

Traceback (most recent call last):
  File "app.py", line 18, in <module>
    user_name = response_data['user']['name']
TypeError: 'NoneType' object is not subscriptable

接口处理被强行中断。

触发根因

  1. 开发者尝试对一个值为 None 的变量使用了下标索引用法(如 variable[key] 或 variable[index])。
  2. 上游函数在未匹配到数据时隐式返回了 None(例如 dict.get('user') 返回了 None,紧接着写了 ['name'])。

解决步骤与操作命令

步骤一:使用防御性字典访问(dict.get 链式防御)

# 脆弱写法
name = data['user']['name']

# 安全写法
user = data.get('user') or {}
name = user.get('name', 'Default Name')

步骤二:针对列表索引进行非空判断

items = get_items_from_db()
if items is not None and len(items) > 0:
    first_item = items[0]
else:
    first_item = None

步骤三:利用 Python 3.8+ 海象运算符(Walrus Operator)

if (user := data.get('user')) is not None:
    print(user.get('name'))

验证确认

重新运行包含边界测试用例的代码: 当数据为 null/None 时能够优雅降级返回默认值,不产生任何未捕获崩盘。