tezvyn:

Python Enums: Give Names to Magic Numbers

Source: docs.python.orgbeginner

Python's Enum gives meaningful names to "magic numbers" or strings. Use it for fixed sets of options like statuses or categories to make code self-documenting. The footgun: don't compare members to raw values; compare member to member for type safety.

Python's Enum replaces ambiguous "magic numbers" or strings with a fixed set of named constants, making your code self-documenting. Instead of checking `if status == 1`, you check `if status == Status.PENDING`. This is perfect for defining states, categories, or configuration options where only a few specific values are allowed. The main footgun is comparing an enum member to its raw value (`status == 1`), which defeats the purpose. Always compare member to member (`status == Status.PENDING`) to leverage type safety and improve clarity.

Read the original → docs.python.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

Python Enums: Give Names to Magic Numbers · Tezvyn