Skip to content

Conversation

hwdegroot
Copy link

@hwdegroot hwdegroot commented Jul 2, 2025

Add feature to use lambdas in fields_mappings, when registering a mapping. Gives the flexibility to define a mapping using the source object in a typesafe manner. similar to the c# AutoMapper.

class Property(BaseModel):
  x: str

class Source(BaseModel):
  default_index: int
  props: List[Property]

Target(BaseModel):
  default_prop: Property

mapper.map(Source, Target, fields_mapping={
  "default_prop": lambda source_obj: source_obj.props[source_ob.default_index]
})

In this mapping, The source class

source_obj = Source(default_prop=2, props=[Property(x="0"), Property(x="1"), Property(x="2"), Property(x="3")])
target_obj = mapper.map(source_obj)

will map to

Target(default_prop=Property(x="2"))

Normally one would do

source_obj = Source(default_prop=2, props=[Property(x="0"), Property(x="1"), Property(x="2"), Property(x="3")])
target_obj = mapper.to(Target).map(source_obj, fields_mapping={
  "default_prop": source_obj.props[source_ob.default_index]
})

But this is only possible as the moment the source_obj is initialized,.

@hwdegroot hwdegroot force-pushed the allow-callable-mappings branch 2 times, most recently from 28696b8 to 7265811 Compare July 3, 2025 04:09
@hwdegroot hwdegroot force-pushed the allow-callable-mappings branch from 7265811 to c7f1e0c Compare July 4, 2025 19:07
@hwdegroot
Copy link
Author

Hi @anikolaienko, really appreciate this library. Can you see if this can be merged into main Would provide a bit more functionality similar to the csharp AutoMapper library (and it would help me out).

Keep up the awsome work!

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