Python challenge: Exploring enumerations
Here are some examples of working with enumerations:
Defining an enumeration
from enum import Enum
class Status(Enum):
OPEN = 1
ONGOING = 2
COMPLETED = 3
Importing an enumeration
Provided the enumeration above is created and saved in a file named status.py, you can import it as follows:
from status import Status
Creating a variable of type Status with value OPEN
status = Status.OPEN
print("Status: " + str(status))
Setting the status with a numeric value
another_status = Status(2)
print(another_status)
Checking the value of the enum variable
if status == Status.COMPLETED:
print("Congrats, the task is completed")
else:
print("Sorry, the task is not completed yet")
See all available values for the enumeration status
for status in Status:
print(status)
Accessing the enum by numeric value: Status(1)
print(Status(1))
Accessing an enum value that does not exist: Status(4) should not exist
try:
print(Status(4))
except ValueError:
print("Status(4) is not valid!")
Checking if a potential member is really a member of an enum
print(isinstance(Status.OPEN, Status))
Retrieving the value of an enum member
print("Status.OPEN has the numeric value %d " % (Status.OPEN.value))