×

Python Modules

Python Modules

The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use. In the simple words, a Python file which consists the runnable code is treated as the module.

Modules provide flexibility, reusability to our program. It can organize the code in a logical order. To use the functionality of the module to another program, we must import the specific module. Consider the below example:

We create the module named as module.py

def fun(a,b):
    c = a+b
    return c

We need to import this file into another code, which can be done using the following ways:

  1. The import statement
  2. The from-import statement

The import statement:

The import statement is used to load all the functionality of one module into another. We can use any Python file to import into another Python source file. The syntax is the following:

Syntax:

import module1, module2…module3

Since, we need to call fun (a,b) defined in the file module.py, we have to import that file as a module into our code. For example:

import module
z = module.fun(20,30) # file name with its function name
print("The sum is:",z)

Output:

The sum is: 50

The from-import statement

A module can contain various attributes, and if we require a specific attribute of a module, then it can be done by the from-import statement.           

from module_name import attribute_name

module.py

def sum(a,b):
    c = a+b
    return c
def sub(a,b):
    c = a-b
    return c
def mul(a,b):
    c = a*b
    return c
def div(a,b):
    c = a/b
    return c

myfile.py

from module import mul
z = mul(20,30)
print("The multiplication is:",z)

Output:

The multiplication is: 600

In the above code, we have imported the module.py into current working file.py with the specific function name. If we already know about the attribute which needs to be import then from-import statement is always good.

We can also import all attributes of the module. The syntax is given below:

Syntax:

from  import*

Example

from module import*
x = mul(20,30)
y = sum(20,30)
z = sub(20,30)
a= div(100,4)
print("The
sum is:",y)
print("The
sub is:",z)
print("The
multiplication is:",x)
print("The
division is:",a)

Output:

The sum is: 50
The sub is: -10
The multiplication is: 600
The division is: 25.0 

Renaming a module (Name Alias)

Python provides flexibility to provide a specific name to the module. It can be done by using as keyword. The syntax is given below:

Syntax:

import module as mod
x = mod.mul(20,30)
y = mod.sum(20,30)
z = mod.sub(20,30)
a= mod.div(100,4)
print("The
sum is:",y)
print("The
sub is:",z)
print("The
multiplication is:",x)
print("The
division is:",a)

Output:

The sum is: 50
The sub is: -10
The multiplication is: 600
The division is: 25.0 

Searching Module Location

When we import the module, the Python interpreter searches for the module in the following sequence:

  • It searches in the current directory first.
  • If the module is not found in each directory in the shell variable PYTHONPATH, and if all searches fail, Python checks the default path.

The dir() function

The dir() function is a built-in  function which returns a list of strings containing the names defined by a module.

The list consists of the names of all the modules, variables, and functions that are defined in a module. Following is an example –

import math
x = dir(math)
print(x)

Output:

['__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil',
'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1',
'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot',
'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log',
'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder',
'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

The reload() function

The reload() function reloads a previously imported method.  When we import the module into source file, the code in the top-level portion of a module executes only once.

Therefore, if we want to re-execute the top-level code in a module, we can use the reload() function.

reload()

Scope of Variable

There are two types of the scope of variable in Python. These scopes are:

  • Local Scope: Variables that are defined inside the function contain a local scope and these variable can be accessed only inside the function. We cannot access them globally.
  • Global Scope: Variables that are defined outside the function have a global scope. If the local variable and global variable have the same name, then local variable will shadow the global variable.

Packages in Python

A package is a classified file directory structure that describes a single Python application environment which consists of modules and sub-package, sub sub-package, and so on. The packages are used to categories level code efficiency

Let’s create a package name Students in home directory. Consider the following steps:

  1. Create a directory with name Students on path /home.
  2. Create a python source file with name CSdepartment.py on the path /home/Student.

CSdepartment.py

        def stuNames():
            list = ['Abhinay','Himanshu','Tushar','Raman']
            return list
  • Similarly we can create ECdepartment and BCAdepartment files and can create a functions getECnames() and getBCAnames().
  •  In the first step, a directory Students which contains two python modules. To make this directory in a package; we need to create one more file here named as __init__.py. This contains the import statements of the module defined in this directory.

__init__.py

     from CSdepartment import stuNames
     from ECdepartment import getECnames

  • Now, the directory Students has become the package. We must create __init__.py inside the directory to convert this directory into package.
  • Create a source file main.py at our home directory (/home) to use the modules defined inside the package Student. We must import this in our python source file.

import Students
print(Students.stuNames)

Output:

['Abhinay','Himanshu','Tushar','Raman']

We have sub package inside the packages. We can include sub-packages inside packages up to any level according to requirements of application.

The following image shows the directory structure of an application Library management system which contains three sub-packages as Admin, Librarian, and Student. The sub-packages include the python modules.

Python Modules

Related Topics

Python String replace() method

Python String replace() method The string.replace() method in Python returns a copy of the string with all occurrences of substring old replaced by new. Syntax replace(old, new[, count]) Parameter old: This parameter represents a substring you want to...

2 minutes read.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Python TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Python Linear regression

In this tutorial, we will understand the meaning, usage, and types of Linear Regression. Further, we will comprehend the terms cost function and Optimization. Linear Regression is the widely used Machine...

3 minutes read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

Python: SetBitmap() function in wxPython

SetBitmap() function In the last tutorial, we have discussed about the GetLabelText() function of wx.MenuItem class which is one of the important function of this class. Now, in this tutorial, we...

6 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

5 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Installing Packages in Python

It's critical to understand that the term "package" here refers to a collection of software that must be installed (i.e. as a synonym for a distribution). It has nothing to...

6 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

3 minutes read.