Python mypy如何为lambda内的正则表达式操作添加类型提示
报错原因
re.match() 方法的返回值类型为 Optional[re.Match[str]],当正则匹配失败时会返回 None,匹配成功才会返回匹配对象。你的代码默认所有输入字符串都符合正则规则,但 mypy 无法识别这个隐含前提,因此会提示 None 对象不存在 group 属性的类型错误。
解决方案
下面提供三种适配不同场景的解决方法:
- 场景1:确定所有输入字符串一定符合格式,优先选择抽离排序函数+显式断言的方案,运行时还能提前发现不符合规则的异常输入:
import re from typing import Sequence x: Sequence[str] = [ "info_2_mation_1_thing", "info_2_mation_5_thing", "info_2_mation_2_thing", "info_2_mation_3_thing", "info_2_mation_13_thing", "info_2_mation_4_thing", ] def get_sort_key(s: str) -> int: match = re.match(r"info_\d_mation_(\d+)_thing", s) assert match is not None, f"异常输入:{s} 不符合预期格式" return int(match.group(1)) sorted(x, key=get_sort_key)
- 场景2:需要兼容可能出现的不匹配输入,显式处理None分支即可:
def get_sort_key(s: str) -> int: match = re.match(r"info_\d_mation_(\d+)_thing", s) if match: return int(match.group(1)) # 匹配失败的字符串默认排序值,可按需调整 return -1
- 场景3:不想增加运行时额外判断,确定100%不会出现匹配失败的情况,可以用
cast强制转换类型,仅静态检查生效:
import re from typing import cast, Sequence x: Sequence[str] = [ "info_2_mation_1_thing", "info_2_mation_5_thing", "info_2_mation_2_thing", "info_2_mation_3_thing", "info_2_mation_13_thing", "info_2_mation_4_thing", ] sorted(x, key=lambda s: int(cast(re.Match[str], re.match(r"info_\d_mation_(\d+)_thing", s)).group(1)))
内容的提问来源于stack exchange,提问作者baxx
相关产品推荐
相关产品推荐

