7
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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Trqzy
  • 73
  • 1
  • 1
  • 6
  • Looks like you're shadowing the standard library module `threading` with a local module by the same name. Don't use names already taken by the standard library. – Brian61354270 Apr 12 '21 at 15:22

3 Answers3

7

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).

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • but how to say vscode\python to search firstly from installed packages, and only after from cwd? – Damir Nafikov Sep 11 '22 at 15:38
  • @DamirNafikov The order is given - check this link https://docs.python.org/3/tutorial/modules.html#the-module-search-path shared by Gino Mempin in his comment to another answer. Anyway, whenever importing multiple modules using the same names (independent of the order), you're running into problems. You need to prevent using _any_ names that are already taken by other modules in your environment. – Lenka Čížková Oct 20 '22 at 13:06
0

I solved my problem, example code:

Main.py

if __name__ == "__main__":
    import package2
    pack2class = package2.Package2(main=self)

package2.py

import Main
class Package2(object):
    def __init__(self, main:Main.MainClass): # for suggestion code
        pass # your codes ...
Dream59
  • 101
  • 6
-1

When importing modules, python checks the files in your current working directory first, before checking other built-in modules. So, you probably have a file named threading.py which doesn't have the necessary attributes. In other words, you made a circular import.

NKUwakwe
  • 7
  • 2
  • Relevant documentation for where/how Python looks for modules: https://docs.python.org/3/tutorial/modules.html#the-module-search-path – Gino Mempin Apr 27 '22 at 23:24