Conditions | 4 |
Total Lines | 28 |
Code Lines | 14 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | from enum import EnumMeta |
||
5 | def default_enum_deserializer(obj: str, |
||
6 | cls: EnumMeta, |
||
7 | *, |
||
8 | use_enum_name: Optional[bool] = None, |
||
9 | **kwargs) -> object: |
||
10 | """ |
||
11 | Deserialize an enum value to an enum instance. The serialized value can be |
||
12 | either the name or the key of an enum entry. If ``use_enum_name`` is set to |
||
13 | ``True``, then the value *must* be the key of the enum entry. If |
||
14 | ``use_enum_name`` is set to ``False``, the value *must* be the value of the |
||
15 | enum entry. By default, this deserializer tries both. |
||
16 | :param obj: the serialized enum. |
||
17 | :param cls: the enum class. |
||
18 | :param use_enum_name: determines whether the name or the value of an enum |
||
19 | element should be used. |
||
20 | :param kwargs: not used. |
||
21 | :return: the corresponding enum element instance. |
||
22 | """ |
||
23 | if use_enum_name: |
||
24 | result = cls[obj] |
||
25 | elif use_enum_name is False: |
||
26 | result = cls(obj) |
||
27 | else: # use_enum_name is None |
||
28 | try: |
||
29 | result = cls[obj] |
||
30 | except KeyError: |
||
31 | result = cls(obj) # May raise a ValueError (which is expected). |
||
32 | return result |
||
33 |