Fix - NameError: name 'Enum' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

Fix - NameError: name 'Enum' is not defined in Python #

The Python "NameError: name 'Enum' is not defined" occurs when we use the Enum class without importing it first. To solve the error, import the class from the enum module before using it - from enum import Enum.

nameerror name enum is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'Enum' is not defined class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3

To solve the error, we have to import the Enum class from the enum module.

main.py
# 👇️ import enum class from enum import Enum class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Size.SMALL) print(Size.MEDIUM) print(Size.LARGE)

Enums are a set of members that are bound to unique, constant values.

The Size class in the example is an enumeration (or enum).

The attributes (Size.SMALL, Size.MEDIUM, etc) are enum members.

Each enum member has a name and a value.

main.py
from enum import Enum class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Size.SMALL.name) # 👉️ "SMALL" print(Size.SMALL.value) # 👉️ 1 print(Size.MEDIUM.name) # 👉️ "MEDIUM" print(Size.MEDIUM.value) # 👉️ 2 print(Size.LARGE.name) # 👉️ "LARGE" print(Size.LARGE.value) # 👉️ 3

Enum members have human readable string representations.

main.py
from enum import Enum class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Size.SMALL) # 👉️ "Size.SMALL" print(Size.MEDIUM) # 👉️ "Size.MEDIUM" print(Size.LARGE) # 👉️ "Size.LARGE"

And the type of an enum member is the enumeration it belongs to.

main.py
from enum import Enum class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(type(Size.SMALL)) # 👉️ "<enum 'Size'>" print(isinstance(Size.SMALL, Size)) # 👉️ True

You can use a simply for loop to iterate over an enum.

main.py
from enum import Enum class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Size: print(size)

You can also programmatically access enum members and their attributes.

main.py
from enum import Enum class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Size(2)) # 👉️ Size.MEDIUM some_key = 'LARGE' print(Size[some_key]) # 👉️ Size.LARGE

We can pass a value to the enum to get access to the member with the specified value.

Bracket notation can also be used for dynamic access of enum members.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.