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
Open
IhorNehrutsa
wants to merge
22
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.
Open
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 8707ea2
python-stdlib\enum: Bump to version="1.4.0".
IhorNehrutsa 6328477
python-stdlib\enum: Add mini Enum implementation.
IhorNehrutsa 8aa455a
enum: Add CPython and MicroPython demo.
IhorNehrutsa 868bc0b
python-stdlib\enum: Bump to version="1.5.0".
IhorNehrutsa 2ba0ffb
python-stdlib/enum: Improve StrEnum behavior and tests
MrCodeGameandAnime 85a6128
python-stdlib\enum: Bump to version="1.5.1".
IhorNehrutsa 30d1f97
python-stdlib\enum_mini: Bump to version="1.5.1".
IhorNehrutsa 33d829b
python-stdlib\enum: Bump to version="1.5.2".
IhorNehrutsa 4a2e389
Add prev enums version.
IhorNehrutsa 4d7491c
enum: Move versions to save _wip.
IhorNehrutsa dd00ae7
enum: Save enum_1_5_2.py.
IhorNehrutsa 54defb8
enum: Move usage examples.
IhorNehrutsa 523dc90
python-stdlib/enum: Remove redundant source version comments.
MrCodeGameandAnime 5746add
python-stdlib/enum: Move development checks into unit tests.
IhorNehrutsa e040e4c
python-stdlib/enum: Check declared Enum member identity.
MrCodeGameandAnime b32e2d4
python-stdlib/enum: Isolate StrEnum value lookup check.
MrCodeGameandAnime e2c2c06
enum: Save enum_check.py.
IhorNehrutsa b9640d2
enum: Remove redundant source version comments.
IhorNehrutsa 0e11d6e
enum: Fix ruff.
IhorNehrutsa 35564ce
enum: Clarify README.
IhorNehrutsa b3378d0
enum: Add test_enum.py from #1061.
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,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 |
|
IhorNehrutsa marked this conversation as resolved.
Resolved
|
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,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 | ||
| ``` |
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.pyinto the suite before removing the script. Does that work for you?There was a problem hiding this comment.
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: