user3595632
user3595632

Reputation: 5730

Python: import each other

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?

Upvotes: 1

Views: 2112

Answers (1)

hspandher
hspandher

Reputation: 16763

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.

Upvotes: 3

Related Questions