Repository navigation
python-stdlib/enum/enum.py: Add Enum class. #980
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
IhorNehrutsa
wants to merge
10
commits into
micropython:master
Choose a base branch
from
IhorNehrutsa:enum
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
9458691
python-stdlib\enum\enum.py: Add Enum class.
IhorNehrutsa 29b8085
python-stdlib\enum: Bump to version="1.4.0".
IhorNehrutsa ff70797
python-stdlib\enum: Add mini Enum implementation.
IhorNehrutsa d3fead8
enum: Add CPython and MicroPython demo.
IhorNehrutsa c3b5aae
python-stdlib\enum: Bump to version="1.5.0".
IhorNehrutsa f757a19
python-stdlib/enum: Improve StrEnum behavior and tests
MrCodeGameandAnime 3fac58b
python-stdlib\enum: Bump to version="1.5.1".
IhorNehrutsa 1310b91
python-stdlib\enum_mini: Bump to version="1.5.1".
IhorNehrutsa 277dab2
Merge branch 'enum' into enum-review
IhorNehrutsa 7ebb140
enum: Merge PR #1 from MrCodeGameandAnime/enum-review.
IhorNehrutsa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| import sys | ||
| # CPy.py | ||
| # version="1.5.1" | ||
|
|
||
| is_micropython = False | ||
| try: | ||
| from machine import reset | ||
| is_micropython = True | ||
| except ImportError: | ||
| pass | ||
|
|
||
| from enum import Enum, StrEnum, IntEnum | ||
|
|
||
|
|
||
| def section(s): | ||
| print(s) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 1. Basic class-based Enum | ||
| # --------------------------------------------------------------------------- | ||
| section("Basic Enum (class syntax)") | ||
|
|
||
| class Color(Enum): | ||
| RED = 1 | ||
| GREEN = 2 | ||
| BLUE = 3 | ||
|
|
||
|
|
||
| print("\n--- Basic Lookups --- # 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'> | ||
| print(len(Color)) # 3 | ||
| print(Color["RED"]) # Color.RED | ||
| print(Color["RED"] is Color.RED) # True | ||
| print(Color.RED == 1) # False # True | ||
| # --------------------------------------------------------------------------- | ||
| # 2. Immutability | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| print("\n--- Immutability Tests ---") | ||
| try: | ||
| Color.RED.value = 99 | ||
| 0 / 0 | ||
| except AttributeError: | ||
| print("Protected: Cannot reassign class attribute") | ||
|
|
||
| try: | ||
| Color.RED = 99 | ||
| 0 / 0 | ||
| except AttributeError: | ||
| print("Protected: Cannot reassign class attribute") | ||
|
|
||
| try: | ||
| del Color.RED | ||
| 0 / 0 | ||
| except AttributeError: | ||
| print("Protected: Cannot delete class attribute") | ||
|
|
||
| try: | ||
| Color.RED.custom = 5 | ||
| print("NOT Protected: Set attribute on enum item") # NOT Protected: Set attribute on enum item | ||
| except AttributeError: | ||
| print("Protected: Cannot set attribute on enum item") # Protected: Cannot set attribute on enum item | ||
|
|
||
| assert Color.RED.value == 1 | ||
| # --------------------------------------------------------------------------- | ||
| # 3. Functional API | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| 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} | ||
| # Functional generic enums retain their container API on MicroPython. | ||
| coord_members = DynCoord() if sys.implementation.name == "micropython" else DynCoord | ||
| print(list(coord_members)) # Order may vary on MicroPython. | ||
| print(DynCoord.X.value) # 10 | ||
|
|
||
| except Exception as e: | ||
| print(f"Functional dict API error: {e}") | ||
|
|
||
| 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'>} # {'a': 'a', 'c': 'c', 'b': 'b'} | ||
| print(list(DynStr)) # [<DynStr.A: 'a'>, <DynStr.B: 'b'>, <DynStr.C: 'c'>] # ['a', 'c', '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}") | ||
|
|
||
| try: | ||
| class Colors(Color): | ||
| YELLOW = 'yellow' | ||
| except TypeError as e: | ||
| print(f"TypeError: {e}") | ||
|
|
||
| if hasattr(Color, "dump"): | ||
| print("\n--- Dump & Restore (if available) ---") | ||
| d_str = Color.dump() | ||
| print("Dump:", d_str) | ||
| Restored = eval(d_str) # Dump: Enum('Color', {'BLUE': 3, 'RED': 1, 'GREEN': 2}) | ||
| print(Restored) # <enum 'Color'> | ||
| print(type(Restored)) # <class 'Color'> | ||
| print(Restored.__members__) # {<Color.RED: 1>: 1, <Color.GREEN: 2>: 2, <Color.BLUE: 3>: 3} | ||
| print(list(Restored())) # [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>] | ||
| print("Restored equality:", Restored == Color) # True | ||
| print("Restored equality:", Restored.RED.value == Color.RED.value) # True | ||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 4. StrEnum class vs instance | ||
| # --------------------------------------------------------------------------- | ||
| print() | ||
|
|
||
| class Mode(StrEnum): | ||
| FAST = "fast" | ||
| SLOW = "slow" | ||
|
|
||
| class Mode2(StrEnum): | ||
| FAST2 = "fast2" | ||
| SLOW2 = "slow2" | ||
|
|
||
| print("--- Class ---") | ||
| 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 isinstance(Mode.FAST, str) | ||
|
|
||
| if is_micropython: | ||
| assert isinstance(Mode, Enum) | ||
| assert isinstance(Mode, (StrEnum, type(StrEnum))) | ||
| else: | ||
| pass | ||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # 5. Instance pattern (MicroPython-friendly) | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| if is_micropython: | ||
| assert issubclass(type(Mode), Enum) | ||
| assert issubclass(type(Mode), (StrEnum, type(StrEnum))) | ||
| else: | ||
| assert issubclass(Mode, Enum) | ||
| assert issubclass(Mode, StrEnum) | ||
|
|
||
| assert isinstance(Mode.FAST, str) | ||
| if is_micropython: | ||
| assert isinstance(Mode.FAST, type(Mode)) | ||
| else: | ||
| assert isinstance(Mode.FAST, Mode) | ||
|
|
||
| if is_micropython: | ||
| print() | ||
| print("--- Instance ---") | ||
| 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 isinstance(mode.FAST, str) | ||
|
|
||
| assert issubclass(type(mode), Enum) | ||
| assert issubclass(type(mode), (StrEnum, type(StrEnum))) | ||
|
|
||
| assert isinstance(mode, Enum) | ||
| assert isinstance(mode, (StrEnum, type(StrEnum))) | ||
|
|
||
| assert isinstance(mode.FAST, str) | ||
| assert isinstance(mode.FAST, type(mode)) | ||
|
|
||
| assert type(mode) is type(Mode) | ||
| assert mode == Mode |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,178 @@ | ||
| # Lightweight Enum | ||
|
|
||
| This package provides two lightweight enumeration implementations for MicroPython: | ||
|
|
||
| * `enum.py` provides `Enum`, `IntEnum`, and `StrEnum`, multiple forms of the | ||
| functional API, lookup by name or value, iteration, and `.dump()`. | ||
| * `enum_mini.py` provides a smaller `Enum` implementation with class-based | ||
| members, dictionary-based functional creation, lookup by name or value, and | ||
| iteration. | ||
|
|
||
| Both implementations avoid metaclasses and share one process-wide | ||
| `__build_class__` dispatcher. `Enum` and `IntEnum`, and the mini implementation, | ||
| keep their existing initialized-container architecture. Their members inherit | ||
| raw value types rather than the declared enum class. `StrEnum` instead keeps | ||
| the real declared class and constructs genuine string instances of that class. | ||
|
|
||
| **Important:** The dispatcher registers both modules and retains families from | ||
| fresh imports, so old aliases continue to work. It chains an existing cooperative | ||
| class-building hook and leaves later cooperative hooks installed. Hooks that do | ||
| not delegate, or manually changing the shared builtin state, are not supported. | ||
| Ordinary classes unrelated to a registered enum family are passed through. | ||
|
|
||
| ## Quick start: `enum.py` | ||
|
|
||
| ```python | ||
| from enum import Enum, IntEnum, StrEnum | ||
|
|
||
| class Color(Enum): | ||
| RED = 1 | ||
| GREEN = 2 | ||
| BLUE = 3 | ||
|
|
||
| print(Color.RED) # Color.RED | ||
| print(Color.RED.name) # RED | ||
| print(Color.RED.value) # 1 | ||
|
|
||
| print(Color(2)) # Color.GREEN: lookup by value | ||
| print(Color("RED")) # Color.RED: lookup by name | ||
| print(Color["RED"]) # Color.RED: lookup by name | ||
| print(list(Color)) # Enum members | ||
| print(len(Color)) # 3 | ||
| print(Color.dump()) # Reconstructable expression | ||
| ``` | ||
|
|
||
| `enum.py` also provides constrained value types: | ||
|
|
||
| ```python | ||
| class Priority(IntEnum): | ||
| LOW = 1 | ||
| HIGH = 2 | ||
|
|
||
| class Status(StrEnum): | ||
| PENDING = "pending" | ||
| DONE = "done" | ||
|
|
||
| print(Priority.HIGH > 1) # True | ||
| print(isinstance(Priority.LOW, int)) # True | ||
| print(Status.PENDING.name.upper()) # PENDING | ||
| print(isinstance(Status.DONE, str)) # True | ||
| ``` | ||
|
|
||
| `IntEnum` values must be integers and `StrEnum` values must be strings. | ||
| Invalid member values raise `TypeError`. | ||
|
|
||
| ## Typed `StrEnum` on stock MicroPython | ||
|
|
||
| ```python | ||
| class Mode(StrEnum): | ||
| FAST = "fast" | ||
| SLOW = "slow" | ||
|
|
||
| def describe(self): | ||
| return self.name + ":" + self.value | ||
|
|
||
| print(type(Mode.FAST) is Mode) # True | ||
| print(isinstance(Mode.FAST, Mode)) # True | ||
| print(isinstance(Mode.FAST, StrEnum)) # True | ||
| print(isinstance(Mode.FAST, Enum)) # True | ||
| print(isinstance(Mode.FAST, str)) # True | ||
| print(Mode("fast") is Mode.FAST) # True | ||
| print(Mode("FAST") is Mode.FAST) # True | ||
| print(Mode(Mode.FAST) is Mode.FAST) # True | ||
| print(Mode.FAST.describe()) # FAST:fast | ||
| print(Mode.FAST[0], Mode.FAST[:2]) # f fa | ||
| print([member.name for member in Mode]) # order is not guaranteed | ||
|
|
||
| Dynamic = StrEnum("Dynamic", "FAST SLOW") | ||
| print(Dynamic.FAST.value) # fast | ||
| ``` | ||
|
|
||
| Members are finalized immediately after the class body. Construction through | ||
| the declared string subclass is adapted from [Dungeon Drifters' StrEnum by | ||
| MrCodeGameAndAnime](https://github.com/MrCodeGameandAnime/Dungeon-Drifters/blob/2fa5f9d0ca806e5e7dbd41f3ac9073465d26762b/root/portability/micropython/enum.py), | ||
| building on this package's existing class-finalization hook. | ||
|
|
||
| The direct functional API is retained: dictionaries, strings, lists/tuples of | ||
| names or pairs, and other name iterables supported by 1.5.0. A string of names | ||
| generates lowercase values; lists and other name iterables retain name spelling. | ||
| `dump()` still emits `StrEnum(...)`. There is no separate factory API. | ||
|
|
||
| String operations, equality and hashing use native string behavior. String-valued | ||
| inputs remain members even if callable, and their content is normalized to a | ||
| plain string before duplicate detection. Inputs overriding string slicing are | ||
| rejected, because stock MicroPython cannot safely bypass that override; members | ||
| produced by this package retain safe string slicing and can be reused as values. | ||
| Private names are ignored and public declared methods are preserved. Duplicate values, | ||
| non-string declarations, custom constructors, mixins and extension of finalized | ||
| StrEnum classes are rejected. Member metadata is read-only through normal | ||
| attribute assignment/deletion. | ||
|
|
||
| ### Stock-runtime limits | ||
|
|
||
| This is a supported subset, not full CPython enum parity: | ||
|
|
||
| - `list(Mode)` and `for member in Mode` use stock MicroPython's class sequence | ||
| fallback. Member indexing and slicing still operate on their string content. | ||
| This class-iteration fallback is not a CPython feature. | ||
| - `len(Mode)` and `Mode["FAST"]` are unavailable for the real-class typed profile. | ||
| Use `len(Mode._i())` and `Mode("FAST")` when those operations are needed. | ||
| - Class member replacement/deletion is not intercepted. The exposed member-to-value | ||
| metadata dictionary is mutable. Do not modify class members or this metadata. | ||
| - Classes keep ordinary class representation. Members keep native string `str` | ||
| and `repr`, rather than enum-style representation, for scalar/list JSON encoding. | ||
| - Stock MicroPython has limitations with Python string-subclass dictionary keys, | ||
| including JSON dictionary keys. Use plain `.value` strings when creating keys. | ||
| This package does not change dictionary or JSON runtime behavior. | ||
| - `Mode()` returning the class, name lookup by call and callable members returning | ||
| values remain 1.5.0 extensions. Member order follows the runtime's declaration | ||
| dictionary traversal and is not guaranteed. | ||
|
|
||
| Generic `Enum`/`IntEnum` and mini containers keep their existing operations and | ||
| representations. They are not changed to match the typed StrEnum restrictions. | ||
|
|
||
| ## Comparing the implementations | ||
|
|
||
| | Feature | CPython | `Enum` / `IntEnum` | Typed `StrEnum` (stock MicroPython) | `enum_mini.py` | | ||
| | --- | --- | --- | --- | --- | | ||
| | Declared-class member identity | Yes | No | Yes | No | | ||
| | Name lookup | `Color["RED"]` | `Color("RED")` or `Color["RED"]` | `Mode("FAST")` | `Color("RED")` | | ||
| | Value lookup | `Color(1)` | `Color(1)` | `Mode("fast")` | `Color(1)` | | ||
| | Iteration | `for item in Color` | `for item in Color` | `for item in Mode` | `for item in Color` | | ||
| | Length | `len(Color)` | `len(Color)` | `len(Mode._i())` | `len(Color)` | | ||
| | `__members__` mapping | Name to member | Member to raw value | Member to raw value | Member to raw value | | ||
| | Functional creation | `Enum(...)` | `Enum(...)` / `IntEnum(...)` | `StrEnum(...)` | `Enum(name, dictionary)` | | ||
| | `.dump()` | No | Yes | Yes | No | | ||
| | Member repr | Enum-style | Enum-style | Native string | Enum-style | | ||
| | Plain Enum equals raw value | No | Yes | String equality | Yes | | ||
| | Calling a member | Not supported | Returns value | Returns value | Returns value | | ||
|
|
||
| ## Code | ||
|
|
||
| The runnable example in [`CPy/CPy.py`](CPy/CPy.py) compares basic member | ||
| access, lookup, iteration, equality, and immutability on CPython and | ||
| MicroPython. | ||
| Run it with `python CPy.py`. | ||
|
|
||
| ## Limitations | ||
|
|
||
| The package intentionally provides a smaller API than standard-library `enum`. | ||
| Equal raw values can compare equal across different enum classes. Generic Enum, | ||
| IntEnum and mini members retain their value-type/container architecture; only | ||
| the typed StrEnum profile provides declared-class member identity. The stock | ||
| limitations above are intentional boundaries, not prerequisites for a modified | ||
| interpreter. | ||
|
|
||
| ## Tests | ||
|
|
||
| With a stock MicroPython 1.29.0 executable and the `unittest` package available, | ||
| run both existing files from this directory in separate processes: | ||
|
|
||
| ```sh | ||
| micropython test_enum.py | ||
| micropython test_enum_mini.py | ||
| ``` | ||
|
|
||
| The files cover full-first and mini-first imports, fresh full imports preserving | ||
| old aliases, cooperative hooks, and the typed-member profile. Check each runner's | ||
| reported result: some MicroPython unittest versions exit zero even on failure. |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.