Monday, March 7, 2022

Adding some import statements

Next, we will explore how to add some import statements to the init file. Let's start with importing the modules inside the init file. In this top-level init file, we will import all functions as shown next:

#__init__ file for package 'masifutil'

from .mycalculator import add, subtract

from .myrandom import random_1d, random_2d

from .advcalc.advcalculator import sqrt, log, ln

Note the use of . before the module name. This is required for Python for the strict use of relative imports. As a result of these three lines inside the init file, the new main script will become simple and the sample code is shown next:

# pkgmain2.py with main function

import masifutil

def my_main():

""" This is a main function which generates two random\

numbers and then apply calculator functions on them """

x = masifutil.random_2d()

y = masifutil.random_1d()

sum = masifutil.add(x,y)

diff = masifutil.subtract(x,y)

sroot = masifutil.sqrt(x)

log10x = masifutil.log(x)

log2x = masifutil.ln(x)

print("x = {}, y = {}".format(x, y))

print("sum is {}".format(sum))

print("diff is {}".format(diff))

print("square root is {}".format(sroot))

print("log base of 10 is {}".format(log10x))

print("log base of 2 is {}".format(log2x))

""" This is executed only if the special variable '__name__' is

set as main"""

if __name__ == "__main__":

my_main()

The functions of the two main modules and the sub-package module are available at the main package level and the developers do not need to know the underlying hierarchy and structure of the modules within the package. This is the convenience we discussed earlier of using import statements inside the init file.

We build the package by keeping the package source code in the same folder where the main program or script resides. This works only to share the modules within a project. Next, we will discuss how to access the package from other projects and from any program from anywhere.

Share:

0 comments:

Post a Comment