Search code examples
pythonimporterror

"Most likely due to circular import" in Python


import threading
import time

start = time.perf_counter()

def do_something():
    print("Sleeping in 1 second")
    time.sleep(1)
    print("Done sleeping")

t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)

finish = time.perf_counter()
print(f"Finished in {round(finish-start,1)} seconds(s) ")

Does anyone know why this piece of code returns this error when run and how to fix it?

Traceback (most recent call last):
  File "c:/Users/amanm/Desktop/Python/Python Crash Course/threading.py", line 1, in <module>
    import threading
  File "c:\Users\amanm\Desktop\Python\Python Crash Course\threading.py", line 12, in <module>
    t1 = threading.Thread(target=do_something)
AttributeError: partially initialized module 'threading' has no attribute 'Thread' (most likely due to a circular import) 

When I run this code in normal IDLE it seems to work but it doesn't work in Visual Studio Code.


Solution

  • It seems like the program file you have created is named threading.py, and you are importing a module also called threading. This causes a circular import because your file is shadowing the built-in module.

    Please rename your program (e.g., threading_example.py).