1

I know there are some question about this problem : Python files - import from each other

But this solution doesn't work for me.

This is directory structure:

├── tester.py
└── utility
    ├── __init__.py
    ├── analysis.py
    └── util.py

__init__.py

from .analysis import *
from .util import *

analysis.py

import util


def funcA():
    print("a")

util.py

import analysis

def funcB():
    print("b")

But this occur,

ImportError: No module named 'util'

I want to main __init__.py the way I defined.

Is there any way I can fix this problem?

user3595632
  • 5,380
  • 10
  • 55
  • 111
  • The error occurs in which module? – stelioslogothetis May 25 '17 at 11:30
  • Refer to [this link for clear explanation](https://stackoverflow.com/questions/11698530/two-python-modules-require-each-others-contents-can-that-work) – gowtham May 25 '17 at 11:30
  • Your example should provide some indication of *why* each module needs to import the other. – chepner May 25 '17 at 12:15
  • You can also move import statements to the end of file. [Two Python modules require each other's contents - can that work?](https://stackoverflow.com/questions/11698530/two-python-modules-require-each-others-contents-can-that-work) – Hadi Nov 11 '18 at 06:19

1 Answers1

3

It's a classic case of circular imports. analysis is importing from util and util is importing from analysis. Although you can resolve the problem, by importing inside a function/method such that it happens at runtime, I'd suggest improving the design of the code.

More often than not circular import error is a sign that there's a problem in your code design. In your case, either the code in analysis file and util file belongs together in a single file, or you need to store the common content of both the files in a separate common file and import from common in both the files, instead of importing from each other.

CyberPlayerOne
  • 3,078
  • 5
  • 30
  • 51
hspandher
  • 15,934
  • 2
  • 32
  • 45