Skip to content

feat: Allow factory method when defining a mapping #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

hwdegroot
Copy link

@hwdegroot hwdegroot commented Jul 4, 2025

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)

@hwdegroot hwdegroot force-pushed the add-model-factory branch from 6f5d3b1 to 7194135 Compare July 4, 2025 15:46
@hwdegroot hwdegroot force-pushed the add-model-factory branch from 7194135 to 7b9da64 Compare July 4, 2025 19:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant