Interdependence of modules in python packages

Viewed 217

I have created a package called 'pkg' and it looks like this:

pkg/
    __init__.py
    mod1.py
    mod2.py

__init__.py is empty.

mod1.py contains only one function and looks like this.

# mod1.py

def my_sqrt(x):

    s = 5 # initialize at 5
    while abs(x - s**2) > 0.00001:
        s = (s+x/s)/2
    return s

mod2.py contains a function that uses the function my_sqrt from mod1.py and looks like this.

# mod2.py

def fourth_root(x):
    return my_sqrt(my_sqrt(x))

Now when I run

from pkg import *
my_sqrt(9)

I get output of 3.000000001396984 as desired but if I then run

fourth_root(81)

I get an error ModuleNotFoundError: No module named 'mod1'. Even if I add the following line in mod2.py,

from mod1 import my_sqrt

It still doesn't work and throws the following error: NameError: name 'my_sqrt' is not defined.

Due to some logical structure, I want to define the functions my_sqrt and fourth_root in separate modules. How do I do that and not get an error. I am having a hard time understanding how to arrange my package so that these interdependence between modules are taken care of.

2 Answers

Import all methods from mod1.py and mod2.py at pkg level.

init.py should look like below to achive what u want.

from mod1 import my_sqrt
from mod2 import fourth_root

Import the methods from mod1.py and mod2.py in init.py

init.py should look like this.

from .mod1 import my_sqrt
from .mod2 import fourth_root
__all__ = [my_sqrt, fourth_root]
Related