Schema generator for data classes
See original GitHub issuePython 3.7 will come with a new feature called Data Classes (see PEP 557). It is available for Python 3.6 on PyPI for demonstration purposes.
It looks like this:
@dataclass
class Artist:
name: str
@dataclass
class Album:
title: str
release_date: datetime.date
artist: List[Artist]
You can immediately notice the resemblance with marshmallow:
class ArtistSchema(Schema):
name = fields.Str()
class AlbumSchema(Schema):
title = fields.Str()
release_date = fields.Date()
artist = fields.Nested(ArtistSchema())
I think for most cases there’s enough information in the dataclass for marshmallow to figure out the schemas by itself. I admit that the schema might change while the model will stay the same but for most cases, it won’t be a problem.
My idea is to leverage on the dataclass to build a Schema automatically for DRY purposes when it makes sense while still getting the features of marshmallow under the hood. What’s your opinion on that? Do you have an idea of implementation so it can be both DRY and extensible?
I may be able to work on a PR for this but I want to go in the right direction.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:8
- Comments:14 (9 by maintainers)
Top GitHub Comments
I published a library that does exactly that: generating schemas from dataclasses.
marshmallow-dataclass
3.6 -> 3.7 releases had breaking changes. 3.8 is still in alpha and could break compatibility at any time before the final release several months from now. As it is now, the typing module will still be provisional in 3.8.
deckar01/marsha@50dbdcc5
https://www.python.org/dev/peps/pep-0569/#schedule
https://docs.python.org/3.8/library/typing.html
__origin__
and__args__
are undocumented, yet are the only way to inspect generics.https://docs.python.org/3.7/library/typing.html
The issue for stabilizing this API seems to have stalled waiting for 3rd party packages to become PEP candidates. typing_inspect is experimental and its primary purpose isn’t really to maintain cross-version compatibility, but it is still probably a safer option than using the private interface of the typing module.
https://bugs.python.org/issue29262
https://github.com/ilevkivskyi/typing_inspect
I’m not suggesting that the typing module shouldn’t be used, but supporting it in a library will come with more maintenance overhead than normal. Without a mechanism to enforce which python versions can be used, it’s probably a good idea to document any library that depends on generic typing as experimental.