我又回到了 Python(在对 Go 和 Typescript 进行了一些不忠之后),同时
type
参数登陆了。
我试图理解如何使用它来精确地描述字典结构,但只能找到一种通用的方法:
type Car = Dict[str, str] # or [str, Any] or whatever
如果我的口述实际上是
{
"color": "blue",
"max_nr_passengers": 26,
"seats": [
{
"color": "green",
"heated": true
},
{
"color": "blue",
"heated": true
},
],
"options": {
"guns": false,
"submarine": false,
"extra_wheels": 18
}
}
然后我希望能够描述它的形状,以便我有真实的类型提示(并且安心)。
在 Go 中,这会是这样的
type Car = struct {
Color String
MaxNrPassengers Int
Seats []struct {
Color String
Heated Bool
}
Options struct {
Guns Bool
Submarine Bool
ExtraWheels Int
}
}
这准确地描述了该类型的实际结构。
这在Python中可能吗?
所以我想说你正在寻找的是一个名为
Pydantic
的图书馆。
https://docs.pydantic.dev/latest/
它允许您将 dict 和 json 结构解析为类型化类,其中项目作为属性进行访问。如果字典不符合结构,则会引发错误。请参阅下面的示例:
from pydantic import BaseModel
my_dict = {
"color": "blue",
"max_nr_passengers": 26,
"seats": [
{
"color": "green",
"heated": True
},
{
"color": "blue",
"heated": True
},
],
"options": {
"guns": False,
"submarine": False,
"extra_wheels": 18
}
}
class Option(BaseModel):
guns: bool
submarine: bool
extra_wheels: int
class Seat(BaseModel):
color: str
heated: bool
class Car(BaseModel):
color: str
max_nr_passengers: int
seats: list[Seat]
options: Option
car: Car = Car.model_validate(my_dict)
print(car)
您也可以将数据类用于这样的结构,但是对于嵌套数据类,从 dict 结构解析它们不太直接。希望这有帮助!