Skip to content

python-stdlib/enum/enum.py: Add Enum class. - #980

Open
IhorNehrutsa wants to merge 22 commits into
micropython:masterfrom
IhorNehrutsa:enum
Open

IhorNehrutsa wants to merge 22 commits into
micropython:masterfrom
IhorNehrutsa:enum

Conversation

@IhorNehrutsa

@IhorNehrutsa IhorNehrutsa commented Mar 5, 2025 •

Copy link
Copy Markdown

Docs in:
docs/library/enum.rst: Add Enum class. #16842
Usage example:

from enum import Enum

class Color(Enum):
    RED = 'red'
    GREEN = 'green'

print(Color.RED)          # Color.RED
print(Color.RED.name)     # RED
print(Color.RED.value)    # red
print(Color.__members__)  # {<Color.GREEN: 'green'>: 'green', <Color.RED: 'red'>: 'red'}
print(list(Color))        # [<Color.RED: 'red'>, <Color.GREEN: 'green'>]
print(Color["RED"])       # Color.RED
print(Color("red"))       # Color.RED

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)

  • ✅ Member access: Color.RED, .name, .value
  • ✅ Member iteration: for item in Color
  • ✅ IntEnum and StrEnum types with strict value checking
  • ✅ Immutability: members cannot be modified after creation
  • ✅ Functional API: Enum('Name', {'KEY': value, ...})

Non-Standard Behavior

Key differences from CPython:

  • Name-based lookup via call: Color("RED") works for both name and value lookup (CPython standard call only supports value lookup).
  • Value equality: Color.RED == 1 is True (only true for IntEnum in CPython).
  • Custom methods: .dump() does not exist in stdlib Enum.
  • Callable members: Color.RED() returns the value (not supported in CPython).
  • Instance __len__: len(Color) works; CPython enums are not containers.
  • Serialization: dump() for eval-based reconstruction is MicroPython-specific.

Comparing the implementations

Feature CPython enum.py enum_mini.py
Enum types Enum, IntEnum, StrEnum Enum, IntEnum, StrEnum Enum
Lookup by name Color["RED"] Color("RED") or Color["RED"] Color("RED")
Lookup by value Color(1) Color(1) Color(1)
Iteration for item in Color for item in Color for item in Color
Iteration in __members__ Yes Yes Yes
__members__ mapping Name to member Member to raw value Member to raw value
Functional API Dict, names string, list/tuple, or iterable Dict, names string, list/tuple, or iterable Dictionary only
start for generated integer values Yes Yes No
Strict integer/string member types IntEnum / StrEnum IntEnum / StrEnum Not provided
Length Not provided len(Color) len(Color)
.dump() No Yes No
Plain Enum member equals its raw value No Yes Yes
Member is an instance of its enum class Yes No No
Calling a member, e.g. Color.RED() Not supported Returns its raw value Returns its raw value

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

@IhorNehrutsa IhorNehrutsa changed the title Add Enum class. python-stdlib/enum/enum.py: Add Enum class. Mar 5, 2025
@IhorNehrutsa

IhorNehrutsa commented Mar 5, 2025 •

Copy link
Copy Markdown
Author

Usage example::

from enum import Enum

class State(Enum):
  Stop = 10
  Run = 20
  Ready = 30

state = State()
print("state:", State)

current_state = state.Stop
print("current_state:", current_state, current_state.name)
if current_state == state.Stop:
  print(" Stop state")
if current_state != state.Ready:
  print(" Not a Ready state")
  print(" Run!")
  current_state = state.Run
print("current_state:", current_state, current_state.name)
# some process
i = -1
while current_state != state.Ready:
  i += 1
  try:
      if state(i) == state.Ready:
          current_state = state.Ready
  except:
      pass
  print(".", end="")
print()
print("current_state:", current_state, state(current_state))
print("Done!")

Output is::

state: <enum 'State'>
current_state: State.Stop Stop
 Stop state
 Not a Ready state
 Run!
current_state: State.Run Run
...............................
current_state: State.Ready State.Ready
Done!

@dpgeorge

Copy link
Copy Markdown
Member

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 tools/ci.sh inside the function ci_package_tests_run.

@IhorNehrutsa

Copy link
Copy Markdown
Author

Did you implement this from scratch, or copy parts from CPython's implementation?

I just saw CPython Enum. It looks like incredible magic. :-)

@dpgeorge

