Howdy Pardner

Skip to content

This here’s a machine-translated text that might contain some errors!

Enums (enumerations) be a way to define a data type that can only hold a limited set o’ pre-defined values. This makes it easier to avoid mistakes by makin’ sure a variable can only have valid values.

Enums ain’t strictly used for validation, but they help us limit which values be valid for a variable, and thus they can help prevent errors.

Fer example, if ya got a class that represents a car, ya 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 gives better autocompletion when we use enums, and we avoid (make it difficult) settin’ invalid values. If we try to assign a color that ain’t defined in CarColor, Python’ll throw an error. This makes the code more robust and easier to maintain. The fewer possible errors that can happen, the better quality we get in the code.

Now, picture this: we got a function that handles payment methods: PayPal, VISA, MASTERCARD and BITCOIN. By usin’ an Enum for payment methods, we can make sure the function only receives valid payment methods, and not "MASTERCARDD" or "CASH", which can lead to errors in the program.

Enum Meme

Easy Task 1 - Make a Enum

Make a Enum called EyeColor and implement this in the Person class from the previous module. EyeColor should have the following values:

  • BLUE
  • BROWN
  • GREEN
  • HAZEL

Enums get used a whole bunch in game development

If you look up the documentation for different games, you’ll often see that they use Enums to define things like weapons, enemies, levels and the like. This is ‘cause it makes it easier to handle such things in the code, and it makes it easier to avoid mistakes.

https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/blockpistonstate?view=minecraft-bedrock-stable

Congrats ya reckon ya understand enums