Skip to content

Enums and the Standard Library

The Standard Library

A module can be imported into our code to add functionality.

We can add third-party packages, but the standard library gives us a lot of utilities.

  • datetime for dates
  • pathlib for file paths
  • logging for structured log messages
  • re for regular expressions such as slug cleanup
  • enum for enums
  • collections for advanced collection types and operations.
Python
from datetime import date

print(date.today())
  • datetime is the module
  • date is the thing I import from it

You'll know that a package is available in the standard library if you can use it without needing to add the package via uv.

Import Syntax

You'll most often see imports in one of these forms:

Python
import datetime
from datetime import date
from pathlib import Path

Enums

An enum is a good fit when a value should come from a small, fixed set of options.

Without an Enum

If I use plain strings everywhere, they're easy to typo and hard to cross reference:

Python
status = "inprogress"

Was that supposed to be "in_progress"? Did I forget an underscore?

Example

Python
from enum import StrEnum


class TaskStatus(StrEnum):
    planned = "planned"
    in_progress = "in_progress"
    blocked = "blocked"
    done = "done"

Why use Enums` instead of strings

  • autocomplete works
  • typos become easier to spot
  • invalid states are easier to reject

Auto-generated Enums.

Python also has an auto method, so you don't need to duplicate code.

Python
from enum import StrEnum, auto


class TaskPriority(StrEnum):
    low = auto()
    medium = auto()
    high = auto()
    urgent = auto()


print(TaskPriority.low)  # <TaskPriority.low: 'low'>

Other Enum Types

Python also has the base Enum class, and IntEnum.