Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
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
.
Here is an example of how the error occurs.
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.
# ✅ 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.
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.
# 👇️ 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.
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.