1

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?

X...
  • 173
  • 1
  • 2
  • 12
  • If you're trying to import * from .bases it work? – Tom Danilov Jul 05 '20 at 07:59
  • @ Tom Danilov Yes, there is no error. But, the classes in ``bases.py`` are not visible at all. If I instantiate for example ``MainBase`` it complains ``NameError: name 'MainBase' is not defined`` – X... Jul 05 '20 at 08:09
  • Python does *allow* circular imports, and support for circular *relative* imports has been gradually improved over several versions. That doesn’t allow time travel, though: your lines of code still have to execute in some order, including the ones which *create* classes and functions. – Davis Herring Jul 05 '20 at 16:10
  • Does this answer your question? [Understanding python's import \* mechanics under circular reference](https://stackoverflow.com/questions/28551513/understanding-pythons-import-mechanics-under-circular-reference) – Davis Herring Jul 05 '20 at 16:17

1 Answers1

2

You have a circular import. In your base module you try to import from extension. But from extension you import base. But base is not finished importing yet so that results in an ImportError when you try to import anything from the extensions module.

Felix He
  • 21
  • 2