Skip to content Skip to sidebar Skip to footer

Python Nameerror: Global Name 'thread' Is Not Defined

I made file called thread.py and if I want to import it, it doesn't work. When I use a filename like cheese.py it works fine import json from thread import Thread class Board:

Solution 1:

A built-in module with the name thread already exists.

>>>import thread>>>thread
<module 'thread' (built-in)>

When you are trying to import using from thread import Thread it is trying to search for the attribute named Thread which does not exists in the built-in thread module.

>>> hasattr(thread, 'Thread')
False

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory).

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  • The installation-dependent default.

For more here

It is recommended that you use a user defined module name that is different than the built-in module name.

Solution 2:

Python 3 has a built in module Threading that has a class called Thread

which is causing the conflict, so consider renaming your file to something else.

Post a Comment for "Python Nameerror: Global Name 'thread' Is Not Defined"