Skip to main content

Autogenerate mappings between dataclasses

Project description

dataclass-mapper

Stable Version Build Status Documentation Status

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

This library makes sure that all fields of the target class are actually mapped to (already at the module import time), and also provides helper mappers for variables that don't change their names. It supports Python's dataclasses and also Pydantic models.

Installation

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

Example

We have the following target data structure, a class WorkContract that contains an attribute of type Person.

from dataclasses import dataclass

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

@dataclass
class WorkContract:
    worker: Person
    manager: Optional[Person]
    salary: int
    signable: bool

We want to have a safe mapper from the source data structure - SoftwareDeveloperContract with the attribute 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:

@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,
            full_name=f"{self.first_name} {self.surname}",
            age=self.age,
        )
      
@dataclass
class SoftwareDeveloperContract:
    worker: ContactInfo
    manager: Optional[ContactInfo]
    salary: int

    def to_WorkContract(self) -> WorkContract:
        return WorkContract(
            worker=self.worker.to_Person(),
            manager=(None if self.manager is None else self.manager.to_Person()),
            salary=self.salary,
            signable=True,
        )


software_developer_contract: SoftwareDeveloperContract
work_contract = software_developer_contract.to_WorkContract()

you can write:

from dataclass_mapper import map_to, mapper

@mapper(Person, {
  "second_name": "surname",
  "full_name": lambda self: f"{self.first_name} {self.surname}"
})
@dataclass
class ContactInfo:
    first_name: str
    surname: str
    age: int
      
@mapper(WorkContract, {"signable": lambda: True})
@dataclass
class SoftwareDeveloperContract:
    worker: ContactInfo
    manager: Optional[ContactInfo]
    salary: int

software_developer_contract: SoftwareDeveloperContract
work_contract = map_to(software_developer_contract, WorkContract)

Features

The current version has support for:

  • :heavy_check_mark: Python's dataclass
  • :heavy_check_mark: pydantic classes, if installed with pip install dataclass-mapper[pydantic]
  • :heavy_check_mark: Checking if all target fields are actually initialized. Raises a ValueError at class definition time when the type is different.
  • :heavy_check_mark: Simple types (str, int, float, datetime, custom types) if the type on the target is the same. Raises a TypeError at class definition time when the type is different.
  • :heavy_check_mark: Optional types. Raises a TypeError at class definition time when an optional type is mapped to a non-optional type.
  • :heavy_check_mark: Recursive models
  • :heavy_check_mark: List types
  • :heavy_check_mark: Default values for simple types
  • :heavy_check_mark: Mapper in the other direction. Use the mapper_from decorator and the same map_to method.
  • :heavy_check_mark: Assign Values with lambdas (with {"x": lambda: 42})
  • :heavy_check_mark: Assign Functions Calls with lambdas and self (with {"x": lambda self: self.x})
  • :heavy_check_mark: USE_DEFAULT for values that you don't wanna set but have a default value/factory

Still missing features:

  • :heavy_multiplication_x: Union types
  • :heavy_multiplication_x: Dict types
  • :heavy_multiplication_x: Aliases in pydantic classes
  • :heavy_multiplication_x: Checking if all source attributes were used
  • :heavy_multiplication_x: SQLAlchemy ORM

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.0.1.tar.gz (8.8 kB view details)

Uploaded Source

Built Distribution

dataclass_mapper-1.0.1-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file dataclass-mapper-1.0.1.tar.gz.

File metadata

  • Download URL: dataclass-mapper-1.0.1.tar.gz
  • Upload date:
  • Size: 8.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.14 CPython/3.9.13 Linux/5.15.0-1014-azure

File hashes

Hashes for dataclass-mapper-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1a919d089e355ef1edac90ffa90d8788fd3b5f75539d838e3ec53743f5849483
MD5 3c4563412b9053f78dceac310b060ea3
BLAKE2b-256 edca7bb8e233f6b79c9fddd8f63d38526ff5d9a184cc5622bc59f72c78f28f5b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: dataclass_mapper-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.1.14 CPython/3.9.13 Linux/5.15.0-1014-azure

File hashes

Hashes for dataclass_mapper-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 37e101d5064867f65f54ff71b6e5f53a01000a93753ffa9baff897a0ee60a1c0
MD5 902ca5ef588860eed4a707f016b6a146
BLAKE2b-256 59e65257900d434ced22d859a6fd42ab28fadeacfee67816e73f9b4295986f60

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