Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
de15faf
python-stdlib\enum\enum.py: Add Enum class.
IhorNehrutsa Mar 5, 2025
8707ea2
python-stdlib\enum: Bump to version="1.4.0".
IhorNehrutsa Oct 5, 2026
6328477
python-stdlib\enum: Add mini Enum implementation.
IhorNehrutsa Oct 6, 2026
8aa455a
enum: Add CPython and MicroPython demo.
IhorNehrutsa Oct 10, 2026
868bc0b
python-stdlib\enum: Bump to version="1.5.0".
IhorNehrutsa Oct 17, 2026
2ba0ffb
python-stdlib/enum: Improve StrEnum behavior and tests
MrCodeGameandAnime Oct 20, 2026
85a6128
python-stdlib\enum: Bump to version="1.5.1".
IhorNehrutsa Oct 20, 2026
30d1f97
python-stdlib\enum_mini: Bump to version="1.5.1".
IhorNehrutsa Oct 20, 2026
33d829b
python-stdlib\enum: Bump to version="1.5.2".
IhorNehrutsa Nov 20, 2026
4a2e389
Add prev enums version.
IhorNehrutsa Nov 20, 2026
4d7491c
enum: Move versions to save _wip.
IhorNehrutsa Nov 23, 2026
dd00ae7
enum: Save enum_1_5_2.py.
IhorNehrutsa Nov 23, 2026
54defb8
enum: Move usage examples.
IhorNehrutsa Nov 23, 2026
523dc90
python-stdlib/enum: Remove redundant source version comments.
MrCodeGameandAnime Nov 23, 2026
5746add
python-stdlib/enum: Move development checks into unit tests.
IhorNehrutsa Nov 23, 2026
e040e4c
python-stdlib/enum: Check declared Enum member identity.
MrCodeGameandAnime Nov 23, 2026
b32e2d4
python-stdlib/enum: Isolate StrEnum value lookup check.
MrCodeGameandAnime Nov 23, 2026
e2c2c06
enum: Save enum_check.py.
IhorNehrutsa Nov 23, 2026
b9640d2
enum: Remove redundant source version comments.
IhorNehrutsa Nov 24, 2026
0e11d6e
enum: Fix ruff.
IhorNehrutsa Nov 24, 2026
35564ce
enum: Clarify README.
IhorNehrutsa Nov 24, 2026
b3378d0
enum: Add test_enum.py from #1061.
IhorNehrutsa Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
232 changes: 232 additions & 0 deletions python-stdlib/enum/CPy/CPy.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file isn't documented, but it looks like development support code rather than something we'd merge into micropython-lib. As discussed elsewhere, ideally there is a way to port the actual CPython enum test code in a way that it can be run to verify the enum code here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@IhorNehrutsa, are you still planning to use Andrew’s CPython-derived tests as the starting point? I can help split the tests into cases shared by full and mini, cases specific to full, and a separate check for importing both modules. I’d also move any useful checks from CPy/CPy.py into the suite before removing the script. Does that work for you?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I use CPy.py like this:

microPython\micropython-lib\python-stdlib\enum\CPy>python.exe CPy.py

microPython\micropython-lib\python-stdlib\enum\CPy>python.exe -m mpremote connect COM9 run CPy.py

Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
# CPy.py

import sys

is_micropython = sys.implementation.name == "micropython"

if is_micropython:
from sys import print_exception

from enum import Enum, EnumMeta, StrEnum, IntEnum

class Mode(Enum):
FAST = "fast"
SLOW = "slow"

def describe(self):
return self.name + ":" + self.value

print('Mode:', Mode)
print('type(Mode):', type(Mode))
print('Mode.FAST:', Mode.FAST)
print('type(Mode.FAST):', type(Mode.FAST))

m = Mode.FAST
print('m:', m)


class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3


print("--- Enum (class syntax) --- # CPython # MicroPython output")
print(Color) # <enum 'Color'>
print(type(Color)) # <class 'enum.EnumType'> # <class 'Color'>
print(Color.__members__) # {'RED': <Color.RED: 1>, 'GREEN': <Color.GREEN: 2>, 'BLUE': <Color.BLUE: 3>} # {<Color.RED: 1>: 1, <Color.GREEN: 2>: 2, <Color.BLUE: 3>: 3}
print(list(Color)) # [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]

print(Color.RED) # Color.RED
print(type(Color.RED)) # <enum 'Color'> # <class 'Color.RED'>
print(Color.RED.name) # RED
print(Color.RED.value) # 1
print(repr(Color.RED)) # <Color.RED: 1>
print(Color.__contains__(1)) # True
print(Color.__contains__(11)) # False
print(Color.__contains__(Color.RED)) # True
print(Color.RED.value == 1) # True
print(Color.RED.value + 10) # 11
print(Color(1) is Color.RED) # True
print()

