3

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?

idlackage
  • 2,715
  • 8
  • 31
  • 52

2 Answers2

2

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.

Amber
  • 507,862
  • 82
  • 626
  • 550
0

You need to move the file1 and file2 imports down to the bottom of your file just to get it to work, though it would be better to avoid the circular imports.

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

file1.py

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

file2.py

from file1 import *
a = A()
Jeff Tratner
  • 16,270
  • 4
  • 47
  • 67