Last modified: Mar 06, 2025 By Alexander Williams

Fix Python NameError: Name 'Thread' Not Defined

If you're working with Python and encounter the error NameError: Name 'Thread' Not Defined, don't worry. This error is common and easy to fix. Let's dive into what causes it and how to resolve it.

What Causes the NameError: Name 'Thread' Not Defined?

The error occurs when Python cannot find the Thread class in your code. This usually happens because the Thread class is not imported from the threading module.

For example, if you try to use Thread without importing it, you'll get this error:


# Incorrect code
t = Thread(target=my_function)

This will raise the error:


NameError: name 'Thread' is not defined

How to Fix the NameError: Name 'Thread' Not Defined

To fix this error, you need to import the Thread class from the threading module. Here's how you can do it:


# Correct code
from threading import Thread

def my_function():
    print("Thread is running")

t = Thread(target=my_function)
t.start()

Now, the code will run without any errors, and the output will be:


Thread is running

Common Mistakes to Avoid

Sometimes, even after importing the Thread class, you might still encounter the error. This can happen if you misspell the import statement or forget to import it altogether.

For example, if you mistakenly write:


# Incorrect import
from threading import thread  # lowercase 'thread'

This will still raise the NameError because thread is not the same as Thread.

If you're dealing with similar errors like NameError: Name 'subprocess' Not Defined or NameError: Name 'datetime' Not Defined, the solution is similar. You need to ensure that the required module or class is imported correctly.

For more details on fixing these errors, check out our guides on Fix Python NameError: Name 'subprocess' Not Defined and Fix Python NameError: Name 'datetime' Not Defined.

Conclusion

The NameError: Name 'Thread' Not Defined is a common issue in Python, especially for beginners. By ensuring that you import the Thread class correctly from the threading module, you can easily resolve this error.

Always double-check your import statements and avoid common mistakes like misspelling. If you encounter similar errors, the same principles apply. Happy coding!