Skip to content

Commit d3fead8

Browse files
committed
enum: Add CPython and MicroPython demo.
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
1 parent ff70797 commit d3fead8

1 file changed

Lines changed: 76 additions & 0 deletions

File tree

‎python-stdlib/enum/CPy/CPy.py‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
from enum import Enum
2+
3+
is_micropython = False
4+
try:
5+
from machine import reset
6+
is_micropython = True
7+
except Exception:
8+
pass
9+
10+
11+
class Color(Enum):
12+
RED = 1
13+
GREEN = 2
14+
BLUE = 3
15+
16+
if is_micropython:
17+
Color() # Trigger initialization
18+
19+
print("\n--- Basic Lookups ---")
20+
print(Color.RED) # Color.RED
21+
print(Color.RED.name) # RED
22+
print(Color.RED.value) # 1
23+
print(repr(Color.RED)) # <Color.RED: 1>
24+
print(Color.__contains__(1)) # True
25+
print(Color.__contains__(11)) # False
26+
print(Color.__contains__(Color.RED)) # True
27+
print(Color.RED.value == 1) # True
28+
print(Color.RED.value + 10) # 11
29+
print(Color(1) is Color.RED) # True
30+
print()
31+
32+
if is_micropython:
33+
print(Color()) # <enum 'Color'>
34+
print(repr(Color())) # <enum 'Color'>
35+
print(len(Color())) # 3
36+
print(Color("RED")) # Color.RED
37+
print(Color("RED") is Color.RED) # True
38+
print(Color.RED == 1) # True (like IntEnum)
39+
print(list(Color())) # ['RED', 'GREEN', 'BLUE']
40+
print(list(Color.__members__)) # ['RED', 'GREEN', 'BLUE']
41+
else:
42+
print(Color) # <enum 'Color'>
43+
print(repr(Color)) # <enum 'Color'>
44+
print(len(Color)) # 3
45+
print(Color["RED"]) # Color.RED
46+
print(Color["RED"] is Color.RED) # True
47+
print(Color.RED == 1) # False
48+
print(list(Color)) # [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
49+
print(list(Color.__members__)) # ['RED', 'GREEN', 'BLUE']
50+
51+
print("\n--- Immutability Tests ---")
52+
try:
53+
Color.RED.value = 99
54+
0 / 0
55+
except AttributeError:
56+
print("Protected: Cannot reassign class attribute")
57+
58+
try:
59+
if is_micropython:
60+
Color().RED = 99
61+
else:
62+
Color.RED = 99
63+
0 / 0
64+
except AttributeError:
65+
print("Protected: Cannot reassign class attribute")
66+
67+
try:
68+
if is_micropython:
69+
del Color().RED
70+
else:
71+
del Color.RED
72+
0 / 0
73+
except AttributeError:
74+
print("Protected: Cannot delete class attribute")
75+
76+
assert Color.RED.value == 1

0 commit comments

Comments
 (0)