Movatterモバイル変換


[0]ホーム

URL:


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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
IhorNehrutsa wants to merge3 commits intomicropython:master
base:master
Choose a base branch
Loading
fromIhorNehrutsa:enum

Conversation

@IhorNehrutsa
Copy link

@IhorNehrutsaIhorNehrutsa commentedMar 5, 2025
edited
Loading

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

from enum import Enume = Enum({"X": 1, "Y": 2})                          # create Enum object from dictionary of key-value pairsprint(e)print("add new key-value pair")e.A = 'A'                                           # add new key-value paire.B = 'B'print(e)print("e.X:", e.X)                                  # get value from keyprint("e.X.value:", e.X.value)                      # get value from keyprint("e(e.X):", e(e.X))                            # get value from keyprint("e.key_from_value(1):", e.key_from_value(1))  # get key from valueprint("e.is_value(e.B):", e.is_value(e.B))print("del e.B")del e.B                                             # delete key-value pairprint(e)print("e.is_value('B'):", e.is_value('B'))          # check if the value is in the Enum objectprint("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 pairEnum({'A': 'A', 'B': 'B', 'Y': 2, 'X': 1})e.X: 1e.X.value: 1e(e.X): 1e.key_from_value(1): Enum.Xe.is_value(e.B): Truedel e.BEnum({'A': 'A', 'Y': 2, 'X': 1})e.is_value('B'): Falsee.B: will raise the KeyError exceptionTraceback (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 theWay to use dot notation to refer to states in a state machine #15694
and@njourdane enum() func from theRequest for package: micropython-enum #269

njourdane reacted with hooray emoji
Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
@IhorNehrutsaIhorNehrutsa changed the titleAdd Enum class.python-stdlib/enum/enum.py: Add Enum class.Mar 5, 2025
@IhorNehrutsa
Copy link
Author

Usage example::

from enum import Enumclass State(Enum):  Stop = 10  Run = 20  Ready = 30state = State()print("state:", State())current_state = state.Stopprint("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.Runprint("current_state:", current_state, state.key_from_value(current_state))# some processi = -1while 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.StopStop stateNot a Ready stateRun!current_state: 20 State.Run...............................current_state: 30 State.ReadyDone!

@dpgeorge
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, intools/ci.sh inside the functionci_package_tests_run.

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

@IhorNehrutsa
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 theWay to use dot notation to refer to states in a state machine #15694
and@njourdane enum() func from theRequest for package: micropython-enum #269

Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
@IhorNehrutsa
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 theenum 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 havekey_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.

@jonnor
Copy link

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
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 freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@dpgeorgedpgeorgedpgeorge left review comments

+1 more reviewer

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

4 participants

@IhorNehrutsa@dpgeorge@jonnor@Josverl

[8]ページ先頭

©2009-2025 Movatter.jp