print(Color) # <enum 'Color'>
print(repr(Color)) # <enum 'Color'>
if is_micropython:
print(len(Color())) # 3
print(Color()["RED"]) # Color.RED
print(Color()["RED"] is Color.RED) # True
print(Color.RED == 1) # True
else:
print(len(Color)) # 3
print(Color["RED"]) # Color.RED
print(Color["RED"] is Color.RED) # True
print(Color.RED == 1) # False

print("\n--- Immutability Tests ---")
try:
Color.RED.value = 99
0 / 0
except AttributeError:
print("Protected: Cannot reassign class attribute")

try:
Color.RED = 99
if is_micropython:
print("MicroPython: NOT Protected: Can reassign class attribute")
Color.RED = Color._i()["RED"]
else:
0 / 0
except AttributeError:
print("Protected: Cannot reassign class attribute")

try:
del Color.RED
if is_micropython:
print("MicroPython: NOT Protected: Can delete class attribute")
Color.RED = Color._i()["RED"]
else:
0 / 0
except AttributeError:
print("Protected: Cannot delete class attribute")

try:
Color.RED.custom = 5
print("CPython: NOT Protected: Set attribute on enum item") # CPython: NOT Protected: Set attribute on enum item
except AttributeError:
print("MicroPython: Protected: Cannot set attribute on enum item") # MicroPython: Protected: Cannot set attribute on enum item

assert Color.RED.value == 1

print("\n--- Functional API & Extensions ---")
try:
DynCoord = Enum("DynCoord", {"X": 10, "Y": 20})
print(DynCoord) # <enum 'DynCoord'>
print(type(DynCoord)) # <class 'enum.EnumType'> # <class 'DynCoord'>
print(DynCoord.__members__) # {'X': <DynCoord.X: 10>, 'Y': <DynCoord.Y: 20>} # {<DynCoord.Y: 20>: 20, <DynCoord.X: 10>: 10}
print(list(DynCoord)) # [<DynCoord.X: 10>, <DynCoord.Y: 20>] # [<DynCoord.Y: 20>, <DynCoord.X: 10>]
print(DynCoord.X.value) # 10
print(type(DynCoord.X) is DynCoord) # True
except Exception as e:
print(f"Functional dict API error: {e}")
print_exception(e)
1/0

print()
try:
DynStr = StrEnum("DynStr", "A B C")
print(DynStr) # <enum 'DynStr'>
print(type(DynStr)) # <class 'enum.EnumType'> # <class 'DynStr'>
print(DynStr.__members__) # {'A': <DynStr.A: 'a'>, 'B': <DynStr.B: 'b'>, 'C': <DynStr.C: 'c'>} # {<DynStr.A: 'a'>: 'a', <DynStr.C: 'c'>: 'c', <DynStr.B: 'b'>: 'b'}
print(list(DynStr)) # [<DynStr.A: 'a'>, <DynStr.B: 'b'>, <DynStr.C: 'c'>] # [<DynStr.A: 'a'>, <DynStr.C: 'c'>, <DynStr.B: 'b'>]
print(DynStr.A.value) # a
print(type(DynStr.A) is DynStr) # True

print(isinstance(DynStr.A, StrEnum)) # True
print(repr(DynStr.A)) # <DynStr.A: 'a'> # 'a' on MicroPython
except Exception as e:
print(f"Functional string API not supported or error: {e}")
print_exception(e)

try:
class Colors(Color):
YELLOW = 'yellow'
except TypeError as e:
print(f"TypeError: {e}") # TypeError: <enum 'Colors'> cannot extend <enum 'Color'> # TypeError: Colors cannot extend Color
if is_micropython:
print_exception(e)

if is_micropython:
print("\n--- Dump & Restore (if available) ---")
d_str = Color.dump()
print("Dump:", d_str) # Dump: Enum('Color', {'BLUE': 3, 'RED': 1, 'GREEN': 2})
Restored = eval(d_str)
print(Restored) # <enum 'Color'>
print(type(Restored)) # <class 'Color'>
print(list(Restored())) # [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
print(Color.__members__) # {<Color.RED: 1>: 1, <Color.GREEN: 2>: 2, <Color.BLUE: 3>: 3}
print(Restored.__members__) # {<Color.RED: 1>: 1, <Color.GREEN: 2>: 2, <Color.BLUE: 3>: 3}
print("Restored equality:", Restored == Color) # True
print("Color.RED.value:", Color.RED.value) # True
print("Restored.RED.value:", Restored.RED.value) # True
print("Restored equality:", Restored.RED.value == Color.RED.value) # True

