微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mypy 如何接受 pydantic 的 constr() 类型?

如何解决mypy 如何接受 pydantic 的 constr() 类型?

我有这个代码

from pydantic import BaseModel,constr

DeptNumber = constr(min_length=6,max_length=6)

class MyStuff(BaseModel):
    dept: DeptNumber

ms = MyStuff(dept = "123456")

deptnr.py:6:错误:变量“deptnr.DeptNumber”作为类型无效
deptnr.py:6:注意:见https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases

提供的链接似乎并没有真正解决我的问题(我没有使用 Type)。

无论有无此 mypy.ini 都会发生这种情况:

[mypy]
plugins = pydantic.mypy

[pydantic-mypy]
init_typed = true

最初我在 Pydantic choice 中也有这个错误,如下所示,但我通过使用 Python 的 Literal解决这个问题。

DIR = choice(["north","East","South","West"])

我需要改变什么才能让 mypy 对我的 Pydantic constr 感到满意?

解决方法

此 Github 问题 https://github.com/samuelcolvin/pydantic/issues/156 中已讨论了与 mypy 的不兼容问题。遗憾的是,没有找到使用 constr and 让 mypy 开心的具体解决方案。

代替 constr,您可以继承 pydantic 的 ConstrainedStr,它提供与 constr 相同的配置和选项,但 mypy 不会抱怨类型别名。

from pydantic import BaseModel,ConstrainedStr

class DeptNumber(ConstrainedStr):
    min_length = 6
    max_length = 6

class MyStuff(BaseModel):
    dept: DeptNumber

ms = MyStuff(dept='123456')

文档的 Strict Types 部分简要提到了 Constrained* 类。它是在 pydantic/types.py 中定义的,如您所见,它与 constr 基本相同:

class ConstrainedStr(str):
    strip_whitespace = False
    to_lower = False
    min_length: OptionalInt = None
    max_length: OptionalInt = None
    curtail_length: OptionalInt = None
    regex: Optional[Pattern[str]] = None
    strict = False

    ...

验证工作相同:

Traceback (most recent call last):
  File "test-2.py",line 13,in <module>
    ms = MyStuff(dept='123456789')
  File "pydantic/main.py",line 406,in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for MyStuff
dept
  ensure this value has at most 6 characters (type=value_error.any_str.max_length; limit_value=6)
,

您可以尝试使用 Field 中的 Pydantic :

from pydantic import BaseModel,Field

class MyStuff(BaseModel):
    dept: str = Field(...,min_length=6,max_length=6)

似乎对我有用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。