Methods and Functions

Python Modules

Python is quickly becoming one of the most popular programming languages. When we create complicated apps and programs, the size of our Python code grows, and as a result, it most likely becomes disorganized over time. Keeping your code in the same file as it grows, on the other hand, makes it tough to maintain and debug. To address these challenges, Python modules assist us in organizing and grouping content through the use of files and folders. Python modules come into play in this modular programming method, where we have separated the code into discrete components. Before we can create Python modules, we must first understand what a module is and why we use it.

What are modules in Python?

Modules in Python are simply files with the “.py” extension that contain Python code such as Python functions, methods, classes, or variables that may be imported into another Python program. A Python module is a file that contains Python commands and definitions. A module is a file that contains Python code, such as myprog.py, and its module name is “myprog”.

A module helps you to structure your Python code logically. Grouping related code into modules makes it easier to comprehend and use the code. Modules allow us to group together related functions, classes, or code blocks in the same file. Instead of copying their definitions into multiple programs, we can define our most frequently used functions in a module and import them.

Let us look at an example of how to create a Python module. To construct a module, we must save the desired code in a file with the file extension “.py”. The name of the Python file is then used as the name of the module. We will create and save the file by the name “program.py

                    

# Python Module program
def add(a, b):
   #This program adds two numbers and return the result
   result = a + b
   print('Sum:', result)

add(10, 5)

In this case, we’ve defined a function called add() within a module called program. The function takes two numbers and returns the total of them.

Advantages of Python modules

Modularizing code in a large application has various advantages Few of them being:

  • Simplicity – Instead of focusing on the full problem, a module often concentrates on a very small section of the problem. When working on a single module, you’ll have a smaller problem domain to think about. This simplifies development and reduces the likelihood of errors.
  • Maintainability – Typically, modules are meant to enforce logical boundaries between distinct issue areas. Modifications to a single module are less likely to have an influence on other portions of the program if modules are written in a way that minimizes interdependence. This makes it more feasible for a large team of programmers to collaborate on a huge application.
  • Reusability – Functionality created in a single module can be easily reused by other portions of the program (via a suitably defined interface). This reduces the requirement for code duplication.
  • Scoping – Modules often specify a separate namespace, which aids in avoiding identifier collisions in different portions of a program.

How to import modules in Python?

Using the import line in another Python source file, we can import the functions and classes defined in one module into another. You must use the import keyword in conjunction with the desired module name. When the interpreter encounters an import statement, it adds the module to your current program. You can access the functions included within a module by using the dot (.) operator in conjunction with the module name.

To import our above-defined module program, we type the following statement in Python prompt:

Then using the module name and the dot (.) operator, we can access the function. As an example:

Output

Python comes with lots of standard modules. Standard modules can be imported in the same way as user-defined modules can. Python provides several sorts of statements for importing modules, which are defined below.

  • Python import statement

This is the most basic approach for importing modules. We can use the import statement to import a module and the dot operator to access the definitions within it, as explained before.

Regardless of how many times a module is imported, it is only loaded once. This avoids the module execution from repeating itself if multiple imports occur.

The syntax for using the import statement is as follows:

                    

import module1, module2,…… module n

Let us look at an example to understand this Python modules import method

                    

# import statement example
# To import standard module math
import math

print('The value of pi is:', math.pi)
print('Square root of 25 is:', math.sqrt(25))

Output

                    

The value of pi is: 3.141592653589793
Square root of 25 is: 5.0

  • Import with renaming

We can also import Python modules by renaming it as per our choices. For example,

                    

# import module by renaming it
import math as m

print('Value of pi:', m.pi)

The math module has been renamed m. In some circumstances, this can save us typing time.  It is worth noting that the term “math” is not recognized in our context. As a result, math.pi is incorrect, whereas m.pi is the right implementation.

  • The from…import statement

The from statement in Python allows you to import particular properties from a module into the current namespace. Instead of importing the entire module into the namespace, Python allows you to import only the characteristics of a module. This can be accomplished by employing the from….import statement.

