Skip to content

Commit 27f81ce

Browse files
authored
Merge pull request #17 from soldag/so/enum
Fix mapping of string enum types
2 parents 01c2508 + e658a3d commit 27f81ce

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

automapper/mapper.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import inspect
22
from copy import deepcopy
3+
from enum import Enum
34
from typing import (
45
Any,
56
Callable,
@@ -51,6 +52,11 @@ def _is_primitive(obj: Any) -> bool:
5152
return type(obj) in __PRIMITIVE_TYPES
5253

5354

55+
def _is_enum(obj: Any) -> bool:
56+
"""Check if object type is enum"""
57+
return issubclass(type(obj), Enum)
58+
59+
5460
def _try_get_field_value(
5561
field_name: str, original_obj: Any, custom_mapping: FieldsMap
5662
) -> Tuple[bool, Any]:
@@ -267,7 +273,7 @@ def _map_subobject(
267273
self, obj: S, _visited_stack: Set[int], skip_none_values: bool = False
268274
) -> Any:
269275
"""Maps subobjects recursively"""
270-
if _is_primitive(obj):
276+
if _is_primitive(obj) or _is_enum(obj):
271277
return obj
272278

273279
obj_id = id(obj)

tests/test_automapper_enum.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from enum import Enum
2+
from typing import Tuple
3+
4+
from automapper import mapper
5+
6+
7+
class StringEnum(str, Enum):
8+
Value1 = "value1"
9+
Value2 = "value2"
10+
Value3 = "value3"
11+
12+
13+
class IntEnum(int, Enum):
14+
Value1 = 1
15+
Value2 = 2
16+
Value3 = 3
17+
18+
19+
class TupleEnum(Tuple[str, str], Enum):
20+
Value1 = ("value", "1")
21+
Value2 = ("value", "2")
22+
Value3 = ("value", "3")
23+
24+
25+
class SourceClass:
26+
def __init__(
27+
self, string_value: StringEnum, int_value: IntEnum, tuple_value: TupleEnum
28+
) -> None:
29+
self.string_value = string_value
30+
self.int_value = int_value
31+
self.tuple_value = tuple_value
32+
33+
34+
class TargetClass:
35+
def __init__(
36+
self, string_value: StringEnum, int_value: IntEnum, tuple_value: TupleEnum
37+
) -> None:
38+
self.string_value = string_value
39+
self.int_value = int_value
40+
self.tuple_value = tuple_value
41+
42+
43+
def test_map__enum():
44+
src = SourceClass(StringEnum.Value1, IntEnum.Value2, TupleEnum.Value3)
45+
dst = mapper.to(TargetClass).map(src)
46+
47+
assert dst.string_value == StringEnum.Value1
48+
assert dst.int_value == IntEnum.Value2
49+
assert dst.tuple_value == TupleEnum.Value3

0 commit comments

Comments
 (0)