Home > Software engineering >  How to use a module inside a folder directly in python?
How to use a module inside a folder directly in python?

Time:01-13

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()

why is np.linalg.inv() not working when the code:

from noobpy import linalg
linalg.inv()

is working

CodePudding user response:

When you use import, it expects a package or module, whereas the keyword from expects a module, subpackage, class or a function. One simple way to fix is to add __init__.py file in your directory noobpy and inside __init__.py you should add import noobpy.linalg

Once you are done with this you can use

import noobpy as np
np.linalg.inv()

in your main file.

Note that __init__.py makes a directory package and acts like a constructor and does the prerequisites that are defined in this constructor for import to work.

  •  Tags:  
  • Related