How to import function in parent folder without importing sys?

Viewed 42

I am trying to import functions from a file inside a folder linked to a parent folder of the file I'm currently in. To clarify, here is the schema of my folders:

/root
  /Math
    linear_algebra.py
  /Algorithms
    gradient_descent.py

Inside the gradient_descent.py file, I want to import a function Vector which is within the linear_algebra.py file. I tried that using:

from ..Math.linear_algebra import Vector

But I get the error:

ImportError: attempted relative import with no known parent package

Is there any way to make this import without using another import, such os or sys?

1 Answers

Based on documentation:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

You're not supposed to run sub-modules as the main module directly when they contain relative imports. If so, you need some hack. (adding paths to sys.path and change the value of __package__ or etc).

But here is a solution without importing sys (or using PYTHONPATH environment variable - which basically adds the path to the sys.path):

  1. change your directory to the parent of root folder.
  2. run your script from there using -m option:
python -m root.Algorithms.gradient_descent

This resolves the from ..Math.linear_algebra import Vector import in gradient_descent.py module.

note: there is no .py at the end.

Related