×

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

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

How to run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Python Memory Management

In order to manage memory, Python uses a private heap that contains all of its data structures and objects. The Python memory manager is responsible for the internal management of...

11 minutes read.

Python String isalnum() method

Python String isalnum() method The string.isalnum () method in Python returns a boolean value true if all characters in the string are alphanumeric else for any other value it returns false. Syntax String.isalnum() Parameter NA Return This...

1 minute read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Excel Automation with Python

Data analysis is the upcoming technology in the IT sector; this data analysis can be performed easily with the help of data frames or by using excel sheets. The data...

4 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.