1

Directory Structure:

| Packages
    | noobpy
        | __init__.py
        | linalg.py
    | main.py

linalg.py:

def inv():
    print("inv called")

main.py :

import noobpy as np
np.linalg.inv()

In __init__.py:

when I use:

import linalg

It throws in the error that "No module named 'linalg'", when running main.py

but when I use:

from . import linalg

inside of _init_ ,it works just fine, even though I can call linalg.inv inside of _init_ in both the cases.

Pranav
  • 11
  • 4
  • which file do you run ? main.py ? – S.B Jan 12 '22 at 14:07
  • @SorousHBakhtiary , yes. – Pranav Jan 12 '22 at 14:09
  • @Pranav I get different error : `No module named 'linalg'`. Are you run it with Pycharm ? because I think Pycharm will automatically add the workspace to the environment variable – S.B Jan 12 '22 at 14:10
  • @SorousHBakhtiary , yes , I have corrected it in the question as well, I dont know why the first time it showed the error differently. – Pranav Jan 12 '22 at 14:14

1 Answers1

0

(Posting as a comment before closing as a duplicate.)

When you run main.py, there are certain directories added to the Python search path where the import mechanism will look for module. The directory main.py itself is in is added to the path. In this case, it only contains the package noobpy. The directory noobpy itself, you must note, is not on the search path.

When you try to use the absolute import linalg, no directory on the search path contains a module named linalg, so the import fails.

When you try to use the relative import from . import lining, the . refers to the current package, which is noobpy itself, and noobpy does contain the module linalg.

chepner
  • 497,756
  • 71
  • 530
  • 681