×

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

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Python md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Python Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

4 minutes read.

Python String center() method

Python String center() method The center() method will center align the string, using a specified character (space is default) as the fill character. Syntax string.center(width[, fillchar]) Parameter width This parameter represents the length of the returned string. fillchar...

1 minute read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

Python Control Statements

Control statements are under the roof topic of loops and loops in python are defined as iteratively and repeatedly working on source code. Loop control statements are defined as they...

3 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

tell() function in Python

Introduction The tell() function in Python is used to return the current position of the file read/write pointer within the file. An integer value is returned by this method, and it...

2 minutes read.