lovasoa / marshmallow_dataclass

Automatic generation of marshmallow schemas from dataclasses.

Home Page:https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeError when creating a marshmallow schema from dataclass inherited from generic class

shpindler opened this issue · comments

It is from my question on StackOverflow: https://stackoverflow.com/questions/75096188/typeerror-when-creating-a-marshmallow-schema-from-dataclass-inherited-from-gener?noredirect=1#comment132530258_75096188

I'm trying to create a marshmallow schema from dataclass which is inherited from generic type:

users_schema = marshmallow_dataclass.class_schema(Users)()

This is my code:

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


T = TypeVar("T")


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


@dataclass
class User:
    pass


@dataclass
class Users(Pagination[User]):
    pass

However I get this traceback:

src/c1client/entities/schemas.py:39: in <module>
    users_schema = marshmallow_dataclass.class_schema(Users)()
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:357: in class_schema
    return _internal_class_schema(clazz, base_schema, clazz_frame)
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:403: in _internal_class_schema
    attributes.update(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:406: in <genexpr>
    field_for_schema(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:701: in field_for_schema
    generic_field = _field_for_generic_type(typ, base_schema, typ_frame, **metadata)
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:505: in _field_for_generic_type
    child_type = field_for_schema(
../../../.venvs/cva-user-service/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py:719: in field_for_schema
    if issubclass(typ, Enum):
E   TypeError: issubclass() arg 1 must be a class

When I print typ variable from the traceback it is printed like ~T which is really not a class.

Also when I make Pagination class concrete - not generic, it works. So the problem is related to Generic.

Any ideas what could I do to make it work?

Currently, marshmallow_dataclass does not support generic dataclasses. (This explains why your example does not work.)

PR #172 is now actively working to implement exactly that, so I think support for will be coming "real soon now".