The syntax followed by this method is as follows:

                    

from  import , ,….

For example

                    

# importing only 2 methods from math module
from math import sqrt, factorial

# if we simply do 'import math', then math.sqrt(16) and math.factorial(6) are required
# else we do not use dot operator
print(sqrt(16))
print(factorial(6))

Output

  • Importing all names

It is also possible to use the following import statement to import all names from a module into the current namespace:

The use of * has both benefits and drawbacks. It is not suggested to use * unless you know exactly what you will require from the module; otherwise, do so.

Python Module Search Path

When a module is imported into Python, the interpreter looks in various places. The interpreter looks for a built-in module first. Then, if no built-in module is identified, Python searches through a list of directories defined in sys.path. The sys.path contains the following locations:

  • The directory in which the input script is stored (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The default installation-dependent directory

                    

import sys
print(sys.path)

Output

                    

['/Users/nd/Documents', '/Library/Frameworks/Python.framework/Versions/
3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/
lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/
lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']

Reloading a module

As previously noted, the Python interpreter only imports a module once during a session. Things become more efficient as a result of this. Here’s an example to demonstrate how this works.

We created a Python module file named example.py having the following line of code:

You can now observe the impact of several imports.

                    

>>>import myexample
Hello World
>>> import myexample
>>> import myexample
>>> import myexample

We can see that our code was only performed once. This means that our module was only imported once.

Now, if our module changed during the program, we’d have to reload it. As a result, if you want to re-execute the top-level code in a module, Python offers a more efficient way to do it. The reload() function can be used. To reload a module, we can use the imp module’s reload() function. We can accomplish this in the following ways:

                    

import imp
import myexample
Hello World

>>> import myexample
>>> imp.reload(myexample)
Hello World
<module 'myexample' from '/Users/nd/Documents/myexample.py'>

The dir() built-in function

The dir() built-in method returns a sorted list of strings containing module names. The names of all the modules, variables, and functions defined in a module are included in the list.

                    

import math

c = dir(math)
print(c)

Output

                    

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

The names of the many functions defined in the module can be seen in the output. The module’s name is stored in the attribute __name__. All characteristics that begin with an underscore are Python default attributes linked with a module.

Using the dir() method without any arguments, we can find all of the names specified in our current namespace.

                    

a = 10
b = 'Python'

import random
print(dir())

Output

                    

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'random']

Frequently Asked Questions

Q1. What are modules in Python?

Python modules are simply files with the “.py” extension that contain Python code such as Python functions, methods, classes, or variables that may be imported into another Python program. A Python module is a file that contains Python commands and definitions. A module is a file that contains Python code, such as myprog.py, and its module name is “myprog”.

A module helps you to structure your Python code logically. Grouping related code into modules makes it easier to comprehend and use the code. Modules allow us to group together related functions, classes, or code blocks in the same file. Instead of copying their definitions into multiple programs, we can define our most frequently used functions in a module and import it.

Q2. How many modules are in Python?

There are 2 types of modules in Python:

  • User-defined modules
  • Built-in modules

Although the actual number varies between distributions, the Python standard library contains well over 200 modules. Not all of these modules are suggested for usage by the average Python programmer; several have specialized purposes related with the Python internal modules and are primarily designed for use by Python developers.

Q3. What is the difference between modules and packages?

  • Modules – A module is a file that contains Python code that is executed at run time for user-specific programming. Python modules are made up of a unit namespace and locally extracted variables.
  • Packages – For any user-oriented code, a package contains the file __init__.py. However, this does not apply to modules in runtime that include user-specific code. The adoption of a well-structured and standard layout for the package facilitates the usage of user-specific tools. It also simplifies runtime executions.

So what distinguishes a Python package from a module. A Python package operates on a library, defining the codes as a single unit of each given function. The modules, on the other hand, are a separate library with built-in functionality. Packages are preferable to modules due to their reusability.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.