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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

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

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

nameerror name operator is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'operator' is not defined print(operator.add(10, 20))

We have to import the operator module to solve the error.

main.py
# ✅ import operator module first import operator print(operator.add(10, 20)) # 👉️ 30

Even though the operator module is in the Python standard library, we still have to import it before using it.

Make sure you haven't used a capital letter o when importing operator because module names are case-sensitive.

Also, make sure you haven't imported operator in a nested scope, e.g. a function. Import the module at the top level to be able to use it throughout your code.

An alternative to importing the entire operator module is to import only the functions that your code uses.

main.py
from operator import add, sub print(add(10, 20)) # 👉️ 30 print(sub(20, 10)) # 👉️ 10

The example shows how to import only the add and sub functions from the operator module.

Instead of accessing the members on the module, e.g. operator.add, we now access them directly.

This should be your preferred approach because it makes your code easier to read.

For example, when we use an import such as import operator, it is much harder to see which functions from the operator module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which functions from the operator module are being used.

You can view all of the functions the operator module provides by visiting the official docs.

Use the search field on my Home Page to filter through my more than 1,000 articles.