backports-strenum
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.
Warnings
- gotcha This library is a backport of `enum.StrEnum` from Python 3.11. If your project targets Python 3.11 or newer, you should use `from enum import StrEnum` directly from the standard library. Using `backports.strenum` on Python 3.11+ is unnecessary and may lead to import conflicts or deprecated code if not managed properly.
- gotcha `StrEnum` members behave like strings for equality checks (`==`) and can be passed where strings are expected. However, they are still distinct enum objects. Identity checks (`is`) against raw strings will fail (e.g., `MyStatus.ACTIVE is "active"` is `False`). Relying purely on string methods without converting the member to `str()` explicitly might lead to unexpected behavior in edge cases.
Install
-
pip install backports-strenum
Imports
- StrEnum
from backports.strenum import StrEnum
Quickstart
from backports.strenum import StrEnum
class MyStatus(StrEnum):
ACTIVE = "active"
INACTIVE = "inactive"
PENDING = "pending"
# Usage examples
print(MyStatus.ACTIVE) # Output: active
print(MyStatus.ACTIVE == "active") # Output: True
print(isinstance(MyStatus.INACTIVE, str)) # Output: True
def get_status_message(status: MyStatus) -> str:
if status == MyStatus.ACTIVE:
return f"Status is: {status}"
return f"Status is not active: {status}"
print(get_status_message(MyStatus.ACTIVE))
print(get_status_message(MyStatus.PENDING))