admin管理员组文章数量:1336624
With pydantic, is there a way for mypy to be hinted so it doesn't raise an error in this scenario, where there's a field_validator modifying the type?
class MyModel(BaseModel):
x: int
@field_validator("x", mode="before")
@classmethod
def to_int(cls, v: str) -> int:
return len(v)
MyModel(x='test')
With pydantic, is there a way for mypy to be hinted so it doesn't raise an error in this scenario, where there's a field_validator modifying the type?
class MyModel(BaseModel):
x: int
@field_validator("x", mode="before")
@classmethod
def to_int(cls, v: str) -> int:
return len(v)
MyModel(x='test')
Share
Improve this question
asked Nov 19, 2024 at 17:41
RobRob
3,4996 gold badges34 silver badges79 bronze badges
3
|
2 Answers
Reset to default 2If you're always inserting a string there, it might be better to use a computed_field
. Something along this, maybe?
class MyModel(BaseModel):
input: str
@computed_field
def x(self) -> int:
return len(self.input)
I think it's very counterintuitive if you see the model with the int declaration while it would raise type errors if you put an integer inside a JSON at that place.
I'm still not convinced that it's a necessary approach, but here's a really simple option how to achieve this:
from pydantic import BaseModel
class MyModel(BaseModel):
x: int
def __init__(self, x: int | str):
super().__init__(x=len(x) if isinstance(x, str) else x)
MyModel(x='test')
本文标签: pythonmypy with pydantic fieldvalidatorStack Overflow
版权声明:本文标题:python - mypy with pydantic field_validator - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742409419a2469486.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
x: int | str
? – Sergius Commented Nov 19, 2024 at 19:35int | str
, now I need to validate this every time something uses the field, or I need to create a method to convert it when it's accessed. – Rob Commented Nov 20, 2024 at 0:46