Search code examples
pythonimporterror

Python won't import parent package within a subpackage


Here is the file structure of my current project:

mechanism
│   .gitignore
│   dataframe.py
│   mechanism.py
│   vectors.py
│   __init__.py
│
├───examples
│       temp.py
│       __init__.py

I would like to be able to use the contents of the parent package in any file under examples. In temp.py, I have the following line:

from ..vectors import Vector

This raises the following error:

Traceback (most recent call last):
  File "C:\Users\gmbra\Downloads\Python Programs\Mechanisms\mechanism\examples\temp.py", line 1, in <module>
    from ..vectors import Vector
ImportError: attempted relative import with no known parent package

I'm not sure what is going on here because I have following the syntax according to section 5.7 found here in the docs. What can I do to fix this?


Solution

  • In a comment you mentioned that you are executing temp.py directly. When you do this, the temp.py package namespace is not considered to be a sub-package of mechanism but instead it’s own package. This is the reason it does not work.

    If you intend to be calling the files from examples directly, it is best to move them out of the package and do from mechanism.vectors import Vector.

    Actually, you might be able to keep it a sub-package and just change the import to the above suggestion.