【问题标题】:Declaring Pydantic Model "TypeError: 'type' object is not iterable"声明 Pydantic 模型“TypeError:‘type’对象不可迭代”
【发布时间】:2021-07-10 15:56:35
【问题描述】:

我正在使用 FastAPI 构建数据 API。我希望客户发布 2 个 24 个浮点数的列表,稍后我将保存到数据库中。

当我尝试创建 Pydantic 模型时:

from pydantic import BaseModel

class Prices(BaseModel):
    buying_price: list(float)=[]
    selling_price: list(float)=[]

我收到以下错误:

File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 3, in <module>
    class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in Prices
    buying_price: list(float)=[]
TypeError: 'type' object is not iterable

即使错误是不言自明的,但我还是不明白。

然后,查看文档我发现了以下方式:

from pydantic import BaseModel
from typing import List

class Prices(BaseModel):
    buying_price: List(float)=[]
    selling_price: List(float)=[]

但我收到以下错误。

File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 4, in <module>
    class Prices(BaseModel):
File "c:/Users/Amin y Lubna/FastAPI-InfluxDB/test.py", line 5, in Prices
    buying_price: List(float)=[]
File "C:\Users\Amin y Lubna\anaconda3\lib\typing.py", line 727, in __call__
    raise TypeError(f"Type {self._name} cannot be instantiated; "
TypeError: Type List cannot be instantiated; use list() instead

几天来我一直在努力解决该错误,但我无法找到解决问题的方法。

【问题讨论】:

  • 你的意思是list[float],或者在旧版本的Python中,List[float]。注意[]() 正在尝试将 list 作为函数调用,这将尝试将 float(一种类型)强制转换为列表;因此错误。
  • 谢谢!!!没有意识到括号。
  • () 通常表示“作为函数调用”。 [] 表示“索引序列”,或者如果它是一种类型,则表示“制作泛型类型的专用版本”。你的意思是三个中的最后一个。

标签: python list fastapi pydantic


【解决方案1】:

您需要使用list[float],而不是list(float)

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 2013-09-01
    • 2015-03-12
    • 1970-01-01
    • 2017-08-27
    • 2018-10-10
    • 2021-12-13
    • 2019-02-20
    相关资源
    最近更新 更多