{"id":13935778,"url":"https://github.com/lovasoa/marshmallow_dataclass","last_synced_at":"2025-05-14T17:03:52.469Z","repository":{"id":34079230,"uuid":"169261453","full_name":"lovasoa/marshmallow_dataclass","owner":"lovasoa","description":"Automatic generation of marshmallow schemas from dataclasses.","archived":false,"fork":false,"pushed_at":"2024-09-12T16:19:00.000Z","size":1240,"stargazers_count":464,"open_issues_count":55,"forks_count":76,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-10T04:53:28.110Z","etag":null,"topics":["dataclass","marshmallow","orm","serialization"],"latest_commit_sha":null,"homepage":"https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lovasoa.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-05T15:17:16.000Z","updated_at":"2025-03-14T07:36:04.000Z","dependencies_parsed_at":"2024-03-20T17:31:43.066Z","dependency_job_id":"fdf6a394-08fd-440d-acab-a0a5b50aa5b5","html_url":"https://github.com/lovasoa/marshmallow_dataclass","commit_stats":{"total_commits":286,"total_committers":37,"mean_commits":7.72972972972973,"dds":"0.46153846153846156","last_synced_commit":"2f8bf4bb082097e453ab520a7ff7d6ef84b6f474"},"previous_names":[],"tags_count":56,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lovasoa%2Fmarshmallow_dataclass","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lovasoa%2Fmarshmallow_dataclass/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lovasoa%2Fmarshmallow_dataclass/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lovasoa%2Fmarshmallow_dataclass/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lovasoa","download_url":"https://codeload.github.com/lovasoa/marshmallow_dataclass/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254190382,"owners_count":22029632,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dataclass","marshmallow","orm","serialization"],"created_at":"2024-08-07T23:02:05.414Z","updated_at":"2025-05-14T17:03:52.374Z","avatar_url":"https://github.com/lovasoa.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"# marshmallow-dataclass\n\n[![Test Workflow Status (master branch)](https://img.shields.io/github/actions/workflow/status/lovasoa/marshmallow_dataclass/python-package.yml?branch=master\u0026label=tests)](https://github.com/lovasoa/marshmallow_dataclass/actions/workflows/python-package.yml)\n[![PyPI version](https://badge.fury.io/py/marshmallow-dataclass.svg)](https://badge.fury.io/py/marshmallow-dataclass)\n[![marshmallow 3 compatible](https://badgen.net/badge/marshmallow/3)](https://marshmallow.readthedocs.io/en/latest/upgrading.html)\n[![download stats](https://img.shields.io/pypi/dm/marshmallow-dataclass.svg)](https://pypistats.org/packages/marshmallow-dataclass)\n\nAutomatic generation of [marshmallow](https://marshmallow.readthedocs.io/) schemas from dataclasses.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\n\nimport marshmallow_dataclass\nimport marshmallow.validate\n\n\n@dataclass\nclass Building:\n    # field metadata is used to instantiate the marshmallow field\n    height: float = field(metadata={\"validate\": marshmallow.validate.Range(min=0)})\n    name: str = field(default=\"anonymous\")\n\n\n@dataclass\nclass City:\n    name: Optional[str]\n    buildings: List[Building] = field(default_factory=list)\n\n\ncity_schema = marshmallow_dataclass.class_schema(City)()\n\ncity = city_schema.load(\n    {\"name\": \"Paris\", \"buildings\": [{\"name\": \"Eiffel Tower\", \"height\": 324}]}\n)\n# =\u003e City(name='Paris', buildings=[Building(height=324.0, name='Eiffel Tower')])\n\ncity_dict = city_schema.dump(city)\n# =\u003e {'name': 'Paris', 'buildings': [{'name': 'Eiffel Tower', 'height': 324.0}]}\n```\n\n## Why\n\nUsing schemas in Python often means having both a class to represent your data and a class to represent its schema, which results in duplicated code that could fall out of sync.\nAs of Python 3.6, types can be defined for class members, which allows libraries to generate schemas automatically.\n\nTherefore, you can document your APIs in a way that allows you to statically check that the code matches the documentation.\n\n## Installation\n\nThis package [is hosted on PyPI](https://pypi.org/project/marshmallow-dataclass/).\n\n```shell\npip3 install marshmallow-dataclass\n```\n\n```shell\npip3 install \"marshmallow-dataclass\"\n```\n\n### marshmallow 2 support\n\n`marshmallow-dataclass` no longer supports marshmallow 2.\nInstall `marshmallow_dataclass\u003c6.0` if you need marshmallow 2 compatibility.\n\n## Usage\n\nUse the [`class_schema`](https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html#marshmallow_dataclass.class_schema)\nfunction to generate a marshmallow [Schema](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.Schema)\nclass from a [`dataclass`](https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass).\n\n```python\nfrom dataclasses import dataclass\nfrom datetime import date\n\nimport marshmallow_dataclass\n\n\n@dataclass\nclass Person:\n    name: str\n    birth: date\n\n\nPersonSchema = marshmallow_dataclass.class_schema(Person)\n```\n\nThe type of your fields must be either basic \n[types supported by marshmallow](https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.Schema.TYPE_MAPPING)\n(such as `float`, `str`, `bytes`, `datetime`, ...), `Union`, or other dataclasses.\n\n### Union (de)serialization coercion \n\nTypically the Union type; `Union[X, Y]` means—from a set theory perspective—either `X` or `Y`, i.e., an unordered set, howevever the order of the sub-types defines the precedence when attempting to ether deserialize or serialize the value per [here](https://github.com/lovasoa/marshmallow_dataclass/blob/master/marshmallow_dataclass/union_field.py). \n\nFor example, \n\n```python\nfrom typing import Union\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Person:\n    name: str\n    age: Union[int, float]\n\n\nPersonSchema = marshmallow_dataclass.class_schema(Person)\nPersonSchema().load({\"name\": \"jane\", \"age\": 50.0})\n# =\u003e Person(name=\"jane\", age=50)\n```\n\nwill first (sucessfully) try to coerce `50.0` to an `int`. If coercion is not desired the `Any` type can be used with the caveat that values will not be type checked without additional [validation](https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html).\n\n### Customizing generated fields\n\nTo pass arguments to the generated marshmallow fields (e.g., `validate`, `load_only`, `dump_only`, etc.),\npass them to the `metadata` argument of the\n[`field`](https://docs.python.org/3/library/dataclasses.html#dataclasses.field) function.\n\nNote that starting with version 4, marshmallow will disallow passing arbitrary arguments, so any\nadditional metadata should itself be put in its own `metadata` dict:\n\n```python\nfrom dataclasses import dataclass, field\nimport marshmallow_dataclass\nimport marshmallow.validate\n\n\n@dataclass\nclass Person:\n    name: str = field(\n        metadata=dict(\n            load_only=True, metadata=dict(description=\"The person's first name\")\n        )\n    )\n    height: float = field(metadata=dict(validate=marshmallow.validate.Range(min=0)))\n\n\nPersonSchema = marshmallow_dataclass.class_schema(Person)\n```\n\n### `@dataclass` shortcut\n\n`marshmallow_dataclass` provides a `@dataclass` decorator that behaves like the standard library's \n`@dataclasses.dataclass` and adds a `Schema` attribute with the generated marshmallow\n[Schema](https://marshmallow.readthedocs.io/en/2.x-line/api_reference.html#marshmallow.Schema).\n\n```python\n# Use marshmallow_dataclass's @dataclass shortcut\nfrom marshmallow_dataclass import dataclass\n\n\n@dataclass\nclass Point:\n    x: float\n    y: float\n\n\nPoint.Schema().dump(Point(4, 2))\n# =\u003e {'x': 4, 'y': 2}\n```\n\nNote: Since the `.Schema` property is added dynamically, it can confuse type checkers.\nTo avoid that, you can declare `Schema` as a [`ClassVar`](https://docs.python.org/3/library/typing.html#typing.ClassVar).\n\n```python\nfrom typing import ClassVar, Type\n\nfrom marshmallow_dataclass import dataclass\nfrom marshmallow import Schema\n\n\n@dataclass\nclass Point:\n    x: float\n    y: float\n    Schema: ClassVar[Type[Schema]] = Schema\n```\n\n### Customizing the base Schema\n\nIt is also possible to derive all schemas from your own \nbase Schema class\n(see [marshmallow's documentation about extending `Schema`](https://marshmallow.readthedocs.io/en/stable/extending.html)).\nThis allows you to implement custom (de)serialization\nbehavior, for instance specifying a custom mapping between your classes and marshmallow fields,\nor renaming fields on serialization.\n\n#### Custom mapping between classes and fields\n\n```python\nclass BaseSchema(marshmallow.Schema):\n    TYPE_MAPPING = {CustomType: CustomField, List: CustomListField}\n\n\nclass Sample:\n    my_custom: CustomType\n    my_custom_list: List[int]\n\n\nSampleSchema = marshmallow_dataclass.class_schema(Sample, base_schema=BaseSchema)\n# SampleSchema now serializes my_custom using the CustomField marshmallow field\n# and serializes my_custom_list using the CustomListField marshmallow field\n```\n\n#### Renaming fields on serialization\n\n```python\nimport marshmallow\nimport marshmallow_dataclass\n\n\nclass UppercaseSchema(marshmallow.Schema):\n    \"\"\"A Schema that marshals data with uppercased keys.\"\"\"\n\n    def on_bind_field(self, field_name, field_obj):\n        field_obj.data_key = (field_obj.data_key or field_name).upper()\n\n\nclass Sample:\n    my_text: str\n    my_int: int\n\n\nSampleSchema = marshmallow_dataclass.class_schema(Sample, base_schema=UppercaseSchema)\n\nSampleSchema().dump(Sample(my_text=\"warm words\", my_int=1))\n# -\u003e {\"MY_TEXT\": \"warm words\", \"MY_INT\": 1}\n```\n\nYou can also pass `base_schema` to `marshmallow_dataclass.dataclass`.\n\n```python\n@marshmallow_dataclass.dataclass(base_schema=UppercaseSchema)\nclass Sample:\n    my_text: str\n    my_int: int\n```\n\nSee [marshmallow's documentation about extending `Schema`](https://marshmallow.readthedocs.io/en/stable/extending.html).\n\n### Custom type aliases\n\nThis library allows you to specify [customized marshmallow fields](https://marshmallow.readthedocs.io/en/stable/custom_fields.html#creating-a-field-class) using python's Annoted type [PEP-593](https://peps.python.org/pep-0593/).\n\n```python\nfrom typing import Annotated\nimport marshmallow.fields as mf\nimport marshmallow.validate as mv\n\nIPv4 = Annotated[str, mf.String(validate=mv.Regexp(r\"^([0-9]{1,3}\\\\.){3}[0-9]{1,3}$\"))]\n```\n\nYou can also pass a marshmallow field class.\n\n```python\nfrom typing import Annotated\nimport marshmallow\nfrom marshmallow_dataclass import NewType\n\nEmail = Annotated[str, marshmallow.fields.Email]\n```\n\nFor convenience, some custom types are provided:\n\n```python\nfrom marshmallow_dataclass.typing import Email, Url\n```\n\nWhen using Python 3.8, you must import `Annotated` from the typing_extensions package\n\n```python\n# Version agnostic import code:\nif sys.version_info \u003e= (3, 9):\n    from typing import Annotated\nelse:\n    from typing_extensions import Annotated\n```\n\n### Custom NewType declarations [__deprecated__]\n\n\u003e NewType is deprecated in favor or type aliases using Annotated, as described above.\n\nThis library exports a `NewType` function to create types that generate [customized marshmallow fields](https://marshmallow.readthedocs.io/en/stable/custom_fields.html#creating-a-field-class).\n\nKeyword arguments to `NewType` are passed to the marshmallow field constructor.\n\n```python\nimport marshmallow.validate\nfrom marshmallow_dataclass import NewType\n\nIPv4 = NewType(\n    \"IPv4\", str, validate=marshmallow.validate.Regexp(r\"^([0-9]{1,3}\\\\.){3}[0-9]{1,3}$\")\n)\n```\n\nYou can also pass a marshmallow field to `NewType`.\n\n```python\nimport marshmallow\nfrom marshmallow_dataclass import NewType\n\nEmail = NewType(\"Email\", str, field=marshmallow.fields.Email)\n```\n\nNote: if you are using `mypy`, you will notice that `mypy` throws an error if a variable defined with\n`NewType` is used in a type annotation. To resolve this, add the `marshmallow_dataclass.mypy` plugin\nto your `mypy` configuration, e.g.:\n\n```ini\n[mypy]\nplugins = marshmallow_dataclass.mypy\n# ...\n```\n\n### `Meta` options\n\n[`Meta` options](https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.Schema.Meta) are set the same way as a marshmallow `Schema`.\n\n```python\nfrom marshmallow_dataclass import dataclass\n\n\n@dataclass\nclass Point:\n    x: float\n    y: float\n\n    class Meta:\n        ordered = True\n```\n\n## Documentation\n\nThe project documentation is hosted on GitHub Pages: https://lovasoa.github.io/marshmallow_dataclass/\n\n## Contributing\n\nTo install this project and make changes to it locally, follow the instructions in [`CONTRIBUTING.md`](./CONTRIBUTING.md).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flovasoa%2Fmarshmallow_dataclass","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flovasoa%2Fmarshmallow_dataclass","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flovasoa%2Fmarshmallow_dataclass/lists"}