1

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?

S.B
  • 13,077
  • 10
  • 22
  • 49
leo_val
  • 150
  • 8
  • https://stackoverflow.com/a/50194143/3155240 - also apparently `...` is supported to go up 2 directories. – Shmack Aug 19 '22 at 17:47
  • I wanted to use these sub-modules as a way to better organize all my functions by categories (math, statistics, algorithms, etc). Is there a better way to make this organization functional? – leo_val Aug 19 '22 at 17:58

1 Answers1

0

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.

S.B
  • 13,077
  • 10
  • 22
  • 49