pythonpython-3.xpython-packaging

Facing an issue with executing python package


I am learning python packages but I am stuck with this issue: I created one package folder "SamplePack". Inside this folder, I have added 2 module files with .py extension and an __ init __.py file as a constructor as below:

Mod2.py

from math import *

def sqroot(x):
    return sqrt(x)

def sine(x):
    return sin(x)

def cos(x):
    return cos(x)

def power(x,y):
    return pow(x,y)

Mod1.py

def Add(x,y):
    return x+y

def Div(x,y):
    return x-y

def function():
    x=input("What's your name? ")
    y=input("Great", x, "What's your phone number? ")

__ init __.py

import Mod1
import Mod2

Post this, I created the package source file from which I will execute these package modules.

Packuse.py

import SamplePack as sp

sp.Mod1.Add(20,20)
sp.Mod2.sqrt(30)
sp.Mod1.function()

When I executed the Packuse.py file through python prompt. I got this error:

C:\Users\Program>python packuse.py Traceback (most recent call last): File "C:\Users\Program\packuse.py", line 1, in import SamplePack as sp File "C:\Users\Program\SamplePack_init_.py", line 1, in import Mod1 ModuleNotFoundError: No module named 'Mod1'


Solution

  • So here's your file architecture :

    Program
    ├- packuse.py
    └- SamplePack
       ├- __init__.py
       ├- Mod1.py
       └- Mod2.py
    

    You're launching your code from the Program directory, So the working directory is Program.

    When you import SamplePack from packuse.py, it looks through the working directory for a directory named SamplePack or a file named SamplePack.py.

    But when you import Mod1 from __init__.py, it also looks through the working directory, wich is always Program, and not SamplePack. So it doessn't find it, because there aren't any Mod1 directory or Mod1.py file in Program.

    What you need to do is to precise that the import system should look for the specified package or module, starting from the package directory (in this case, SamplePack).

    Here's how to do it :

    __init__.py :
    from . import Mod1
    from . import Mod2
    

    The . indicates that it should looks from the actual file's parent directory, and not from the working directory. Note that this only works in package files.