This is a machine-translated text that may contain errors!
Enums (enumerations) are a way to define a data type that can only have a limited set of predefined values. This makes it easier to avoid errors by ensuring that a variable can only hold valid values.
Strictly speaking, enums are not used for validation, but they help us restrict which values are valid for a variable, thereby helping to prevent errors.
For example, if you have a class representing a car, you can use an enum to define what colors the car can be:
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 named EyeColor and implement it 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 through the documentation of various games, you will often see that they use Enums to define things such as weapons, enemies, levels, and so on. This is because it makes handling these types of elements easier within the code, making it simpler to avoid errors.

