Home > Blockchain >  Python won't import parent package within a subpackage
Python won't import parent package within a subpackage

Time:10-09

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?

CodePudding user response:

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.

CodePudding user response:

temp.py is top script in your project structure, not in a python package. While relative import is the concept of package scope. So you get the error.

Typically, for your scenario, the suggest solution is as next:

temp.py:

from vectors import Vector

execute:

$ cd mechanism
$ PYTHONPATH=. python3 examples/temp.py
  • Related