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

继承泛型类的数据类生成Marshmallow Schema时触发TypeError

解决泛型数据类生成Marshmallow Schema的TypeError问题

问题原因

marshmallow_dataclass在处理继承自泛型数据类的子类时,无法正确将泛型类型变量(如~T)替换为实际的具体类型,导致issubclass()检查时传入了非类对象,触发TypeError: issubclass() arg 1 must be a class。

解决方案

方法一:显式重写泛型字段指定具体类型

在子类中重新定义泛型字段,明确指定具体类型,让marshmallow_dataclass能正确解析:

from dataclasses import dataclass
from typing import Generic, List, TypeVar
import marshmallow_dataclass

T = TypeVar("T")

@dataclass
class Pagination(Generic[T]):
    items: List[T]

@dataclass
class User:
    pass

@dataclass
class Users(Pagination[User]):
    items: List[User]  # 显式重写字段,替换泛型变量为具体类型

users_schema = marshmallow_dataclass.class_schema(Users)()
# 测试序列化
test_users = Users(items=[User(), User()])
print(users_schema.dump(test_users))

方法二:手动编写Marshmallow Schema

绕过marshmallow_dataclass的泛型解析,直接用marshmallow原生Schema定义:

from dataclasses import dataclass
from typing import Generic, List, TypeVar
import marshmallow
import marshmallow_dataclass
from marshmallow.fields import List, Nested

T = TypeVar("T")

@dataclass
class Pagination(Generic[T]):
    items: List[T]

@dataclass
class User:
    pass

# 生成User的Schema
UserSchema = marshmallow_dataclass.class_schema(User)

# 手动定义Users的Schema
class UsersSchema(marshmallow.Schema):
    items = List(Nested(UserSchema))

users_schema = UsersSchema()
# 测试序列化
test_users = Users(items=[User(), User()])
print(users_schema.dump(test_users))

方法三:升级marshmallow_dataclass版本

部分旧版本的marshmallow_dataclass对泛型支持不完善,升级到最新版本可能自动修复该问题:

pip install --upgrade marshmallow_dataclass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:05:36