PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 27, 2022

[FIXED] How to use a module inside a folder directly in python?

 November 27, 2022     import, module, python, python-3.x     No comments   

Issue

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


Solution

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.



Answered By - Trilokinath Modi
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing