Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Morty Proxy This is a proxified and sanitized view of the page, visit original site.