Python 3x Pandas Django

Python Modules


You have seen how you can reuse code in your program by defining functions once. what if you wanted to reuse a number of functions in other programs that you write? As you might have guessed, the answer is Modules.

There are various methods of writing modules, but the simplest way is to create a file with .py extension that contains functions and variables.

and, Another method is to write the modules in the native langauge in which the python interpreter itself was written.

A module can be imported by another program to make use of its functionality. This is how we can use the python standard library as well. First we will see how to use the standard library modules.

#Filename:example1.py

import math

print(math.pi)  #Output: 3.141592653589793

How It Works

First, we import the math module using import statement. Basically, this translates to us telling python that we want to use this module. the math module contains functionality related to the python interpreter and it's environment (i.e) the system. When python executes the import math statement, it looks for the math module.

In this case, it is one of the built-in modules, and hence python knows where to find it

If it was not a complied module i.e. a module written in python, then the python interpreter will search for it in the directories listed in it sys.path variable. If the module is found, then the statements in the body of that module are run and the module is made available for you to use.

Finally, print math.pi constant returns the value of PI: 3.141592653589793

Making Your Own Math Module

First, Create a math_example.py file with a constant pi value

#Python File C:\Users\user\math_example.py

global pi

pi = 3.141592653589793

and create a module_example.py file with an import math_example module

#Python File C:\Users\user\module_example.py

import math_example

print(math_example.pi)    #Output: 3.141592653589793

In the above example, you have seen how to import constant from another program and now, we are going to see how to import functions from another program

Import Functions

Create a math_operators_example.py file with a math operations

#Python File C:\Users\user\math_operators_example.py

def sum_two_number(a, b):
  return a + b
def sub_two_number(a, b):
  return a - b
def mul_two_number(a, b):
  return a - b


and create a math_operations_example.py file with an import math_operators_example module

#Python File C:\Users\user\math_operations_example.py

import math_operators_example

print(math_operators_example.sum_two_number(10, 20))    #Output: 30
print(math_operators_example.sub_two_number(10, 20))    #Output: -10
print(math_operators_example.mul_two_number(10, 20))    #Output: 200

The from...import...statement

from math_operators_example import sum_two_number

print(sum_two_number(10, 20))    #Output: 30

In this way, we can use only sum_two_number function as from math_operators_example import sum_two_number statement will import the sum_to_number functionality alone

If we want to import all the functions and constant from math_operators_example file then, we have use either from math_operators_example import * or import math_operators_example

from... import *

from math_operators_example import * 

print(sum_two_number(10, 20))    #Output: 30
print(sub_two_number(10, 20))    #Output: -10

import math_operators_example

import math_operators_example

print(math_operators_example.sum_two_number(10, 20))    #Output: 30
print(math_operators_example.sub_two_number(10, 20))    #Output: -10

__name__ Special Built-In Module's

__name__ is a built-in variable which evaluates to the name of the current module.

It can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below

In the example below is a stand-alone python script which is not referring to any other script, the value of __name__ variable is equal to __main__.

Example1:

#Example1.py
class TwoNumber:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2


    def sum_numbers(self):
        return print(f'Sum of {self.num1} + {self.num2} = { str(self.num1 + self.num2)}')

print(__name__)                 #__main__
if __name__ == "__main__" :
    obj1 = TwoNumber(10, 20)
    obj1.sum_numbers()          #Sum of 10 + 20 = 30

Output1:

__main__
Sum of 10 + 20 = 30

Example2:

#Example2.py
from Example1 import TwoNumber

print(__name__)                     #__main__
if __name__ == "__main__" :
    obj1 = TwoNumber(10, 20)
    obj1.sum_numbers()              #Sum of 10 + 20 = 30

Output2:

Example1                      #This output line from Example1.py print(__name__)
__main__                      #This output line from Example2.py print(__name__)
Sum of 10 + 20 = 30

In the example above, importing one python script into another. In such a scenario, there seem to be two different scopes which can be considered as the main() function. The first scope can be the __main__ variable of the currently running program and the second the scope of the __main__ variable of the imported script used in the current program.

Python Module Index from Python Docs

Python Package

A package is a collection of Python modules.

It is basically a directory with Python files and a file with the name __init__.py. This means that every directory inside of the Python path, which contains a file named __init__.py, will be treated as a package by Python. It's possible to put several modules into a Package.

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!