Skip to content

Conversation

IhorNehrutsa
Copy link
Contributor

@IhorNehrutsa IhorNehrutsa commented Mar 1, 2025

Summary

There are several requests to develop the Enum class for MicroPython:

Implementation in:
micropython-lib/python-stdlib/enum/enum.py: Add Enum class. #980

Testing

Tested during porting MKS-Servo CAN Interface Library to the MicroPython.
Used port/esp32: Add CAN(TWAI) driver. #12331.

Trade-offs and Alternatives

There is the trouble with the isinstance()/type().

  >>> isinstance(State.Run, State)
  False
  >>> State(State.Ready) == State.Ready
  False
  >>> int(str(State(State.Ready))) == State.Ready
  True
  >>> type(State(State.Ready))
  <class 'State'>
  >>> type(state(State.Ready))
  <class 'int'>
  >>> state(State.Ready) == State.Ready
  True

Quastion: Should enum.py and enum_test.py be placed in the micropython or micropython-lib repository?

Comment on lines +131 to +144
There is the trouble with the isinstance()/type().

>>> isinstance(State.Run, State)
False
>>> State(State.Ready) == State.Ready
False
>>> int(str(State(State.Ready))) == State.Ready
True
>>> type(State(State.Ready))
<class 'State'>
>>> type(state(State.Ready))
<class 'int'>
>>> state(State.Ready) == State.Ready
True
Copy link
Contributor Author

@IhorNehrutsa IhorNehrutsa Mar 11, 2025

Choose a reason for hiding this comment

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

@dpgeorge
There is solution for this trouble.
We need to remove enums from internal State.__dict__

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

>>> dir(State)
['__dir__', '__call__', '__class__', '__delitem__', '__getattr__', '__getitem__', '__init__', '__len__', '__module__', '__name__', '__qualname__', '__repr__', '__setitem__', '__str__', 'append', 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', '__bases__', '__delattr__', '__dict__', '__setattr__', 'fromkeys', '_get_enums_from_class', '_update', 'is_value', 'key_from_value', 'Stop', 'Run', 'Ready']
>>> State.__dict__
{'__qualname__': 'State', 'Ready': 30, '__module__': '__main__', 'Stop': 10, 'Run': 20}
>>> 

I tried, but I couldn't do it.

Signed-off-by: Ihor Nehrutsa <Ihor.Nehrutsa@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants