This is a machine-translated text that may contain errors!
Enums (enumerations) are a way to define a datatype that can only have a limited set of predefined values. This makes it easier to avoid errors by ensuring that a variable can only have valid values.
Enums are not strictly used for validation, but they help us limit which values are valid for a variable, and can therefore help prevent errors.
For example, if you have a class that represents a car, you can use an Enum to define what colors the car can have:
from enum import Enum
class CarColor(Enum):
RED = "red"
BLUE = "blue"
GREEN = "green"
BLACK = "black"
WHITE = "white"
class Car:
def __init__(self, make: str, model: str, year: int, color: CarColor):
self.make = make
self.model = model
self.year = year
self.color = color
Why?
Our IDE provides better autocompletion when we use enums, and we avoid (make it difficult) to set invalid values. If we try to assign a color that is not defined in CarColor, Python will throw an error. This makes the code more robust and easier to maintain. The fewer possible errors that can occur, the better quality we get in the code.
Imagine we have a function that handles payment methods: PayPal, VISA, MASTERCARD and BITCOIN. By using an Enum for payment methods, we can ensure that the function only receives valid payment methods, and not "MASTERCARDD" or "CASH", which can lead to errors in the program.
Task 1 - Create an Enum
Create an Enum called EyeColor and implement this in the Person class from the previous module. EyeColor should have the following values:
BLUEBROWNGREENHAZEL
Enums are widely used in game development
If you look up the documentation for various games, you will often see that they use Enums to define things like weapons, enemies, levels and the like. This is because it makes it easier to handle such things in the code, and it makes it easier to avoid errors.

