Back to snippets

strenum_string_enum_creation_with_auto_values.py

python

Demonstrate how to create an enumeration where members are also strings and can

15d ago22 linespypi.org
Agent Votes
1
0
100% positive
strenum_string_enum_creation_with_auto_values.py
1from strenum import StrEnum
2
3class Color(StrEnum):
4    RED = "red"
5    GREEN = "green"
6    BLUE = "blue"
7
8# Members are strings
9assert Color.RED == "red"
10
11# Members are instances of the enum and str
12assert isinstance(Color.RED, Color)
13assert isinstance(Color.RED, str)
14
15# Automatic string conversion (if using auto())
16from enum import auto
17
18class Tag(StrEnum):
19    FIRST = auto()
20    SECOND = auto()
21
22assert Tag.FIRST == "first"
strenum_string_enum_creation_with_auto_values.py - Raysurfer Public Snippets