Enums Toolkits Module

The enums toolkits module provides a sophisticated framework for defining specialized Enum classes in Python, extending the native Enum capabilities with advanced features like metadata handling, serialization, and type-specific validation.

Key Components

Classes

MetadataConfig

class true.enums_toolkits.MetadataConfig(include_bit_length=True, include_type_info=True, custom_attributes=None, default_value='N/A')[source]

Configuration for enum metadata.

include_bit_length: bool = True
include_type_info: bool = True
custom_attributes: Dict[str, Any] = None
default_value: Any = 'N/A'
__init__(include_bit_length=True, include_type_info=True, custom_attributes=None, default_value='N/A')

SerializedEnumMeta

class true.enums_toolkits.SerializedEnumMeta(name: str, bases: tuple, namespace: dict, **kwargs)[source]
__getitem__(item)[source]

Allow enum items to be retrieved using bracket notation (Enum[item]). Provides a custom KeyError message.

Return type:

Enum

static __new__(mcs, name, bases, namespace, **kwargs)[source]

Custom Meta class for advanced Enum features.

classmethod from_dict(name, members, *, preserve_original=True)[source]

Generate an Enum class from a dictionary of member names and values.

Parameters:
  • name (str) – Name for the new enum class

  • members (Dict[str, Any]) – Dictionary mapping member names to their values

  • preserve_original (bool) – If True, preserves original enum class metadata

Return type:

Type[Enum]

Returns:

A new Enum class with the specified members

classmethod from_json(name, json_data, *, preserve_original=True)[source]

Generate an Enum class from a JSON string or dictionary.

Parameters:
  • name (str) – Name for the new enum class

  • json_data (NewType(JsonType, dict)) – JSON string or dictionary containing enum members

  • preserve_original (bool) – If True, preserves original enum class metadata

Return type:

Type[Enum]

Returns:

A new Enum class with the specified members

Raises:
  • ValueError – If invalid JSON data is provided

  • TypeError – If json_data is neither a string nor dictionary

to_dict()[source]

Convert enum class to a dictionary representation.

Return type:

Dict[str, Any]

Returns:

Dictionary containing member names mapped to their values

to_json()[source]

Convert enum class to a JSON string representation.

Return type:

str

Returns:

JSON string containing the enum class data

DynamicEnum

class true.enums_toolkits.DynamicEnum(**kwargs)[source]

A dynamic enumeration class that allows runtime modification of members.

This class provides functionality to create and manage enum-like objects that can be modified during runtime, unlike traditional Python enums. It supports adding and removing members dynamically while maintaining the familiar enum interface.

Variables:

_value2member_map_ (Dict[Any, Any]) – Mapping of values to enum members.

__init__(**kwargs)[source]
add_member(name, value)[source]

Adds a new member to the enumeration.

Parameters:
  • name (str) – The name of the new enum member.

  • value (Any) – The value associated with the enum member.

Raises:

ValueError – If the name is invalid or already exists.

Return type:

None

remove_member(name)[source]

Removes a member from the enumeration.

Parameters:

name (str) – The name of the enum member to remove.

Raises:

ValueError – If the member does not exist.

Return type:

None

property names: list

Returns a list of all member names.

Returns:

List of member names.

Return type:

list

property values: list

Returns a list of all member values.

Returns:

List of member values.

Return type:

list

classmethod from_enum(enum_class)[source]

Creates a DynamicEnum from an existing Enum class.

Parameters:

enum_class (type[Enum]) – The source Enum class to convert.

Returns:

A new DynamicEnum instance with members from the source Enum.

Return type:

DynamicEnum

DynamicEnumMember

class true.enums_toolkits.DynamicEnumMember(name, value, enum_class)[source]

Represents a member of a DynamicEnum.

This class encapsulates the name and value of an enum member and provides comparison and string representation functionality.

Variables:
  • _name (str) – The name of the enum member.

  • _value (Any) – The value of the enum member.

  • _enum_class (DynamicEnum) – Reference to the parent enum class.

__init__(name, value, enum_class)[source]
property name: str

Gets the name of the enum member. :returns: The name of the enum member. :rtype: str

property value: Any

Gets the value of the enum member.

Returns:

