

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Sum Types
incomplete
2: Union Types
incomplete
3: Enums
incomplete
4: Sum Types
incomplete
5: Match
incomplete
6: Sum Types Practice
incomplete
This lesson's interactive features are locked, please to keep using them
So far, we've used classes to model the different cases in a sum type, and union type hints as a simpler way of describing the possible types of a value (albeit with no automatic enforcement at runtime).
If what you're trying to represent is a fixed set of values, you have another good option in Python's type system: enums.
Click to play video
Let's say we have a Color variable that we want to restrict to only three possible values:
REDGREENBLUEWe could use a plain old str to represent these values, but that's annoying because we have to keep track of the "valid" values and defensively check for invalid ones all over our codebase. Instead, we can use an Enum:
from enum import Enum
Color = Enum("Color", ["RED", "GREEN", "BLUE"])
print(Color.RED) # this works, prints 'Color.RED'
print(Color.TEAL) # this raises an exception
There is also a manual class-based syntax:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # this works, prints 'Color.RED'
print(Color.TEAL) # this raises an exception
The class-based syntax is more verbose, but safer because it prevents ambiguity between the variable name and the enum name. With Color = Enum("Color", ...), the string "Color" sets the enum class name, while Color = assigns that class to a variable. While those names normally shouldn't be different, they can be.
Now Color is a sum type! At least, as close as we can get in Python. There are a few benefits:
Color can only be RED, GREEN, or BLUE. If you try to use Color.TEAL, Python raises an exception.Color.Color has a "name" (e.g. RED) and an integer value (e.g. 1). The value can be useful if you need to store, compare, or serialize the enum in a specific way.Create an Enum called Doctype with values:
PDFTXTDOCXMDHTMLDon't forget to import the Enum class from the enum module!