py-automapper
py-automapper copied to clipboard
feat: Allow factory method when defining a mapping
Add feature to indicate a function or cunstructor to use as model factory. Mutually exclusive with the fields_mapping.
The model_factory: Callable[[S], T] will take a source_obj andshould return a target_obj
This allows the following mapping definitions
class SourceEnum(Enum):
VALUE1 = "value1"
VALUE2 = "value2"
VALUE3 = "value3"
class NameEnum(Enum):
VALUE1 = 1
VALUE2 = 2
VALUE3 = 3
class ValueEnum(Enum):
A = "value1"
B = "value2"
C = "value3"
mapper.add(SourceEnum, NameEnum, model_factory=lambda x: NameEnum[x.name])
mapper.map(SourceEnum.VALUE1) # NameEnum.VALUE1
mapper.add(ValueEnum, SourceEnum, model_factory=lambda x: SourceEnum(x.value))
mapper.map(ValueEnum.B) # SourceEnum.VALUE2
class ValueObject:
value: str
def __init__(self, value: Union[float, int, Decimal]):
self.value = str(value)
mapper.to(ValueObject).map(Decimal("42"), model_factory=ValueObject) # ValueObject(42)