MyEnum: AbstractBaseClass for Flexible Enumerations#
- class my.types.MyEnum.MyEnum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)#
Enhanced Enum base class with flexible & ergonomic parsing, arithmetic, and comparison.
This class is built to be a useful base more than anything, but as-is, its main strength is in its (de)serialization methods. A single
read()call can parse strings (matching normalized names, string values, or regex aliases), integer values, and Flag lists all at once, while thewrite()method serializes enums back to strings, with pipe-separated names for combined flags.This class does not inherit from
enum.Flagby default, but it is built with support for such usecases out-of-the-box; to use those features, simply subclass bothMyEnumandFlag.Note
Total ordering is implemented based on enum value for numeric enums, and declaration order otherwise – if you want ordering based on string values, you’ll have to override
__lt__().Examples
Define an enum, then parse, serialize, and compare its members:
>>> from my import MyEnum >>> class Color(MyEnum): ... RED = 1 ... GREEN = 2 ... BLUE = 3 >>> Color.read('red') Color.RED >>> Color.RED.write() 'red' >>> Color.RED + 1 Color.GREEN >>> sorted([Color.BLUE, Color.RED]) [Color.RED, Color.BLUE]
Mix in
enum.Flagto unlock combined values:>>> from enum import Flag >>> class Perm(MyEnum, Flag): ... R = 1 ... W = 2 ... X = 4 >>> Perm.read('r|w') Perm.R|W >>> (Perm.R | Perm.W).write() 'r|w'
- classmethod MyEnum.read(value: str | int | list | Self) Self#
Parse a value into an enum member.
Supports multiple input formats:
Enum member: Returns as-is
String: Matches trimmed, case-insensitive names or values, regex aliases, and numbers
Integer: Matches exact values; for Flag enums, also accepts combined bit masks
List: For Flag enums, combines multiple values
- Parameters:
value – Value to parse into enum member.
- Returns:
Corresponding enum member.
- Raises:
ValueError – If value cannot be parsed.
Examples
Parse names, numeric strings, and flag lists:
>>> from enum import Flag >>> class Perm(MyEnum, Flag): ... R = 1 ... W = 2 ... X = 4 >>> Perm.read('r') Perm.R >>> Perm.read('2') Perm.W >>> Perm.read(['R', 'X']) Perm.R|X
- MyEnum.write() str#
Convert enum member to string representation.
- Returns:
String value, lowercase name, or pipe-separated flags for Flag enums.
Examples
Serialize simple members and flag unions:
>>> from enum import Flag >>> class Perm(MyEnum, Flag): ... R = 1 ... W = 2 >>> Perm.R.write() 'r' >>> (Perm.R | Perm.W).write() 'r|w'
- property MyEnum.parts: list[Self]#
The component members of Flag unions, else just
[self].Examples
Decompose a flag union into its atoms:
>>> from enum import Flag >>> class Perm(MyEnum, Flag): ... R = 1 ... W = 2 >>> (Perm.R | Perm.W).parts [Perm.R, Perm.W]