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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

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

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

nameerror name threading is not defined

Here is an example of how the error occurs.

main.py
import queue q = queue.Queue() def worker(): while True: item = q.get() print(f'Working on {item}') print(f'Finished {item}') q.task_done() # ⛔️ NameError: name 'threading' is not defined threading.Thread(target=worker, daemon=True).start() for item in range(15): q.put(item) q.join() print('All work completed')

To solve the error, we have to import the threading module.

main.py
# ✅ import threading module first import threading import queue q = queue.Queue() def worker(): while True: item = q.get() print(f'Working on {item}') print(f'Finished {item}') q.task_done() threading.Thread(target=worker, daemon=True).start() for item in range(15): q.put(item) q.join() print('All work completed')

Even though the threading 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 t when importing threading because module names are case-sensitive.

Also, make sure you haven't imported threading 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 threading module is to import only the functions and classes that your code uses.

main.py
# 👇️ import only Thread class from threading import Thread from queue import Queue q = Queue() def worker(): while True: item = q.get() print(f'Working on {item}') print(f'Finished {item}') q.task_done() # 👇️ accessing Thread class directly Thread(target=worker, daemon=True).start() for item in range(15): q.put(item) q.join() print('All work completed')

The example shows how to import the Thread class from the threading module.

Instead of accessing the members on the module, e.g. threading.Thread, 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 threading, it is much harder to see which classes or functions from the threading module are being used in the file.

Conversely, when we import specific classes, it is much easier to see which classes and methods from the threading module are being used.

You can view all of the classes and methods the threading module provides by visiting the official docs.

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