py-automapper
py-automapper copied to clipboard
feat: Allow lambda functions in mappings
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,.
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!