Skip to content

Commit 4ed3df9

Browse files
committed
python-stdlib\enum\enum.py: Rewrite Enum with Gemini.
Rewrite Enum with Gemini. Add enum.md. Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
1 parent 6e709ca commit 4ed3df9

File tree

4 files changed

+518
-262
lines changed

4 files changed

+518
-262
lines changed

python-stdlib/enum/enum.md

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
Below is the documentation for your `enum.py` library. This file explains the core concepts of your custom `Enum` implementation and provides practical examples for embedded development and general logic.
2+
3+
---
4+
5+
# Custom Enum Library for Python & MicroPython
6+
7+
This library provides a flexible, memory-efficient `Enum` class designed for dynamic usage and seamless mathematical integration. Unlike the standard CPython `Enum`, this version allows for runtime expansion and direct arithmetic operations without needing to access a `.value` property.
8+
9+
## Core Features
10+
* **Transparent Math**: Supports arithmetic (`+`, `-`, `*`, `/`) and bitwise (`&`, `|`, `^`, `<<`, `>>`) operations directly on enum members.
11+
* **Dynamic Expansion**: Add new members at runtime via `.append()` or direct attribute assignment.
12+
* **Memory Efficient**: Uses `__slots__` in the `ValueWrapper` to minimize RAM usage on platforms like the ESP32.
13+
* **Flexible Initialization**: Can be initialized via class inheritance, dictionaries, or keyword arguments.
14+
15+
---
16+
17+
## Usage Examples
18+
19+
### 1. Hardware Pin Configuration (ESP32)
20+
Define your hardware pins using class inheritance. You can skip internal or reserved pins using the `__skipped__` attribute.
21+
22+
```python
23+
from enum import Enum
24+
25+
class Pins(Enum):
26+
# Members defined at class level
27+
LED = 2
28+
BUTTON = 4
29+
# Members to exclude from the enum mapping
30+
__skipped__ = ('RESERVED_PIN',)
31+
RESERVED_PIN = 0
32+
33+
# You can also add pins during instantiation
34+
pins = Pins(SDA=21, SCL=22)
35+
36+
print(f"I2C SDA Pin: {pins.SDA}") # Output: 21
37+
print(f"Is pin 21 valid? {pins.is_value(21)}") # Output: True
38+
```
39+
40+
### 2. Math and Register Logic
41+
The `ValueWrapper` allows you to perform calculations directly. This is particularly useful for bitmasks and step-based logic.
42+
43+
```python
44+
# Initialize with key-value pairs
45+
brightness = Enum(MIN=0, STEP=25, MAX=255)
46+
47+
# Direct arithmetic (Forward and Reflected)
48+
next_level = brightness.MIN + brightness.STEP // 2
49+
complex_math = 100 + brightness.STEP
50+
51+
print(f"Next Level: {next_level}") # Output: 12
52+
print(f"Complex Math: {complex_math}") # Output: 125
53+
54+
# Bitwise operations for register control
55+
flags = Enum(BIT_0=0x01, BIT_1=0x02)
56+
combined = flags.BIT_0 | flags.BIT_1
57+
print(f"Combined Flags: {hex(combined)}") # Output: 0x03
58+
```
59+
60+
### 3. Dynamic State Machines
61+
You can expand an `Enum` as your program logic progresses, such as adding states to a connection manager.
62+
63+
```python
64+
status = Enum(IDLE=0, CONNECTING=1)
65+
66+
# Add multiple members via append()
67+
status.append(CONNECTED=2, ERROR=3)
68+
69+
# Add a single member via direct assignment
70+
status.DISCONNECTING = 4
71+
72+
for name, val in status.items():
73+
print(f"Status {name} has code {val}")
74+
```
75+
76+
### 4. Working with Different Data Types
77+
Enums are not restricted to integers; they can wrap strings, floats, and booleans.
78+
79+
```python
80+
commands = Enum(
81+
START="CMD_START",
82+
STOP="CMD_STOP",
83+
TIMEOUT=5.5,
84+
IS_ACTIVE=True
85+
)
86+
87+
if commands.IS_ACTIVE:
88+
# Use str() to get the wrapped string value
89+
print(f"Executing: {commands.START}")
90+
```
91+
92+
### 5. Introspection and Utilities
93+
The library provides helper methods to validate values or find keys based on their values.
94+
95+
```python
96+
class ErrorCodes(Enum):
97+
NOT_FOUND = 404
98+
SERVER_ERROR = 500
99+
100+
# Check if a value exists in the Enum
101+
exists = ErrorCodes.is_value(404) # True
102+
103+
# Get the formatted string name from a value
104+
name = ErrorCodes.key_from_value(500)
105+
print(name) # Output: ErrorCodes.SERVER_ERROR
106+
```
107+
108+
---
109+
110+
## API Reference
111+
112+
### `ValueWrapper`
113+
The internal class that wraps values to enable mathematical transparency.
114+
* `.value`: Access the raw value.
115+
* `()`: Calling the object returns the raw value.
116+
117+
### `Enum` (Inherits from `dict`)
118+
* `append(arg=None, **kwargs)`: Adds new members to the Enum.
119+
* `is_value(value)`: Returns `True` if the value exists in the Enum.
120+
* `key_from_value(value)`: Returns the string representation (e.g., `ClassName.KEY`) for a given value.

0 commit comments

Comments
 (0)