0

I have the following structure

folder/
├─ subfolder/
│  ├─ __init__.py
│  ├─ script.py
├─ __init__.py
├─ module.py

Inside script.py I want to import the function my_function from module.py. I have tried various variants

from ..module import my_function
from ...folder.module import my_function
from .. import module         # and then use module.my_function
from ... import folder.module # and then use folder.module.my_function

However, whenever I am in the terminal inside folder and run python3 subfolder/script.py I get the error

ImportError: attempted relative import with no known parent package
Physics_Student
  • 556
  • 2
  • 9
  • 1
    `python3 subfolder/script.py` runs `script.py` as a top-level script that _is not associated with a package_. You probably mean to use `python3 -m folder.subfolder.script`, assuming that `folder` is your intended top-level package. – Brian61354270 Feb 09 '23 at 16:31
  • 2
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – Brian61354270 Feb 09 '23 at 16:32
  • 1
    Also, remember that Python imports **do not** navigate your filesystem. Imports are only resolved by searching the Python path. If you want `folder` to be an importable package, it's containing directory must be on the Python path. This is generally done either by installing your project as a distribution package or by relying on having the parent directory of `folder` be your CWD. All modules named in imports inside your package need to follow the package structure. E.g., there is no module named `script`, only one named `folder.subfolder.script`. – Brian61354270 Feb 09 '23 at 16:35

0 Answers0