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

Ruff 0.0.209对Python3.10.9的match/case语法报E999错误求助

解决Ruff对match/case语法的SyntaxError问题

问题重现

使用Ruff 0.0.209 + Python 3.10.9,运行以下代码时触发语法错误:

from http import HTTPStatus

http_status = HTTPStatus.OK

match http_status:
    case HTTPStatus.OK:
        print("OK!")

    case HTTPStatus.BAD_REQUEST:
        print("Bad, bad Zoot!")

    case _:
        print("Just a flesh wound.")

错误提示:

5:8: E999 SyntaxError: invalid syntax. Got unexpected token 'http_status'

原因分析

match/case是Python 3.11正式引入的语法特性。尽管Ruff声称支持Python 3.11,但如果项目未正确配置目标Python版本,Ruff会默认按本地Python解释器版本(3.10)进行语法检查,从而将match/case判定为无效语法。

解决方案

1. 配置Ruff的目标Python版本

在项目根目录的pyproject.toml或ruff.toml中添加以下配置,明确指定目标版本为Python 3.11及以上:

方式一:pyproject.toml

[tool.ruff]
target-version = "py311"

方式二:ruff.toml

target-version = "py311"

2. 确保Ruff为最新版本

旧版本的Ruff可能对match/case的支持存在bug,执行以下命令更新到最新版:

pip install --upgrade ruff

更新后可通过ruff --version确认版本号。

3. 无需升级本地Python解释器

Ruff的语法检查逻辑独立于本地Python解释器,只要Ruff配置了正确的目标版本,即使本地用3.10,也能正常解析3.11的语法特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:40:57