treevalue.utils.enum

int_enum_loads

treevalue.utils.enum.int_enum_loads(enable_int: bool = True, value_preprocess: Optional[Callable[[int], int]] = None, enable_str: bool = True, name_preprocess: Optional[Callable[[str], str]] = None, external_process: Optional[Callable[[Any], Optional[_EnumType]]] = None)[source]
Overview:

Decorate a int enum class with a new loads class method.

Arguments:
  • enable_int (bool): Enable int parse, default is True.

  • value_preprocess (Optional[Callable[[int, ], int]]): Preprocessor of value, default is None which means no change.

  • enable_str (bool): Enable str parse, default is True.

  • name_preprocess (Optional[Callable[[str, ], str]]): Preprocessor of name, default is None which means no change.

  • external_process (Optional[Callable[[Any, ], Optional[_EnumType]]]): External processor for the unprocessable data, default is None which means raise a KeyError.

Examples:
  • Simple usage

>>> from enum import IntEnum, unique
>>>
>>> @int_enum_loads()
>>> @unique
>>> class MyEnum(IntEnum):
>>>     A = 1
>>>     B = 2
>>>
>>> MyEnum.loads(1)    # MyEnum.A
>>> MyEnum.loads('A')  # MyEnum.A
>>> MyEnum.loads(2)    # MyEnum.B
>>> MyEnum.loads('B')  # MyEnum.B
>>> MyEnum.loads(-1)   # KeyError
>>> MyEnum.loads('a')  # KeyError
>>> MyEnum.loads('C')  # KeyError
  • Preprocessors

>>> from enum import IntEnum, unique
>>>
>>> @int_enum_loads(name_preprocess=str.upper, value_preprocess=abs)
>>> @unique
>>> class MyEnum(IntEnum):
>>>     A = 1
>>>     B = 2
>>>
>>> MyEnum.loads(1)    # MyEnum.A
>>> MyEnum.loads('A')  # MyEnum.A
>>> MyEnum.loads(2)    # MyEnum.B
>>> MyEnum.loads('B')  # MyEnum.B
>>> MyEnum.loads(-1)   # MyEnum.A
>>> MyEnum.loads('a')  # MyEnum.A
>>> MyEnum.loads('C')  # KeyError
  • External processor

>>> from enum import IntEnum, unique
>>>
>>> @int_enum_loads(external_process=lambda data: None)
>>> @unique
>>> class MyEnum(IntEnum):
>>>     A = 1
>>>     B = 2
>>>
>>> MyEnum.loads(1)    # MyEnum.A
>>> MyEnum.loads('A')  # MyEnum.A
>>> MyEnum.loads(2)    # MyEnum.B
>>> MyEnum.loads('B')  # MyEnum.B
>>> MyEnum.loads(-1)   # None
>>> MyEnum.loads('a')  # None
>>> MyEnum.loads('C')  # None