如何指定数据结构以满足mypy和pydantic的要求

问题描述 投票:0回答:1
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import datetime

class Vault(BaseModel):
    VaultARN: str
    VaultName: str
    CreationDate: datetime
    LastInventoryDate: Optional[datetime] = None
    NumberOfArchives: int
    SizeInBytes: int

class VaultListResponse(BaseModel):
    VaultList: List[Vault]

# Example data
data = {
    "VaultList": [
        {
            "VaultARN": "arn:aws:glacier:eu-central-1:801680170242:vaults/ab_2017_bis_2022",
            "VaultName": "ab_2017_bis_2022",
            "CreationDate": "2022-07-05T08:37:25.552Z",
            "LastInventoryDate": "2024-09-14T18:54:58.863Z",
            "NumberOfArchives": 5712,
            "SizeInBytes": 28571666494
        },
        {
            "VaultARN": "arn:aws:glacier:eu-central-1:801680170242:vaults/photos-161218",
            "VaultName": "photos-161218",
            "CreationDate": "2016-12-18T15:03:19.426Z",
            "LastInventoryDate": "2024-09-14T18:54:52.853Z",
            "NumberOfArchives": 28418,
            "SizeInBytes": 94052378166
        }
    ]
}

# Pass the entire dictionary to the VaultListResponse constructor
vault_list_response = VaultListResponse(**data)
print(vault_list_response)

代码可以工作,但 mypy 给了我一个我无法摆脱的错误:“VaultListResponse”的参数 1 具有不兼容的类型“**dict[str, list[dict[str, object]]]”;预期的“list[Vault]”mypyarg-type

我如何指定数据结构,使其也满足 mypy

mypy pydantic
1个回答
0
投票

尝试

data = {
    "VaultList": [
        Vault(**{
            "VaultARN": "arn:aws:glacier:eu-central-1:801680170242:vaults/ab_2017_bis_2022",
            "VaultName": "ab_2017_bis_2022",
            "CreationDate": "2022-07-05T08:37:25.552Z",
            "LastInventoryDate": "2024-09-14T18:54:58.863Z",
            "NumberOfArchives": 5712,
            "SizeInBytes": 28571666494
        }),
        Vault(**{
            "VaultARN": "arn:aws:glacier:eu-central-1:801680170242:vaults/photos-161218",
            "VaultName": "photos-161218",
            "CreationDate": "2016-12-18T15:03:19.426Z",
            "LastInventoryDate": "2024-09-14T18:54:52.853Z",
            "NumberOfArchives": 28418,
            "SizeInBytes": 94052378166
        })
    ]
}

vault_list_response = VaultListResponse.model_validate(data)
print(vault_list_response)

对于第二个,你只会失去对参数的类型检查。但有时这正是您所需要的。不知道这是否是你的情况。

© www.soinside.com 2019 - 2024. All rights reserved.