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

如何正确标注re.compile返回值的类型?

正确为re.compile返回值添加类型标注的方式

问题原因

  • re.AnyStr@compile是编辑器提示的内部类型绑定语法,并非合法的Python类型标注语法,mypy无法识别,因此报错Invalid type comment or annotation。
  • 直接使用re.Pattern[typing.AnyStr]时,AnyStr是未绑定的类型变量,必须在函数/类的泛型签名中声明后才能使用,否则mypy会提示类型变量未绑定。

正确标注方式

1. 针对字符串字面量的场景(最常见)

因为你的正则表达式是字符串字面量(r"""..."""),re.compile会返回Pattern[str]类型,直接标注即可:

import re

def dummyF(fp: str) -> dict[str, int]:
    # 正确标注:明确Pattern的类型参数为str
    daterx: re.Pattern[str] = re.compile(r""" ... """, re.VERBOSE)
    # ...
    return {}

2. 兼容str和bytes的泛型场景

如果你的函数需要同时处理字符串和字节类型的正则,可以将函数声明为泛型函数,绑定AnyStr类型变量:

import re
from typing import AnyStr, Pattern

def dummyF[AnyStr](fp: AnyStr) -> dict[AnyStr, int]:
    # 此时AnyStr已绑定,可直接用于标注
    daterx: Pattern[AnyStr] = re.compile(r""" ... """, re.VERBOSE)
    # ...
    return {}

额外说明

  • 从Python 3.9+开始,typing模块中的Pattern已被移至标准库的re模块,直接使用re.Pattern即可,无需从typing导入。
  • mypy会自动推断re.compile的返回类型,如果你的代码逻辑清晰,也可以省略显式标注,mypy仍能正确识别类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:42:28