The enum package in python 3.11 has the StrEnum class. I consider it very convenient but cannot use it in python 3.10. What would be the easiest method to use this class anyway?
On Python 3.10, you can inherit from str and Enum to have a StrEnum:
from enum import Enum
class MyEnum(str, Enum):
choice1 = "choice1"
choice2 = "choice2"
With this approach, you have string comparison:
"choice1" == MyEnum.choice1
>> True
Be aware, however, that Python 3.11 makes a breaking change to classes which inherit from (str, Enum): https://github.com/python/cpython/issues/100458. You will have to change all instances of (str, Enum) to StrEnum when upgrading to maintain the same behavior.
Or:
you can execute pip install StrEnum and have this:
from strenum import StrEnum
class MyEnum(StrEnum):
choice1 = "choice1"
choice2 = "choice2"
There is also backports.strenum which copies the standard library implementation from 3.11 and makes it available to Python >=3.8.6. You might want this instead of https://pypi.org/project/StrEnum/ if you intend to switch to the standard library version for Python >= 3.11, as it should be drop-in compatible.
Note that backports.strenum enforces Python <3.11, so you need to specify a conditional dependency like this:
"backports.strenum (>=1.3.1,<2.0) ; python_version < '3.11'"
You can then import like this to automatically use the standard library version if available:
try:
from enum import StrEnum
except ImportError:
from backports.strenum import StrEnum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With