hbutils.model.enum¶
- Overview:
Useful utilities for python enum class.
AutoIntEnum¶
-
class
hbutils.model.enum.
AutoIntEnum
(value)[source]¶ - Overview:
An example from official documentation.
- Examples::
>>> from hbutils.model import AutoIntEnum >>> class MyEnum(AutoIntEnum): ... def __init__(self, v): ... self.v = v ... A = 'a_v' ... B = 'b_vv' ... C = 'c_vvv' ... >>> MyEnum.A <MyEnum.A: 1> >>> MyEnum.A.value 1 >>> MyEnum.A.v 'a_v' >>> MyEnum.C <MyEnum.C: 3> >>> MyEnum.C.value 3 >>> MyEnum.C.v 'c_vvv'
int_enum_loads¶
-
hbutils.model.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