class Mode(StrEnum):
FAST = "fast"
SLOW = "slow"

print("\n--- Class ---")
print(list(Mode))
print("Mode:", Mode)
print("type(Mode):", type(Mode))
print("Mode.FAST:", Mode.FAST)
print("type(Mode.FAST):", type(Mode.FAST))
print('Mode("fast"):', Mode("fast"))
print('type(Mode("fast")):', type(Mode("fast")))
print("Members:", getattr(Mode, "__members__", None))

assert isinstance(Mode.FAST, str)

assert Mode.FAST.name == "FAST"
assert Mode.FAST.value == "fast"
#assert Mode(Mode.FAST) is Mode.FAST
#assert Mode("fast") is Mode.FAST

if is_micropython:
assert issubclass(Mode, str)
assert issubclass(Mode, EnumMeta)
assert issubclass(Mode, Enum)
assert issubclass(Mode, StrEnum)

assert isinstance(Mode, type)
assert isinstance(Mode(), str)
assert isinstance(Mode(), Enum)
assert isinstance(Mode(), StrEnum)
else:
pass

if is_micropython:
assert issubclass(Mode, Enum)
assert issubclass(Mode, StrEnum)
pass
else:
assert issubclass(Mode, Enum)
assert issubclass(Mode, StrEnum)

if is_micropython:
assert isinstance(Mode.FAST, Mode)
pass
else:
assert isinstance(Mode.FAST, Mode)

if is_micropython:
print("\n--- Instance(MicroPython) ---")
mode = Mode()
print("Mode:", Mode)
print("mode:", mode)
print("type(mode):", type(mode))
print("mode.FAST:", mode.FAST)
print("type(mode.FAST):", type(mode.FAST))
print("Members:", getattr(mode, "__members__", None))

assert mode.FAST.name == "FAST"
assert mode.FAST.value == "fast"
assert mode("fast") is mode.FAST
assert mode(mode.FAST) is mode.FAST

assert issubclass(type(mode), Enum)
assert issubclass(type(mode), StrEnum)

assert isinstance(mode, Enum)
assert isinstance(mode, StrEnum)

assert isinstance(mode.FAST, str)
assert isinstance(mode.FAST, type(mode))

assert type(mode) is Mode
print("Mode Members:", Mode.__members__)
print("mode Members:", mode.__members__)
Mode1 = Mode
assert Mode1 == Mode
#assert Mode == mode
#assert mode == Mode
55 changes: 55 additions & 0 deletions python-stdlib/enum/README.md
Comment thread
IhorNehrutsa marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Enum for MicroPython

Use enums to give a fixed set of values meaningful names, such as modes in
a state machine or settings on a sensor.

- Use `enum.py` for `Enum`, `IntEnum`, or `StrEnum`.
- Use `enum_mini.py` for a smaller alternative when you only need `Enum`.

## Getting started

Copy the module you want to the device alongside your program or into its
library directory. Import `Enum` from `enum` for the full version, or from
`enum_mini` for the mini version.

```python
from enum import Enum

class Color(Enum):
RED = 1
GREEN = 2

print(Color.RED.name) # RED
print(Color.RED.value) # 1
print(Color(2).name) # GREEN
```

Members are available as soon as the definition finishes in both versions.
The [full example](examples/enum_usage.py) also shows integer and string
members. The [mini example](examples/enum_mini_usage.py) shows class
declarations and creation from a dictionary. Run each example on MicroPython
with the corresponding module on its import path.

## Differences from CPython

- Both versions accept a member name or value in a call such as `Color("RED")`
or `Color(1)`. Plain `Enum` members can compare equal to their raw values.
- The full version uses `Color()["RED"]` for subscription and `len(Color())`
for the length on MicroPython. CPython uses `Color["RED"]` and `len(Color)`.
- The full version maps names to members in `__members__`. Mini maps members
to raw values. Iteration order can differ from declaration order.
- Member objects and class attributes have different protections. In the full
version, assigning to or deleting `Color.RED` on the class is possible on
MicroPython.
- Both modules install a class creation hook when imported. The examples
use one implementation per program.

## Running the package tests

With MicroPython and the `unittest` package available, run each test file
in a separate process from this directory and check its reported result.

```sh
micropython test_enum.py
micropython test_enum_mini.py
```
Loading
Loading