StrEnum

0.4.15 · active · verified Sun Mar 29

StrEnum is a Python library that provides an `Enum` class that inherits from `str`, allowing enumeration members to behave directly like strings. This is particularly useful for scenarios involving APIs, JSON serialization, and generally replacing 'magic strings' with type-safe, readable constants. The library is actively maintained, with version 0.4.15 being the current release, and follows a frequent, minor-version release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a basic `StrEnum` where `auto()` uses the member name directly, and a `LowercaseStrEnum` which converts `auto()` values to lowercase. It also shows manual string assignment and how `StrEnum` members behave like strings, including comparison.

from enum import auto
from strenum import StrEnum, LowercaseStrEnum

class HttpMethod(StrEnum):
    GET = auto() # Value will be 'GET'
    POST = 'post_value' # Explicitly assigned string value
    PUT = auto()

class FileExtension(LowercaseStrEnum):
    TXT = auto() # Value will be 'txt'
    PDF = auto()

assert HttpMethod.GET == 'GET'
assert HttpMethod.POST == 'post_value'
assert HttpMethod.PUT == 'PUT'

assert FileExtension.TXT == 'txt'
assert FileExtension.PDF == 'pdf'

print(f"HTTP Method: {HttpMethod.GET}")
print(f"File Type: {FileExtension.PDF}")

# Enums compare equal to their string value
assert HttpMethod.GET == "GET"

# However, it's generally recommended to compare enum to enum for type safety
if HttpMethod.GET is HttpMethod.GET:
    print("GET method detected.")

view raw JSON →