Copy link
Copy Markdown
Member

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.

@IhorNehrutsa

Copy link
Copy Markdown
Author

| 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
and @njourdane enum() func from the Request for package: micropython-enum #269

Comment thread python-stdlib/enum/manifest.py Resolved
@IhorNehrutsa
IhorNehrutsa force-pushed the enum branch 2 times, most recently from e70dd06 to 6ab2ebe Compare March 12, 2025 07:34
@IhorNehrutsa

Copy link
Copy Markdown
Author

Should I squash commits?

Comment thread python-stdlib/enum/test_enum.py Outdated
@@ -0,0 +1,91 @@
# enum_test.py

from enum import Enum, enum

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

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.

Version 1.4 matches CPython as I could manage.

Comment thread python-stdlib/enum/test_enum.py Resolved
Comment thread python-stdlib/enum/test_enum.py Resolved
Comment thread python-stdlib/enum/test_enum.py Resolved
Comment thread python-stdlib/enum/test_enum.py Resolved
Comment thread python-stdlib/enum/test_enum.py Resolved
Comment thread python-stdlib/enum/test_enum.py Resolved
Comment thread python-stdlib/enum/test_enum.py Outdated
print("type(state('CW')):", type(state("CW")))

print("state.key_from_value(20):", state.key_from_value(20))
print("len(state):", len(state))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

CPython doesn't have __len__ on an enum.

@IhorNehrutsa IhorNehrutsa Oct 10, 2026 •

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.

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__']

Comment thread python-stdlib/enum/test_enum.py Resolved
@jonnor

jonnor commented Apr 25, 2025

Copy link
Copy Markdown

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
With some exceptions like the tests using inspect, threading, pickle it seems possible to port most of them to MicroPython. That would give a very high degree of confidence that the implementation is conformant. And in the cases that one chooses to not be conformant, that can be documented with skipped tests.

@IhorNehrutsa

Copy link
Copy Markdown
Author

I have successfully completed the task that requires the Enum class.
I don't plan to support this PR in the future.
You are welcome to continue working with this PR as you wish.
Thanks everyone.

rtyley added a commit to rtyley/analogue-led-clock that referenced this pull request Mar 22, 2026
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
rtyley added a commit to rtyley/analogue-led-clock that referenced this pull request Mar 22, 2026
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
@mchobby

mchobby commented Apr 11, 2026

Copy link
Copy Markdown

@dpgeorge
This PR looks stuck in time. I didn't find enum.py in micropython-lib/python-stdlib/enum.py .
Getting Enum for MicroPython would be really useful .

Need some help on this PR ? Were could I start ?

Dominique

@Josverl

Josverl commented Apr 12, 2026

Copy link
Copy Markdown
Contributor

Need some help on this PR ? Were could I start ?

That would be much appreciated.
I would suggest that making it match Cpython more and changing/adding tests to prove that would be the next step

@IhorNehrutsa

Copy link
Copy Markdown
Author

@mchobby @Josverl You may pull down this PR and try to use enum.py. Please write reviews about usage here

@Josverl

Josverl commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

@IhorNehrutsa, may I ask why you closed the documentation PR?

@IhorNehrutsa

Copy link
Copy Markdown
Author

@IhorNehrutsa, may I ask why you closed the documentation PR?

