Introduction of a generic schema used to type load and loads
Vince-LD opened this issue · comments
Hello,
This week, I've started to use marshmallow and marshmallow_dataclass at work for the first time and it's absolutely great. However, I was wondering if there was a reason not to use a generic schema to keep track of the wrapped dataclass when using class_schema
factory.
The basic idea is pretty simple:
# have a custom schema class that is used only for type checking
class DataclassSchema(Generic[_T]):
if TYPE_CHECKING:
# use some overloading here to chose between the two result types
def load(...) -> Union[_T, List[_T]]: ...
# update `class_schema` signature
def class_schema(clazz: Typ[_T], ...) -> Type[DataclassSchema[_T]]: ...
Then we can create a dataclass and the corresponding schema:
@dataclass
class Test:
a : int
b : str
# The types can actually be inferred by Pyright
schema: DataclassSchema[Test] = class_schema(Test)()
data: Test = schema.load({"a": 0, "b": "hellow world :)")
I have created a first implementation of this proposal in this fork. I am not familiar with mypy (I use Pyright through Pylance) and really advanced typing so I don't know if this is the best way to achieve my goal. If this subject interests you I'd be glad to contribute :)
Cheers,
Vincent
Edit: Sorry for the tag....
Yes, I'm proposing something similar. Actually, my first implementation works really well in real conditions (used it at work this week). I'm going to try another implentation by using marshmallow-generic
but it would still require to modify the signature of marshmallow_dataclass.class_schema
to use this generic Schema
and a dataclass TypeVar
instead of type
and Schema
.