Repository navigation
python-stdlib/enum/enum.py: Add Enum class. - #980
IhorNehrutsa wants to merge 22 commits into
Conversation
|
Usage example:: Output is:: |
|
Thanks for the contribution, this looks pretty good! Did you implement this from scratch, or copy parts from CPython's implementation? I'm just wondering about licensing and copyright. Can you please add the test to the CI, in |
I just saw CPython Enum. It looks like incredible magic. :-) |
That doesn't really answer the question. Did you copy this implementation from CPython? Also, please make sure the CI all passes, there's currently a failure. |
|
| Did you implement this from scratch, or copy parts from CPython's implementation? No, I didn't use CPython implementation. It was inspired by @shariltumin Dot class from the Way to use dot notation to refer to states in a state machine #15694 |
e70dd06 to
6ab2ebe
Compare
|
Should I squash commits? |
| @@ -0,0 +1,91 @@ | |||
| # enum_test.py | |||
|
|
|||
| from enum import Enum, enum | |||
There was a problem hiding this comment.
I tried to run this test under CPython 3.12.2 but it doesn't work, for many reasons. And it should run under CPython so we can test that the implementation of MicroPython's enum matches the CPython enum.
For example, enum does not exist in the enum CPython module. Which version of CPython were you testing against?
There was a problem hiding this comment.
Version 1.4 matches CPython as I could manage.
| print("type(state('CW')):", type(state("CW"))) | ||
|
|
||
| print("state.key_from_value(20):", state.key_from_value(20)) | ||
| print("len(state):", len(state)) |
There was a problem hiding this comment.
CPython doesn't have __len__ on an enum.
There was a problem hiding this comment.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(dir(Color))
['GREEN', 'RED', '__class__', '__contains__', '__doc__', '__getitem__', '__init_subclass__', '__iter__',
'__len__',
'__members__', '__module__', '__name__', '__qualname__']
|
There is a quite comprehensive set of unit-tests for enum available in CPython: https://github.com/python/cpython/blob/main/Lib/test/test_enum.py |
|
I have successfully completed the task that requires the Enum class. |
We need to mip install `datetime`, tzif-parser requires it. https://github.com/micropython/micropython-lib/tree/master/python-stdlib/datetime ``` mpremote connect id:a5f14b8bfbff4289 mip install datetime ``` ## CPython features originally used in `tzif-parser` which were missing or different in MicroPython * `sysconfig` * `enum` - micropython/micropython-lib#269 - micropython/micropython-lib#980 * Regex _named_ Groups - https://docs.python.org/3/howto/regex.html#non-capturing-and-named-groups - https://docs.micropython.org/en/latest/library/re.html * `dataclasses` - https://docs.python.org/3/library/dataclasses.html - https://github.com/orgs/micropython/discussions/13741 - https://github.com/dhrosa/udataclasses - https://udataclasses.readthedocs.io/en/latest/ * `struct` (https://docs.python.org/3/library/struct.html#format-characters) features not available in MicroPython (https://docs.micropython.org/en/latest/library/struct.html#module-struct): - `c` for `char`, which in CPython would be decoded as an instance of [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes-objects) with length 1. Instead of `c`, we could use `s`, but we know this is a single byte, so `b` does just fine, giving us a Python integer. The integral repeat count prefix `1` is superfluous. * [MicroPython `bytearray`](https://www.fredscave.com/43-micropython-data-types-bytearray.html) type doesn't have the [`clear()`](https://docs.python.org/3/library/stdtypes.html#sequence.clear) method [mutable sequences](https://docs.python.org/3/library/stdtypes.html#typesseq-mutable) in CPython do * `Typing.IO` - python/typing#829
We need to mip install `datetime`, tzif-parser requires it. https://github.com/micropython/micropython-lib/tree/master/python-stdlib/datetime ``` mpremote connect id:a5f14b8bfbff4289 mip install datetime ``` ## CPython features originally used in `tzif-parser` which were missing or different in MicroPython * `sysconfig` * `enum` - micropython/micropython-lib#269 - micropython/micropython-lib#980 * Regex _named_ Groups - https://docs.python.org/3/howto/regex.html#non-capturing-and-named-groups - https://docs.micropython.org/en/latest/library/re.html * `dataclasses` - https://docs.python.org/3/library/dataclasses.html - https://github.com/orgs/micropython/discussions/13741 - https://github.com/dhrosa/udataclasses - https://udataclasses.readthedocs.io/en/latest/ * `struct` (https://docs.python.org/3/library/struct.html#format-characters) features not available in MicroPython (https://docs.micropython.org/en/latest/library/struct.html#module-struct): - `c` for `char`, which in CPython would be decoded as an instance of [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes-objects) with length 1. Instead of `c`, we could use `s`, but we know this is a single byte, so `b` does just fine, giving us a Python integer. The integral repeat count prefix `1` is superfluous. * [MicroPython `bytearray`](https://www.fredscave.com/43-micropython-data-types-bytearray.html) type doesn't have the [`clear()`](https://docs.python.org/3/library/stdtypes.html#sequence.clear) method [mutable sequences](https://docs.python.org/3/library/stdtypes.html#typesseq-mutable) in CPython do * `Typing.IO` - python/typing#829
|
@dpgeorge Need some help on this PR ? Were could I start ? Dominique |
That would be much appreciated. |
|
@IhorNehrutsa, may I ask why you closed the documentation PR? |
This has been going on for so long that I forgot. :( |
|
I'm a bit skeptical about the last @IhorNehrutsa action. On the meanwhile, @IhorNehrutsa pushed an AI rework of the code and "here is it for you to test". Nevertheless, I do not want to be retrograde but being the "human behind the IA for checking the IA work" is not really what I was expecting. |
|
@mchobby, @IhorNehrutsa , I’m also genuinely confused by the pattern of behavior around these PRs: starting work, abandoning it, then suddenly re‑engaging with AI‑generated updates, along with the closing, and re‑opening of related PRs. It makes it difficult to understand the actual intent, the direction of the contribution, or whether you are committed to following through. There is clear interest in having an At the same time, it’s important that MicroPython stays close to CPython where feasible, while still respecting MicroPython’s own design principles and constraints. Achieving that balance requires careful design and discussion, not a surface‑level or (mostly) AI‑generated port. I have not had the time to look at the most recent tests and code - but I do plan to do that in the next few days. |
|
Okay. No one minds if I copy the previous version of enum.py to enum_0.py, the latest to enum_1.py, then we'll choose the best implementation options for enum.py from them. |
Can someone write a MicroPython version of the CPython tests https://github.com/python/cpython/blob/main/Lib/test/test_enum.py ? |
projectgus
left a comment
There was a problem hiding this comment.
Thanks @IhorNehrutsa and @MrCodeGameandAnime, and I appreciate your continued patience.
I've done a quick pass over the PR and left some review comments with pointers about what we'd like to see for "upstream acceptance".
This isn't a complete review, and a lot of the inline comments apply in multiple places.
Up to you to decide if you want to keep updating this PR together or proceed in some other way, but hopefully this has given you some additional direction.
If replying to this review, please don't paste a large LLM-generated response. I typed all of this out myself, and appreciate the same care.🙏
There was a problem hiding this comment.
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.
@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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Is it a reasonable goal that after merging this it should be possible for someone to mip install enum or mip install enum-mini and get the relevant module available via import enum in either case?
There was a problem hiding this comment.
@IhorNehrutsa, are you ok with enum and enum-mini as alternative installs that both provide import enum? We can keep the full package where it is and give mini its own python-stdlib/enum-mini/ directory, with its implementation packaged as enum.py. We’d document that users should choose one variant per install location. Am I following your intent correctly?
There was a problem hiding this comment.
I suggest not spending time discussing enum_mini right now, but rather deferring it to the final stage.
There was a problem hiding this comment.
Understood. We'll focus on enum for now and revisit enum-mini packaging at the final stage.
| @@ -0,0 +1,152 @@ | |||
| # enum_usage.py | |||
| # version="1.5.1" | |||
There was a problem hiding this comment.
No need to track versions in the source files, they're tracked in the manifest and by git.
There was a problem hiding this comment.
1a6da1e45d0f4143cbba750cb7e5023b6402d22a removed the version headers from the usage examples. 92eda8bdb5a64bc036cd51091d59c042231dcec9 removes the remaining headers from the active enum modules and tests (enum.py, enum_mini.py, test_enum.py, and test_enum_mini.py). The package version stays in manifest.py.
| 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. |
There was a problem hiding this comment.
The purpose of this README should be to guide MicroPython users who want to use enum classes in their own code, so they can understand what is possible and how to proceed.
Some of the current contents of this file don't make sense to me, and I'm unsure if that's because I'm not strong enough on Python internals or because they are LLM word salad (possibly both). Either way it's not suitable for a package README.
Suggest that:
- The
README.mdshould be user-facing documentation, including: basics of enum use, how/why someone would choose betweenenumandenum_miniimplementations, differences to CPython enum. Should not require expert level Python knowledge to understand. - Important implementation details can be moved to source code comments (and/or module level source comments).
- Unimportant details should be removed.
There was a problem hiding this comment.
Simplified the README in 1a6da1e45d0f4143cbba750cb7e5023b6402d22a. It now shows how to get started, when to use full or mini, and where behavior differs from CPython.
| self.assertEqual(json.loads(json.dumps([Mode.FAST])), ["fast"]) | ||
|
|
||
| def test_full_then_mini_and_fresh_full(self): | ||
| import enum_mini |
There was a problem hiding this comment.
I don't understand why this test imports enum_mini, when enum_mini has its own tests.
(It would be neat to restructure this so there were some tests which pass with both enum and enum_mini, and then a second set of tests which only pass when run against enum).
There was a problem hiding this comment.
The active cross-import test is in the mini suite and checks that the two modules can coexist. I’d keep it separate from the shared compatibility tests and cases specific to the full enum in the full suite. This ties into the CPython-derived test discussion. Does that split work for you?
| (type(v), cls), | ||
| { | ||
| "name": n, | ||
| "value": v, |
There was a problem hiding this comment.
There are often ways to avoid this kind of minification and still save space.
For example, because there is already a string literal "value" then this module already has a QSTR for value. So you can call this variable value instead of v at no cost.
(This advice applies elsewhere in this PR, too.)
There was a problem hiding this comment.
Used descriptive names such as value in the full and mini member construction helpers in 88dc53df1528d0fcc4a7df055491efe4745fbaed.
| # _i() -> items: Classmethod to initialize and return the __members__ dict. | ||
| # a(s, k, v) -> __setattr__: Inner setter guard raising AttributeError on enum items. | ||
| # | ||
| # Helper Arguments & Local Variables: |
There was a problem hiding this comment.
This is an interesting approach but I worry it will be hard to maintain, probably better to comment inline where names are used. (It's also not strictly necessary to use single-letter variables, see other comment.)
There was a problem hiding this comment.
Removed the abbreviation glossaries from both enum modules and put the relevant explanations next to the code in 88dc53df1528d0fcc4a7df055491efe4745fbaed.
There was a problem hiding this comment.
Let’s rank the properties based on priority (here is my rankings):
- code size in flash memory (enum_1_5_1.py is smollest now)
- code size in RAM
- end-user convenience (I prefer 'x for x in Color' rathet 'x for x in Color()' )
- look like CPython, don't work like CPython
- ability to use libraries from "big" Python with minimal changes
- compatibility with CPython (for me, the execution 'self.assertIs(type(Color.RED), Color)' is not important)
| cls.__getitem__ = getitem | ||
| cls._str_getitem = getitem | ||
| cls.__members__ = members | ||
| cls._str_finalized = _STR_FINALIZED |
There was a problem hiding this comment.
Why does this need to be set to a sentinel object rather than being a boolean flag?
(Not asking to be changed necessarily, but it'd be good to add an explanation in a comment.)
There was a problem hiding this comment.
In 1.5.2, the active implementation checks for __members__ in the class’s __dict__ to decide whether to build the member mapping. The sentinel remains only in the old enum_1_5_0_DD.py snapshot.
There was a problem hiding this comment.
This seems like more development code rather than something we'd merge. If possible, please convert to unit tests instead.
There was a problem hiding this comment.
Moved the string lookup and empty enum checks into test_enum.py and removed enum_check.py in 833c65cb0acc701a5ccc057e453c3fd398da94ac. The existing tests already cover the other active checks.
There was a problem hiding this comment.
The convention elsewhere in micropython-lib is to have an examples directory and place individual examples there.
(For example see python-stdlib/unittest/examples and python-stdlib/logging/examples.)
There was a problem hiding this comment.
Moved both usage scripts into examples/ and trimmed them to short demos in 1a6da1e45d0f4143cbba750cb7e5023b6402d22a
|
@IhorNehrutsa, I'm willing to work on @projectgus's feedback and open a PR on your fork if it will be handled collaboratively. Please confirm so it's not overridden, and we can get this done for the community. |
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
The builder hook allows using an Enum without lazy initialization. Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: MrCodeGameandAnime <69434842+MrCodeGameandAnime@users.noreply.github.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com> Co-Authored-By: MrCodeGameandAnime <69434842+MrCodeGameandAnime@users.noreply.github.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com> Co-Authored-By: MrCodeGameandAnime <69434842+MrCodeGameandAnime@users.noreply.github.com>
|
I’m losing optimism regarding this PR. I believe we should reduce the scope of the requirements and make some compromises concerning strict compliance with CPython. |
|
@IhorNehrutsa I’ve opened a branch |
|
@MrCodeGameandAnime Ok, let's try |
|
@IhorNehrutsa, both examples and the two tests moved from |
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
The package tests already cover member access, lookup errors, iteration, mutation checks, functional creation, dump round trips, and typed `StrEnum` behavior. Move the remaining checks for plain enums with string values and empty enum length into `test_enum.py`, then remove the development script. enum: Save enum_check.py. Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: MrCodeGameandAnime <MrCodeGameAndAnime@gmail.com>
Signed-off-by: MrCodeGameandAnime <MrCodeGameAndAnime@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com> Co-Authored-By: MrCodeGameandAnime <69434842+MrCodeGameandAnime@users.noreply.github.com>
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com> Co-Authored-By: Andrew Leech <andrew.leech@planetinnovation.com.au>
Docs in:
docs/library/enum.rst: Add Enum class. #16842
Usage example:
EDITED:
Inspired by @shariltumin Dot class from the Way to use dot notation to refer to states in a state machine #15694
and @njourdane enum() func from the Request for package: micropython-enum #269
EDITED October 2026:
See
README.md, `CPy/CPy.py'@MrCodeGameandAnime Thank you very much. I catch idea of immediate member availability after class definition from the DD’s enum implementation.
Standard Behavior (Compatible)
Color.RED,.name,.valuefor item in ColorIntEnumandStrEnumtypes with strict value checkingEnum('Name', {'KEY': value, ...})Non-Standard Behavior
Key differences from CPython:
Color("RED")works for both name and value lookup (CPython standard call only supports value lookup).Color.RED == 1isTrue(only true forIntEnumin CPython)..dump()does not exist in stdlibEnum.Color.RED()returns the value (not supported in CPython).__len__:len(Color)works; CPython enums are not containers.dump()for eval-based reconstruction is MicroPython-specific.Comparing the implementations
enum.pyenum_mini.pyEnum,IntEnum,StrEnumEnum,IntEnum,StrEnumEnumColor["RED"]Color("RED")orColor["RED"]Color("RED")Color(1)Color(1)Color(1)for item in Colorfor item in Colorfor item in Color__members____members__mappingstartfor generated integer valuesIntEnum/StrEnumIntEnum/StrEnumlen(Color)len(Color).dump()Enummember equals its raw valueColor.RED()Comparison: enum.py: Check a size 1.5.0
esp32: +2672 +0.147% ESP32_GENERIC[incl +2672(data)]
mimxrt: +2640 +0.669% TEENSY40
rp2: +2604 +0.269% RPI_PICO_W
samd: +2648 +0.950% ADAFRUIT_ITSYBITSY_M4_EXPRESS
Comparison: enum.py: Check a size 1.5.0 DD
esp32: +4368 +0.241% ESP32_GENERIC[incl +4368(data)]
mimxrt: +4272 +1.083% TEENSY40
rp2: +4236 +0.437% RPI_PICO_W
samd: +4272 +1.532% ADAFRUIT_ITSYBITSY_M4_EXPRESS
Comparison: enum.py: Check a size 1.5.1
esp32: +2320 +0.128% ESP32_GENERIC[incl +2320(data)]
mimxrt: +2304 +0.584% TEENSY40
rp2: +2268 +0.234% RPI_PICO_W
samd: +2304 +0.826% ADAFRUIT_ITSYBITSY_M4_EXPRESS
Comparison: enum.py: Check a size 1.5.2
esp32: +3136 +0.173% ESP32_GENERIC[incl +3136(data)]
mimxrt: +3112 +0.789% TEENSY40
rp2: +3092 +0.319% RPI_PICO_W
samd: +3116 +1.117% ADAFRUIT_ITSYBITSY_M4_EXPRESS
Comparison: enum.py: Check a size 1.5.2 DD
esp32: +3152 +0.174% ESP32_GENERIC[incl +3152(data)]
mimxrt: +3112 +0.789% TEENSY40
rp2: +3092 +0.319% RPI_PICO_W
samd: +3124 +1.120% ADAFRUIT_ITSYBITSY_M4_EXPRESS