This has been going on for so long that I forgot. :(

@mchobby

mchobby commented Apr 15, 2026

Copy link
Copy Markdown

I'm a bit skeptical about the last @IhorNehrutsa action.
As I understand, the initial PR enum.py behavior was too far from CPython implementation.
I was interested to help in reducing the gap between CPython & MicroPython implementation.
That was looking as a "Good-First-Issue" to me (and for me).

On the meanwhile, @IhorNehrutsa pushed an AI rework of the code and "here is it for you to test".
As last arrival in this PR (and micropython-lib), I'm not in great position to evaluate the appropriateness of that rework.
@Josverl could you have a quick review on this for guidance?

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.
Cheers

@Josverl

Josverl commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

@mchobby,
I agree with the earlier comments that it isn’t the reviewer’s job to try to interpret or “fix up” clearly AI‑generated submissions. If the submitter isn’t putting in at least the same level of effort as the reviewers, the process becomes unbalanced and unsustainable.
That does not mean that AI is not to be used as a tool to create code, but it does mean that there needs to be more that just that.

@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.
to be clear - I do appreciate your efforts, and I realize that sometimes the wait for a PR to get merged (or even rejected) can exceed ones attention span. but in order for us to work as a community I prefer to have some level confidence.

There is clear interest in having an Enum class available in MicroPython. But implementing one properly is non‑trivial — it touches (the lack of) metaclasses, memory constraints, and the broader philosophy of keeping the core minimal.

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.

@IhorNehrutsa

Copy link
Copy Markdown
Author

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.

@IhorNehrutsa

Copy link
Copy Markdown
Author

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 With some exceptions like the tests using inspect, threading, pickle it seems possible to port most of them to MicroPython. That would give a very high degree of confidence that the implementation is conformant. And in the cases that one chooses to not be conformant, that can be documented with skipped tests.

Can someone write a MicroPython version of the CPython tests https://github.com/python/cpython/blob/main/Lib/test/test_enum.py ?

@projectgus projectgus left a comment

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.

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.🙏

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

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.

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?

@MrCodeGameandAnime MrCodeGameandAnime Nov 23, 2026 •

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 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?

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 suggest not spending time discussing enum_mini right now, but rather deferring it to the final stage.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Understood. We'll focus on enum for now and revisit enum-mini packaging at the final stage.

Comment thread python-stdlib/enum/enum_usage.py Outdated
@@ -0,0 +1,152 @@
# enum_usage.py
# version="1.5.1"

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.

No need to track versions in the source files, they're tracked in the manifest and by git.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment thread python-stdlib/enum/README.md Outdated
Comment on lines +11 to +21
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.

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.

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.md should be user-facing documentation, including: basics of enum use, how/why someone would choose between enum and enum_mini implementations, 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Simplified the README in 1a6da1e45d0f4143cbba750cb7e5023b6402d22a. It now shows how to get started, when to use full or mini, and where behavior differs from CPython.

Comment thread python-stdlib/enum/test_enum.py Outdated
self.assertEqual(json.loads(json.dumps([Mode.FAST])), ["fast"])

def test_full_then_mini_and_fresh_full(self):
import enum_mini

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.

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).

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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?

Comment thread python-stdlib/enum/enum.py Outdated
(type(v), cls),
{
"name": n,
"value": v,

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.

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.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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:

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 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.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Removed the abbreviation glossaries from both enum modules and put the relevant explanations next to the code in 88dc53df1528d0fcc4a7df055491efe4745fbaed.

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.

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)

Comment thread python-stdlib/enum/enum.py Outdated
cls.__getitem__ = getitem
cls._str_getitem = getitem
cls.__members__ = members
cls._str_finalized = _STR_FINALIZED

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.

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.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

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 seems like more development code rather than something we'd merge. If possible, please convert to unit tests instead.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

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.

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.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Moved both usage scripts into examples/ and trimmed them to short demos in 1a6da1e45d0f4143cbba750cb7e5023b6402d22a

@MrCodeGameandAnime

Copy link
Copy Markdown

@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.

IhorNehrutsa and others added 10 commits November 20, 2026 10:34
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>
@IhorNehrutsa
IhorNehrutsa marked this pull request as ready for review November 20, 2026 08:55
@IhorNehrutsa

Copy link
Copy Markdown
Author

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.

@MrCodeGameandAnime

Copy link
Copy Markdown

@IhorNehrutsa I’ve opened a branch 4a2e389 and fixed the commit-message check locally. Are you open to reviewing a follow-up patch on your branch that addresses projectgus’s packaging and documentation feedback? We can agree separately on which CPython behaviors to support.

@IhorNehrutsa

Copy link
Copy Markdown
Author

@MrCodeGameandAnime Ok, let's try

@MrCodeGameandAnime

Copy link
Copy Markdown

@IhorNehrutsa, both examples and the two tests moved from enum_check.py passed on stock MicroPython 1.29.0 for Windows. I also updated the plain Enum identity test to match 1.5.2, and it now passes. The suites still report seven test failures or errors. The underlying issues were already present in 4a2e389, and the StrEnum raw-value lookup failure now has its own test. The two latest commits (1384867e417e7991afe5a8cbd2f72a5d99d8fd8a and 7ac7b809d6a5b16b533abf45062a80dd99879a22) only change tests. I’m holding the packaging and shared-test changes until we agree on the proposals in the inline threads.

IhorNehrutsa and others added 12 commits November 24, 2026 00:00
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants