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

使用@validate_arguments时Field的regex参数触发AttributeError问题

解决Pydantic 1.10.2中@validate_arguments结合Field regex的AttributeError问题

问题原因

错误AttributeError: 'str' object has no attribute 'match'的核心原因是:在Pydantic 1.x版本中,Field的regex参数要求传入编译后的正则表达式对象(即re.Pattern类型),而非字符串形式的正则表达式。直接传入字符串"[a-z ]+"会导致内部验证逻辑试图调用字符串的match方法,但字符串本身没有这个方法,从而触发报错。

解决方案

导入re模块,将正则表达式字符串编译为re.Pattern对象后再传入Field的regex参数。

修改后的代码

import re
from pydantic import validate_arguments, StrictStr, Field
from pydantic.typing import Annotated


@validate_arguments()
def test(a: Annotated[StrictStr, Field(regex=re.compile("[a-z ]+"))]):
    print(a)


# 测试合法输入,正常执行
test("abc def")
# 测试非法输入(会触发验证错误,符合预期)
# test("ABCDEF")

验证说明

  • 传入符合正则规则的小写字母加空格的字符串时,函数正常执行并打印内容。
  • 传入大写字母的字符串(如原代码中的"ABCDEF")时,会触发Pydantic的验证错误,提示输入不符合正则约束,这是预期的验证行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:22:46