Python local import from files stored in at the same level of directory is often confusing to me. I have the following directory structure,
/distrib
__init__.py # empty
bases.py # contains classes MainBase etc.
extension.py # contains classes MainExtension etc
/errors
__init__.py
base_error.py
In file bases.py
importing classes from extension.py
is successful. For example, simply using from .extensions import MainExtension
would work. On the other hand, in extensions.py
, importing a class from bases.py
faces challenges.
Attempt 1
If I from bases import MainBase
, it complains ModuleNotFoundError: No module named 'bases'
.
Attempt 2
If I specify it as local import by from .bases import MainBase
, it complains ImportError: cannot import name 'MainBase'
.
Attempt 3
If I import it using from . import bases
, there is no error. But, consequently using bases.MainBase
triggers error module distrib.bases has no attribute 'MainBase'
and
it seem that all classes defined in the bases.py
file are 'missing'.
However, in a different folder such as errors
, I can import classes from distrib.bases
normally. What exactly is happening here? Doesn't Python allow cyclical import?