Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this import sequence generate an error? [duplicate]

I have three files, with import statements done in the following way:

main.py

from file1 import *
from file2 import *
def someFunc():
    print("hi")

file1.py

from main import someFunc as sayHi
class A:
    def __init__(self):
        pass
sayHi()

file2.py

from file1 import *
a = A()

As soon as that import line in file1.py is written, I get this error: ImportError: cannot import name someFunc. And with another compiler, I get NameError: Name 'A' is not defined. Why is this so?

like image 566
idlackage Avatar asked Feb 24 '26 22:02

idlackage


1 Answers

When you run main.py, it executes its first line, which is to import file1.py. This causes file1.py to be run. It tries to import from main.py, but remember, only the first line of main.py has run so far - someFunc hasn't been defined yet. Thus, that import fails.

like image 194
Amber Avatar answered Feb 27 '26 12:02

Amber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!