Learn Python – Python Modules- Basic and advance

A python module can be defined as a python software file which carries a python code along with python functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is handled as the module. We may also have a runnable code interior the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the performance of one module into another, we need to have to import the unique module.

Example

In this example, we will create a module named as file.py which carries a characteristic func that consists of a code to print some message on the console.

Let’s create the module named as file.py.

#displayMsg prints a message to the name being passed.   
def displayMsg(name)  
    print("Hi "+name);    

Here, we need to consist of this module into our foremost module to name the technique displayMsg() described in the module named file.

Loading the module in our python code

We need to load the module in our python code to use its functionality. Python presents two kinds of statements as described below.

The import statement
The from-import statement

The import statement

The import assertion is used to import all the performance of one module into another. Here, we ought to note that we can use the performance of any python supply file via importing that file as the module into every other python source file.

We can import multiple modules with a single import statement, but a module is loaded as soon as regardless of the range of times, it has been imported into our file.

The syntax to use the import announcement is given below.

import module1,module2,........ module n  

Hence, if we need to call the function displayMsg() described in the file file.py, we have to import that file as a module into our module as proven in the instance below.

Example:

import file;  
name = input("Enter the name?")  
file.displayMsg(name)  

Output:

Enter the name?John
Hi John

The from-import statement

Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be achieved via the usage of from? import statement. The syntax to use the from-import declaration is given below.

from < module-name> import <name 1>, <name 2>..,<name n>   

Consider the following module named as calculation which carries three features as summation, multiplication, and divide.

calculation.py:

#place the code in the calculation.py   
def summation(a,b):  
    return a+b  
def multiplication(a,b):  
    return a*b;  
def divide(a,b):  
    return a/b;  

Main.py:

from calculation import summation    
#it will import only the summation() from calculation.py  
a = int(input("Enter the first number"))  
b = int(input("Enter the second number"))  
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()  

Output:

Enter the first number10
Enter the second number20
Sum =  30

The from…import declaration is continually better to use if we be aware of the attributes to be imported from the module in advance. It does not let our code to be heavier. We can additionally import all the attributes from a module through the usage of *.

Consider the following syntax.

from <module> import *   

Renaming a module

Python affords us the flexibility to import some module with a specific identify so that we can use this title to use that module in our python source file.

The syntax to rename a module is given below.

import <module-name> as <specific-name>   

Example

#the module calculation of previous example is imported in this example as cal.   
import calculation as cal;  
a = int(input("Enter a?"));  
b = int(input("Enter b?"));  
print("Sum = ",cal.summation(a,b))  

Output:

Enter a?10
Enter b?20
Sum =  30

Using dir() function

The dir() function returns a sorted list of names described in the passed module. This listing incorporates all the sub-modules, variables and features defined in this module.

Consider the following example.

Example

import json  
  
List = dir(json)  
  
print(List)  

Output:

['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__', '__doc__',
'__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

The reload() function

As we have already stated that, a module is loaded as soon as regardless of the quantity of instances it is imported into the python source file. However, if you favor to reload the already imported module to re-execute the top-level code, python gives us the reload() function. The syntax to use the reload() characteristic is given below.

reload(<module-name>)  

for example, to reload the module calculation described in the preceding example, we must use the following line of code.

reload(calculation)  

Scope of variables

In Python, variables are related with two types of scopes. All the variables described in a module contain the global scope until or till it is described within a function.

All the variables defined inside a feature include a local scope that is restrained to this characteristic itself. We can no longer get right of entry to a nearby variable globally.

If two variables are defined with the same name with the two exceptional scopes, i.e., local and global, then the precedence will constantly be given to the neighborhood variable.

Consider the following example.

Example

name = "john"  
def print_name(name):  
    print("Hi",name) #prints the name that is local to this function only.  
name = input("Enter the name?")  
print_name(name)  

Output:

Hi David 

Python packages

The packages in python facilitate the developer with the utility improvement surroundings by way of presenting a hierarchical directory structure where a package carries sub-packages, modules, and sub-modules. The applications are used to categorize the application degree code efficiently.

Let’s create a package named Employees in your home directory. Consider the following steps.

  1. Create a directory with name Employees on route /home.

two Create a python supply file with title ITEmployees.py on the route /home/Employees.

ITEmployees.py

def getITNames():  
    List = ["John", "David", "Nick",    "Martin"]  
    return List;  

three Similarly, create one more python file with title BPOEmployees.py and create a feature getBPONames().

four Now, the listing Employees which we have created in the first step consists of two python modules. To make this directory a package, we need to include one more file here, that is __init__.py which contains the import statements of the modules described in this directory.

__init__.py

from ITEmployees import getITNames  
from BPOEmployees import getBPONames  

5. Now, the directory Employees has grow to be the package containing two python modules. Here we should notice that we ought to have to create __init__.py inner a listing to convert this directory to a package.

6. To use the modules described interior the bundle Employees, we must have to import this in our python supply file. Let’s create a simple python supply file at our domestic directory (/home) which makes use of the modules defined in this package.

Test.py

import Employees  
print(Employees.getNames())  

Output:

['John', 'David', 'Nick', 'Martin']

We can have sub-packages internal the packages. We can nest the packages up to any stage depending upon the utility requirements.

The following photo suggests the listing structure of an utility Library administration system which consists of three sub-packages as Admin, Librarian, and Student. The sub-packages contain the python modules.