Skip to main content

No project description provided

Project description

Python ClassMapper

A simple class mapping (conversion) Python library.

Example

Imagine you have two classes, OriginCls and DestinationCls:

from dataclasses import dataclass

@dataclass
class OriginCls:
    id: str
    name: str
    age: int

@dataclass
class DestinationCls:
    _id: str
    data: dict

You want to be able to convert an object of OriginCls to DestinationCls and viceversa. ClassMapper allows you to define "mappers" - functions that explicitly convert an object of a class A to a new instance of a class B. Being explicit means that you have to explicitly define how the conversion between classes is performed.

from classmapper import ClassMapper

mapper = ClassMapper()

@mapper.register(OriginCls, DestinationCls)
def _mapper_origin_destination(_from: OriginCls) -> DestinationCls:
    return DestinationCls(
        _id=_from.id,
        data={
            "name": _from.name,
            "age": _from.age
        }
    )

@mapper.register(DestinationCls, OriginCls)
def _mapper_destination_origin(_from: DestinationCls) -> OriginCls:
    return OriginCls(
        id=_from._id,
        name=_from.data["name"],
        age=_from.data["age"]
    )

Now you can convert an object of OriginCls into DestinationCls, and viceversa:

source = OriginCls(id="1", name="foo", age=21)
# mapper.map(source object, target class)
#   returns object of target class, if a mapper between source object's class and target class is registered
result = mapper.map(source, DestinationCls)
print(result)

# convert back into the original
result = mapper.map(result, OriginCls)
print(result)

If you try to convert between classes not mapped, a NoClassMappingError is raised:

class OtherCls:
    pass

mapper.map(source, OtherCls)  # raises NoClassMappingError

More examples can be found on tests.

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

classmapper-0.0.1.tar.gz (3.3 kB view details)

Uploaded Source

File details

Details for the file classmapper-0.0.1.tar.gz.

File metadata

  • Download URL: classmapper-0.0.1.tar.gz
  • Upload date:
  • Size: 3.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for classmapper-0.0.1.tar.gz
Algorithm Hash digest
SHA256 a2e015007d6ffffa205cf8e0633d793037c4caecab922dd9967f6e60cc9ab9a5
MD5 dc9d5b2a6f90dfcdcae8545863e71ac9
BLAKE2b-256 4fdfdab992885c87981e73766233c6fc8159983dbd6d8b5e27fe701f2d885f01

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