ano*_*spp 7 python-3.x pydantic
我有以下 pydantic 模型,其中包含Union[int,float]如下所示键入的结果。
from typing import Union
from pydantic import BaseModel
class Calculation(BaseModel):
arg1: int
arg2: int
class CalculationResult(Calculation):
op: str
result: Union[int, float]
if __name__ == "__main__":
arg1 = 1
arg2 = 2
result = arg1 / arg2
# this displays type of result := <class 'float'> when program is run
print(f"type of result := {type(result)}")
x = CalculationResult(**{"arg1": arg1, "arg2": arg2, "op": "divide", "result": result})
print(f"result := {x.result}")
Run Code Online (Sandbox Code Playgroud)
当 的结果属性的CalculationResult值为 0.5 时,它会舍入为 0。
我如何让 pydantic 认识到 0.5 是用于输入提示的浮点数Union[int, float]?
小智 7
修改 @anon_dcs3spp 的答案中提到的顺序可能并不理想,因为Union[float, int]会导致所有整数被强制转换为浮点数。
smart_union Pydantic最近添加了支持,可以防止类型强制并保留原始类型。
所以像下面这样的东西应该有效!
类 CalculationResult(计算): op: str 结果: Union[int, float]
class CalculationResult(Calculation):
op: str
result: Union[int, float]
class Config:
smart_union = True
Run Code Online (Sandbox Code Playgroud)
查看 Pydantic文档后解决了!
解决方案是首先指定最具体的类型,然后指定不太通用的类型。在本例中,我交换了联合类型声明中 float 和 int 的顺序。
class CalculationResult(Calculation):
op: str
result: Union[float, int]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6139 次 |
| 最近记录: |