Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 3 commits into micropython:master
base: master
Choose a base branch
Loading
from IhorNehrutsa:enum

Conversation

@IhorNehrutsa
Copy link

@IhorNehrutsa IhorNehrutsa commented Mar 5, 2025
edited
Loading

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

from enum import Enum
e = Enum({"X": 1, "Y": 2}) # create Enum object from dictionary of key-value pairs
print(e)
print("add new key-value pair")
e.A = 'A' # add new key-value pair
e.B = 'B'
print(e)
print("e.X:", e.X) # get value from key
print("e.X.value:", e.X.value) # get value from key
print("e(e.X):", e(e.X)) # get value from key
print("e.key_from_value(1):", e.key_from_value(1)) # get key from value
print("e.is_value(e.B):", e.is_value(e.B))
print("del e.B")
del e.B # delete key-value pair
print(e)
print("e.is_value('B'):", e.is_value('B')) # check if the value is in the Enum object
print("e.B: will raise the KeyError exception")
print(e.B) # raise an exception due to no such a key attribute

Output is:

Enum({'Y': 2, 'X': 1})
add new key-value pair
Enum({'A': 'A', 'B': 'B', 'Y': 2, 'X': 1})
e.X: 1
e.X.value: 1
e(e.X): 1
e.key_from_value(1): Enum.X
e.is_value(e.B): True
del e.B
Enum({'A': 'A', 'Y': 2, 'X': 1})
e.is_value('B'): False
e.B: will raise the KeyError exception
Traceback (most recent call last):
File "<stdin>", line 234, in <module>
File "<stdin>", line 126, in __getattr__
KeyError: no such attribute: B

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

njourdane reacted with hooray emoji
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
@IhorNehrutsa IhorNehrutsa changed the title (削除) Add Enum class. (削除ここまで) (追記) python-stdlib/enum/enum.py: Add Enum class. (追記ここまで) Mar 5, 2025
Copy link
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, state.key_from_value(current_state))
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, state.key_from_value(current_state))
# some process
i = -1
while current_state != state.Ready:
 i += 1
 if state.is_value(i):
 if state(i) == state.Ready:
 current_state = state.Ready
 print(".", end="")
print()
print("current_state:", current_state, state.key_from_value(current_state))
print("Done!")

Output is::

state: State({'Ready': 30, 'Stop': 10, 'Run': 20})
current_state: 10 State.Stop
Stop state
Not a Ready state
Run!
current_state: 20 State.Run
...............................
current_state: 30 State.Ready
Done!

Copy link
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.

Copy link
Author

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

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

Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Copy link
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.

Copy link
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

Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Copy link
Author

Should I squash commits?

@@ -0,0 +1,91 @@
# enum_test.py

from enum import Enum, enum
Copy link
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?

Enabled = True


state = Enum()
Copy link
Member

Choose a reason for hiding this comment

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

CPython cannot create enums in this way.


state = Enum()
print(state)
state = Direction()
Copy link
Member

Choose a reason for hiding this comment

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

CPython requires a value in the constructor here.

print(state)
state = State()
print(state)
state = State({"X": 1.0, "Y": 2.0})
Copy link
Member

Choose a reason for hiding this comment

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

CPython doesn't allow such an argument to the constructor.


print("Direction(Direction.CCW):", Direction(Direction.CCW))
print("Direction('CW'):", Direction("CW"))
print("state(10):", state(10))
Copy link
Member

Choose a reason for hiding this comment

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

CPython doesn't allow calling an enum.

print("state('CW'):", state("CW"))
print("type(state('CW')):", type(state("CW")))

print("state.key_from_value(20):", state.key_from_value(20))
Copy link
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 key_from_value().

CCW = "CCW"


class State(Direction):
Copy link
Member

Choose a reason for hiding this comment

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

CPython doesn't allow inheriting enums from each other.

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


print("state.keys():", state.keys())
print("state.values():", state.values())
print("state.items():", state.items())
Copy link
Member

Choose a reason for hiding this comment

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

CPython enums don't have keys/values/items methods.

Copy link

jonnor commented Apr 25, 2025

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.

Copy link
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.

jonnor and njourdane reacted with thumbs up emoji

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@dpgeorge dpgeorge dpgeorge left review comments

+1 more reviewer

@Josverl Josverl Josverl left review comments

Reviewers whose approvals may not affect merge requirements

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

AltStyle によって変換されたページ (->オリジナル) /