Enum Metadata and Serialization

This example demonstrates how to work with enum metadata and serialization features.

Example Code

Enum Metadata and Serialization Example
  1"""
  2Examples of enum metadata and serialization features.
  3"""
  4
  5from enum import Enum
  6
  7from true.enums_toolkits import metadata, MetadataConfig, SerializedEnumMeta
  8
  9
 10def demo_basic_metadata():
 11    """Demonstrate basic metadata usage."""
 12    print("=== Basic Metadata ===")
 13
 14    # Create enum with default metadata
 15    @metadata()
 16    class Status(Enum):
 17        PENDING = 0
 18        ACTIVE = 1
 19        INACTIVE = 2
 20
 21    print("Default metadata:")
 22    for member in Status:
 23        print(f"\n{member.describe}")
 24
 25
 26#
 27def demo_custom_metadata():
 28    """Demonstrate custom metadata configuration."""
 29    print("\n=== Custom Metadata ===")
 30    #
 31    # Create custom metadata config
 32    config = MetadataConfig(
 33        include_bit_length=True,
 34        include_type_info=True,
 35        custom_attributes={
 36            "Category": "System Status",
 37            "Reversible": True
 38        },
 39        default_value="Unknown"
 40    )
 41
 42    #
 43    @metadata(config)
 44    class ProcessState(Enum):
 45        STARTING = 0
 46        RUNNING = 1
 47        STOPPING = 2
 48        STOPPED = 3
 49
 50    #
 51    print("Custom metadata configuration:")
 52    for member in ProcessState:
 53        print(f"\n{member.describe}")
 54    #
 55    # Set custom description
 56    try:
 57        ProcessState.set_description(ProcessState.STARTING, "Process is actively executing tasks")
 58        print(f"\nCustom description for RUNNING:")
 59        print(ProcessState.RUNNING.describe)
 60    except Exception as e:
 61        print(f"Error setting description: {e}")
 62
 63
 64#
 65def demo_serialization():
 66    """Demonstrate serialization features."""
 67    print("\n=== Serialization ===")
 68
 69    #
 70    #     # Create enum with serialization support
 71    class Color(Enum, metaclass=SerializedEnumMeta):
 72        RED = "#FF0000"
 73        GREEN = "#00FF00"
 74        BLUE = "#0000FF"
 75
 76    #
 77    # Convert to dictionary
 78    color_dict = Color.to_dict()
 79    print("Enum as dictionary:")
 80    for name, value in color_dict.items():
 81        print(f"{name}: {value}")
 82    #
 83    # Create new enum from dictionary
 84    members = {
 85        "SUCCESS": 200,
 86        "NOT_FOUND": 404,
 87        "ERROR": 500
 88    }
 89    #
 90    StatusCode = Color.from_dict("StatusCode", members)
 91    print("\nEnum from dictionary:")
 92    for member in StatusCode:
 93        print(f"{member.name}: {member.value}")
 94
 95    #     # JSON serialization
 96    json_data = Color.to_json()
 97    print("\nEnum as JSON:")
 98    print(json_data)
 99    #
100    # Create enum from JSON
101    json_members = '{"SMALL": 1, "MEDIUM": 2, "LARGE": 3}'
102    Size = Color.from_json("Size", json_members)
103    print("\nEnum from JSON:")
104    for member in Size:
105        print(f"{member.name}: {member.value}")
106
107
108#
109def demo_combined_features():
110    """Demonstrate combination of metadata and serialization."""
111    print("\n=== Combined Features ===")
112
113    @metadata(MetadataConfig(
114        custom_attributes={"API_Version": "1.0"}
115    ))
116    class ApiStatus(Enum, metaclass=SerializedEnumMeta):
117        OK = {"code": 200, "message": "Success"}
118        ERROR = {"code": 500, "message": "Internal Error"}
119        NOT_FOUND = {"code": 404, "message": "Resource Not Found"}
120
121    #
122    # Show metadata
123    print("API Status with metadata:")
124    for member in ApiStatus:
125        print(f"\n{member.describe}")
126
127    #     # Serialize
128    print("\nAPI Status as dictionary:")
129    api_dict = ApiStatus.to_dict()
130    for name, value in api_dict.items():
131        print(f"{name}: {value}")
132
133
134if __name__ == "__main__":
135    demo_basic_metadata()
136    demo_custom_metadata()
137    demo_serialization()
138    demo_combined_features()

Key Features

  1. Metadata Management - Adding metadata to enums - Accessing metadata - Metadata inheritance

  2. Serialization - JSON serialization - Custom serialization formats - Deserialization support

  3. Advanced Features - Metadata validation - Schema support - Version control