You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对通过Generic[T]传入的类型对象调用TypeAdapter.validate_python?

问题解决方法

问题根源

  • Service类中self.item_type = type[T]是错误写法,type[T]仅作为类型注解使用,并非实际的类对象,导致传递给TypeAdapter的不是有效的Pydantic数据类类型。
  • 数据类Customer使用了标准库的@dataclass装饰器,而非Pydantic提供的版本,引发TypeAdapter兼容性问题。

解决方案

1. 修正Service类的类型传递逻辑

重构Service类,让子类能正确传入实际的数据类类型:

from abc import ABC
from typing import Generic, TypeVar
from app.core import DynamoDB

T = TypeVar("T")

class Service(ABC, Generic[T]):
    dynamodb: DynamoDB
    item_type: type[T]

    def __init__(self, dynamodb: DynamoDB, item_type: type[T]) -> None:
        self.dynamodb = dynamodb
        self.item_type = item_type

    async def _get_item(
        self,
        item_table: str,
        item_id_keyname: str,
        item_id_value: str,
    ) -> T | None:
        return await self.dynamodb.get_item(
            item_table, self.item_type, Key={item_id_keyname: item_id_value}
        )

2. 使用Pydantic专属的dataclass装饰器

替换标准库的@dataclass为Pydantic版本,确保数据类具备Pydantic的验证能力:

from pydantic.dataclasses import dataclass

@dataclass
class Customer:
    customerID: str
    name: str

3. 子类初始化时传入数据类类型

修改CustomerService,在初始化父类时传入Customer类对象:

class CustomerService(Service[Customer]):
    def __init__(self, dynamodb: DynamoDB) -> None:
        super().__init__(dynamodb, Customer)

    async def get_customer(self, customer_id: str) -> Customer | None:
        return await self._get_item(
            self.dynamodb.table_config.customer_table,
            "customerID",
            customer_id,
        )

可选优化:直接使用数据类的model_validate方法

若TypeAdapter仍有问题,可改用Pydantic数据类自带的model_validate方法替代,简化代码:

async def get_item(
    self,
    table_name: str,
    type: type[T],
    **get_params: Unpack[GetParams],
) -> Optional[T]:
    async with self.resource() as dynamodb_resource:
        table = await dynamodb_resource.Table(table_name)
        response = await table.get_item(**get_params)
        if "Item" not in response:
            return None
        return type.model_validate(response["Item"], from_attributes=True)

内容的提问来源于stack exchange,提问作者ayrtondenner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 12:13:15