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

Python中list[str]类型提示报TypeError错误的解决求助

解决Python 3.8中list[str]类型提示报错问题

问题原因

Python 3.9及以上版本才支持直接对list、dict这类内置类型使用下标语法实现泛型类型提示,你使用的Python 3.8.15不支持该写法,因此会抛出TypeError: 'type' object is not subscriptable错误。课程环境能正常运行,是因为使用了Python 3.9+版本。

两种解决方法

  1. 使用typing模块的List类型
    这是Python 3.9之前版本的标准写法,导入typing.List后即可正常添加类型提示:

    from typing import List
    
    tricks: List[str] = []
    
  2. 开启PEP 585向后兼容
    在代码文件(或Jupyter Notebook单元格)顶部添加from __future__ import annotations,即可直接使用list[str]的写法。该导入会将类型提示在运行时视为字符串处理,避免语法报错:

    from __future__ import annotations
    
    tricks: list[str] = []
    

以上两种方法在常规.py文件和Jupyter Notebook中均适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:35:25