The `backports.strenum` library provides a backport of the `enum.StrEnum` class, which was introduced in Python 3.11. It allows developers using Python versions 3.8.6 through 3.10 to define enumerated constants that are also subclasses of `str`, behaving like both an Enum member and a string. The current version is 1.3.1, and its release cadence is tied to the need for compatibility with newer Python features.
pip install backports-strenumVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to define a `StrEnum` class and use its members, highlighting their string-like behavior and direct comparison capabilities.
For projects targeting Python 3.11+, remove `backports-strenum` from your dependencies and update all `from backports.strenum import StrEnum` imports to `from enum import StrEnum`. Consider conditional imports for multi-version support (e.g., `try...except ImportError`).
Always use `==` for value comparison. If strictly string-only functionality is required, explicitly convert the `StrEnum` member to a string using `str(MyStatus.MEMBER)` before performing operations that require a raw string.
Install `backports.strenum` using `pip install backports.strenum` and employ a conditional import statement to correctly import `StrEnum` based on the Python version:
```python
import sys
if sys.version_info >= (3, 11):
from enum import StrEnum
else:
from backports.strenum import StrEnum
class MyEnum(StrEnum):
# ...
```Specify `backports.strenum` as a conditional dependency in your `pyproject.toml` or `setup.py` to ensure it's only installed for Python versions less than 3.11. For example, in `pyproject.toml`: ```toml [project] dependencies = [ "some-other-package", "backports.strenum; python_version < '3.11'" ] ```
Access the `name` or `value` attributes directly on the `StrEnum` member before any string coercion. Remember that for `StrEnum`, the member's value *is* the string itself, so `str(MyEnum.MEMBER)` or simply using `MyEnum.MEMBER` directly yields its string value.
```python
from backports.strenum import StrEnum
class Color(StrEnum):
RED = "red"
BLUE = "blue"
print(Color.RED) # Outputs: red
print(Color.RED.name) # Outputs: RED
# print(str(Color.RED).name) # This would raise AttributeError
```No dependency data recorded yet.