Add properties to Python enumeration values with a simple declarative syntax. Enum Properties is a lightweight extension to Python's Enum class. Example:
importtypingastfromenum_propertiesimportEnumPropertiesfromenumimportautoclassColor(EnumProperties):
rgb: t.Tuple[int, int, int]
hex: str# name value rgb hexRED=auto(), (1, 0, 0), 'ff0000'GREEN=auto(), (0, 1, 0), '00ff00'BLUE=auto(), (0, 0, 1), '0000ff'# the type hints on the Enum class become properties on# each value, matching the order in which they are specifiedassertColor.RED.rgb== (1, 0, 0)
assertColor.GREEN.rgb== (0, 1, 0)
assertColor.BLUE.rgb== (0, 0, 1)
assertColor.RED.hex=='ff0000'assertColor.GREEN.hex=='00ff00'assertColor.BLUE.hex=='0000ff'Properties may also be symmetrically mapped to enumeration values using annotated type hints:
importtypingastfromenum_propertiesimportEnumProperties, SymmetricfromenumimportautoclassColor(EnumProperties):
rgb: t.Annotated[t.Tuple[int, int, int], Symmetric()]
hex: t.Annotated[str, Symmetric(case_fold=True)]
RED=auto(), (1, 0, 0), 'ff0000'GREEN=auto(), (0, 1, 0), '00ff00'BLUE=auto(), (0, 0, 1), '0000ff'# Enumeration instances may be instantiated from any Symmetric property# values. Use case_fold for case insensitive matchingassertColor((1, 0, 0)) isColor.REDassertColor((0, 1, 0)) isColor.GREENassertColor((0, 0, 1)) isColor.BLUEassertColor('ff0000') isColor.REDassertColor('FF0000') isColor.RED# case_fold makes mapping case insensitiveassertColor('00ff00') isColor.GREENassertColor('00FF00') isColor.GREENassertColor('0000ff') isColor.BLUEassertColor('0000FF') isColor.BLUEassertColor.RED.hex=='ff0000'Member functions may also be specialized to each enumeration value, using the @specialize decorator.
fromenum_propertiesimportEnumPropertiesasEnum, specializeclassSpecializedEnum(Enum):
ONE=1TWO=2THREE=3@specialize(ONE)defmethod(self):
return'method_one()'@specialize(TWO)defmethod(self):
return'method_two()'@specialize(THREE)defmethod(self):
return'method_three()'assertSpecializedEnum.ONE.method() =='method_one()'assertSpecializedEnum.TWO.method() =='method_two()'assertSpecializedEnum.THREE.method() =='method_three()'Please report bugs and discuss features on the issues page.
Contributions are encouraged!
Full documentation at read the docs.
pip install enum-properties