Skip to main content

Elegant implementation of Enum which inherits from str or bytes

Project description


Python 3.7 PyPi Package Version

Elegant implementation of Enum which inherits from str or bytes

As simple as this

from anystrenum import StrEnum

class Season(StrEnum):
    spring: str
    summer: str
    autumn: str
    winter: str

print(isinstance(Season.summer, str))
# summer
# True


  • Easy members assignment with type hinting (No need to use auto() or other stubs)
  • Automatic value generation with support of custom converters or separators
  • Method to filter members (contains, contained_in, startswith, endswith, etc.)
  • Custom str and bytes types support


$ pip install AnyStrEnum


Using custom words separator

To automatically replace all underscores (_) in names to something more suitable, use sep parameter:

from anystrenum import StrEnum

class Region(StrEnum, sep='-'):
    us_east_1: str
    us_west_1: str
    ca_central_1: str
    cn_northwest_1: str
    eu_central_1: str
    eu_west_1: str
    eu_north_2: str
    sa_east_1: str

# us-east-1

Using str converter and custom words separator

If you need to apply to your names more changes, you can use converter parameter. Pass a function in here which will be called on every member

from anystrenum import StrEnum

class ContentType(StrEnum, converter=lambda s: s.replace('_', '/', 1), sep='-'):
    application_json: str
    application_octet_stream: str
    application_x_json_stream: str
    audio_mpeg: str
    audio_pcm: str
    audio_ogg: str

# application/octet-stream

As you can see from an example, firstly, names will be converted with our lambda function and then, remaining underscores will be replaced with given separator

Filtering enum members

Using enums from previous examples

print(ContentType.filter(contains='-', startswith='a', endswith='m'))
# {<ContentType.application_octet_stream: 'application/octet-stream'>,
# <ContentType.application_x_json_stream: 'application/x-json-stream'>}

print(ContentType.filter(contained_in='Usually content type for MP3 is audio/mpeg'))
# {<ContentType.audio_mpeg: 'audio/mpeg'>}

print(Region.filter(startswith='eu', endswith='1'))
# {<Region.eu_west_1: 'eu-west-1'>, <Region.eu_central_1: 'eu-central-1'>}

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for AnyStrEnum, version 0.2.0
Filename, size File type Python version Upload date Hashes
Filename, size AnyStrEnum-0.2.0-py3-none-any.whl (6.3 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size AnyStrEnum-0.2.0.tar.gz (5.2 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page