The value of the enum member.

Return type:

Any

Type-Specific Enums

IterableEnum

class true.enums_toolkits.IterableEnum[source]

Enumeration for iterable objects.

This class ensures that the value is an iterable.

Raises:

EnumTypeError – If the provided value is not iterable.

IteratorEnum

class true.enums_toolkits.IteratorEnum[source]

Enumeration for iterator objects.

This class ensures that the value is an iterator.

Raises:

EnumTypeError – If the provided value is not an iterator.

GeneratorEnum

class true.enums_toolkits.GeneratorEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for generator objects.

This class ensures that the value is a generator.

Raises:

EnumTypeError – If the provided value is not a generator.

property value
property name

ByteEnum

class true.enums_toolkits.ByteEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for byte values.

This class ensures that values are of type bytes.

Raises:

EnumTypeError – If the provided value is not of type bytes.

FloatEnum

class true.enums_toolkits.FloatEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for float values.

This class ensures that values are of type float.

Raises:

EnumTypeError – If the provided value is not of type float.

ComplexNumberEnum

class true.enums_toolkits.ComplexNumberEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

DictEnum

class true.enums_toolkits.DictEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for dictionary values.

This class ensures that a single dictionary is provided during instantiation.

Raises:

EnumValidationError – If more than one argument is provided or the first argument is not a dictionary.

SetEnum

class true.enums_toolkits.SetEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for set values.

This class ensures that the provided value is of type set, list, or tuple.

Raises:

EnumTypeError – If the provided value is not of type set, list, or tuple.

ListEnum

class true.enums_toolkits.ListEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for list values.

This class ensures that the provided value is of type list or tuple.

Raises:

EnumTypeError – If the provided value is not of type list or tuple.

TupleEnum

class true.enums_toolkits.TupleEnum(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Enumeration for tuple values.

This class ensures that the provided value is of type list or tuple.

Raises:

EnumTypeError – If the provided value is not of type list or tuple.

Decorators

metadata

true.enums_toolkits.metadata(config=None)[source]

A decorator that adds metadata capabilities to Enum classes.

Parameters:

config (Optional[MetadataConfig]) – Configuration object for metadata handling. If not provided, default configuration will be used.

Return type:

Callable[[Type[TypeVar(E, bound= Enum)]], Type[TypeVar(E, bound= Enum)]]

Returns:

A decorator function that enhances the Enum class with metadata capabilities.

Raises:

EnumMetadataError – If there are issues with metadata configuration.

Examples

Basic Usage with DynamicEnum

from true.enums_toolkits import DynamicEnum

# Create a dynamic enum
colors = DynamicEnum(RED="red", GREEN="green", BLUE="blue")

# Access members
print(colors.RED.value)  # "red"
print(colors.RED.name)   # "RED"

# Add new members at runtime
colors.add_member("YELLOW", "yellow")

# Remove members
colors.remove_member("BLUE")

Type-Safe Enums

from true.enums_toolkits import FloatEnum, DictEnum, SetEnum

class Temperatures(FloatEnum):
    FREEZING = 0.0
    BOILING = 100.0

class Config(DictEnum):
    DEFAULT = {"host": "localhost", "port": 8080}
    PRODUCTION = {"host": "example.com", "port": 443}

class Permissions(SetEnum):
    READ = {"read"}
    WRITE = {"read", "write"}
    ADMIN = {"read", "write", "admin"}

Metadata and Serialization

from true.enums_toolkits import metadata, MetadataConfig, SerializedEnumMeta
from enum import Enum

config = MetadataConfig(
    include_bit_length=True,
    include_type_info=True,
    custom_attributes={"category": "status"}
)

@metadata(config)
class Status(Enum):
    ACTIVE = 1
    INACTIVE = 0

# Get detailed description
print(Status.ACTIVE.get_description())

# Serialization
class Colors(metaclass=SerializedEnumMeta):
    RED = "#FF0000"
    GREEN = "#00FF00"
    BLUE = "#0000FF"

# Convert to dict/json
colors_dict = Colors.to_dict()
colors_json = Colors.to_json()

# Create from dict/json
new_colors = Colors.from_dict("NewColors", {"PURPLE": "#800080"})