QUERY · ISSUE
Request for package: micropython-enum
enhancement
I would like micropython to have support for IntEnum class. Base Enum would be nice to have, although just bare IntEnum would be enough in my opinion.
CANDIDATE · PULL REQUEST
docs/library/enum.rst: Add Enum class.
docs
Summary
There are several requests to develop the Enum class for MicroPython:
- #15694
- #8545
- #269
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?
Enums are especially useful when it comes to static type-checking. So it would be great if the implementation of this enum type allowed type-checking via mypy. This means all values need to be an instance of the defined enum-type.
I'm also interested by enum in MicroPython.
In the meantime, I found here this workaround:
for type-checking, I'm using the following trick:
This workaround is excellent! I combined it with const for my purposes:
+1 for a real implementation of this
But when have been imported getting "Unresolved attribute reference" warning.
The cpython implementation is surprisingly very complicated and relies heavily on metaclasses which aren't supported in micropython:
https://github.com/python/cpython/blob/f585ed19ad00f78ed99ba44be5e333c056076160/Lib/enum.py#L1051
As such any micropython implementation will need to be completely custom really, at which point we need to clearly define which aspects of Enum we want to support first, before figuring out how to implement them!
There are a number of limitations when subclassing builtins in micropython, especially
intbecause behind the scenes it's particularly optimised. Eg. https://docs.micropython.org/en/latest/genrst/builtin_types.html#no-int-conversion-for-int-derived-types-available+1 for an implementation of this as well.
docs/library/enum.rst: Add Enum class. #16842
Implementation in:
micropython-lib/python-stdlib/enum/enum.py: Add Enum class. #980