By reading the documentation (i.e., I didn't try it because I use an older version of Python, but I trust the docs), since Python 3.11 you can do the following:
from enum import StrEnum
class Directions(StrEnum):
NORTH = 'north'
SOUTH = 'south'
print(Directions.NORTH)
>>> north
Note that it looks like when subclassing StrEnum, defining the enum fields as single-value tuples will make no difference at all and would also be treated as strings, like so:
class Directions(StrEnum):
NORTH = 'north', # notice the trailing comma
SOUTH = 'south'
Please refer to the docs and the design discussion for further understanding.
If you're running python 3.6+, execute pip install StrEnum
, and then you can do the following (confirmed by me):
from strenum import StrEnum
class URLs(StrEnum):
GOOGLE = 'www.google.com'
STACKOVERFLOW = 'www.stackoverflow.com'
print(URLs.STACKOVERFLOW)
>>> www.stackoverflow.com
You can read more about it here.
Also, this was mentioned in the docs - how to create your own enums based on other classes:
While IntEnum is part of the enum module, it would be very simple to
implement independently:
class IntEnum(int, Enum):
pass This demonstrates how similar derived enumerations can be defined; for example a StrEnum that mixes in str instead of int.
Some rules:
When subclassing Enum, mix-in types must appear before Enum itself in
the sequence of bases, as in the IntEnum example above.
While Enum can have members of any type, once you mix in an additional
type, all the members must have values of that type, e.g. int above.
This restriction does not apply to mix-ins which only add methods and
don’t specify another type.
When another data type is mixed in, the value attribute is not the
same as the enum member itself, although it is equivalent and will
compare equal.
%-style formatting: %s and %r call the Enum class’s str() and
repr() respectively; other codes (such as %i or %h for IntEnum) treat the enum member as its mixed-in type.
Formatted string literals, str.format(), and format() will use the
mixed-in type’s format() unless str() or format() is
overridden in the subclass, in which case the overridden methods or
Enum methods will be used. Use the !s and !r format codes to force
usage of the Enum class’s str() and repr() methods.
Source: https://docs.python.org/3/library/enum.html#others