Skip to main content

Autogenerate mappings between dataclasses

Project description

pypi version supported Python version licence Read the documentation at https://dataclass-mapper.readthedocs.io/en/latest/ build status Code coverage

Writing mapper methods between two similar dataclasses is boring, need to be actively maintained and are error-prone. Much better to let a library auto-generate them for you.

This library makes it easy to autogenerate mappers, makes sure that the types between source and target class match, and that all fields of the target class are actually mapped to. Most of those checks are already done at class definition time, not when the mappings are run. It supports Python’s dataclasses and also Pydantic models, and can also map between those two.

Installation

dataclass-mapper can be installed using:

pip install dataclass-mapper
# or for Pydantic support
pip install dataclass-mapper[pydantic]

Small Example

We have the following target data structure, a class called Person.

from dataclasses import dataclass

@dataclass
class Person:
    first_name: str
    second_name: str
    age: int

We want to have a mapper from the source data structure, a class called ContactInfo. Notice that the attribute second_name of Person is called surname in ContactInfo. Other than that, all the attribute names are the same.

Instead of writing a mapper to_Person by hand:

@dataclass
class ContactInfo:
    first_name: str
    surname: str
    age: int

    def to_Person(self) -> Person:
        return Person(
            first_name=self.first_name,
            second_name=self.surname,
            age=self.age,
        )

person = some_contact.to_Person()

you can let the mapper autogenerate with:

from dataclass_mapper import map_to, mapper

@mapper(Person, {"second_name": "surname"})
@dataclass
class ContactInfo:
    first_name: str
    surname: str
    age: int

person = map_to(some_contact, Person)

The dataclass-mapper library autogenerated some a mapper, that can be used with the map_to function. All we had to specify was the name of the target class, and optionally specify which fields map to which other fields. Notice that we only had to specify that the second_name field has to be mapped to surname, all other fields were mapped automatically because the field names didn’t change.

And the dataclass-mapper library will perform a lot of checks around this mapping. It will check if the data types match, if some fields would be left uninitialized, etc.

Features

The current version has support for:

  • Python’s dataclass

  • pydantic classes

  • Checks if all target fields are actually initialized. Raises a ValueError at class definition time when the type is different.

  • Checks if the type on the target field is the same as the source field. Raises a TypeError at class definition time when the type is different.

  • Recursive dataclasses

  • IGNORE_MISSING_MAPPING for values that you don’t wanna set but have a default value/factory.

  • Optional types (mapping from an non-optional to an optional field, or to an optional field with default values/fields). Raises a TypeError at class definition time when an optional type is mapped to a non-optional type.

  • List types

  • Mapper in both direction with mapper and mapper_from.

  • Assign Values with lambdas (e.g. {"x": lambda: 42})

  • Custom mapping computations with with lambdas (e.g. {"x": lambda self: self.x + 1})

  • For Optional fields in Pydantic classes, only set those target fields that actually set in the source (__fields_set__).

  • Use Pydantic’s .construct method if no validators are used (can give an up to 30x boost)

Still missing features:

  • Union types

  • Dict types

  • Aliases in pydantic classes

  • Checking if all source attributes were used

  • SQLAlchemy ORM / attr

License

The project is released under the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dataclass_mapper-1.3.0.tar.gz (10.9 kB view details)

Uploaded Source

Built Distribution

dataclass_mapper-1.3.0-py3-none-any.whl (10.5 kB view details)

Uploaded Python 3

File details

Details for the file dataclass_mapper-1.3.0.tar.gz.

File metadata

  • Download URL: dataclass_mapper-1.3.0.tar.gz
  • Upload date:
  • Size: 10.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.2.2 CPython/3.9.15 Linux/5.15.0-1023-azure

File hashes

Hashes for dataclass_mapper-1.3.0.tar.gz
Algorithm Hash digest
SHA256 520af080103da80b1a8aa8b10999fc589feb2523e67f737b2d36cdbffa542934
MD5 5a6e23ae608d700bb4e4627242fabd13
BLAKE2b-256 4fbe9bfd4caef321bbb16a3fd20e7d5d39d481c67931426dfbf4547c322e5187

See more details on using hashes here.

File details

Details for the file dataclass_mapper-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: dataclass_mapper-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 10.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.2.2 CPython/3.9.15 Linux/5.15.0-1023-azure

File hashes

Hashes for dataclass_mapper-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 cde48028775edd334e5a6ddc4fb873196dd9210f2baad97b319ac6e82e9ab256
MD5 7c7179f17fa4393d3ae27f5e83c71642
BLAKE2b-256 6c6fa9d6e526304280074d0a3be3113d7ba69c23121b54ecec1423d663f4a329

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page