0

The module importing seems failing when cross-importing.

My prog.py file:

import sys
sys.path.append(".")
from m1 import f1

And m1.py:

from m2 import f2

def f1():
  pass

And m2.py:

from m1 import f1

def f2():
  pass   

My module m1 needs to use some functions in module 2, and module 2 needs to use some functions in module 1, so I import them the way above. But Python (python3) doesn't let me do so. Here's the exeption:

Traceback (most recent call last):
  File "prog.py", line 3, in <module>
    from m1 import f1
  File "/temp/m1.py", line 1, in <module>
    from m2 import f2
  File "/temp/m2.py", line 1, in <module>
    from m1 import f1
ImportError: cannot import name 'f1'

I know it is cross-importing, but how to solve this problem?

Dee
  • 7,455
  • 6
  • 36
  • 70

2 Answers2

2

You can move the cross imports to the end of the file, so that everything you export is already defined:

And m1.py:

def f1():
  pass

from m2 import f2

And m2.py:

def f2():
  pass

from m1 import f1
MegaIng
  • 7,361
  • 1
  • 22
  • 35
0

There's a solution here by moving the import into the function instead of importing at top of file, but importing at top is more good looking.

Reference: https://stackoverflow.com/a/17226057/5581893

Dee
  • 7,455
  • 6
  • 36
  • 70