Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Python Modules
2.1.
Creating Modules In Python
2.2.
Variables In Module
3.
The Import Statement
3.1.
Renaming a Module During Import
4.
The From Module Import Statement
5.
Python Module Search Path
6.
Reloading a Module
7.
dir() Function
8.
FAQs
9.
Key Takeaways
Last Updated: Mar 27, 2024

Import and Modules in Python

Author ANKIT KUMAR
0 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Modules in the Python programming language are the group of some instructions or functions or statements having a .py extension. For example, the math module, which most of us must have used at least once. If you remember, while using the factorial or sqrt function, we imported the math module, and then we used the functions. Here math is a module where different types of mathematical functions are defined. So to use all those functions, we simply have to import the module, and that's all!

In this article, we shall understand the reason for using modules and how we can create our own modules. Moreover, we shall also learn how the "import" keyword works.

Also See, Floor Division in Python.

Also See, Python Round Function.

Python Modules

We have already defined what a module is in the Python programming language. In real-world software programming, there can be thousands of lines of code in a project. It can become very tedious to manage and debug. Now, consider a situation where a certain segment of code is being used again and again. It is a very bad practice to write the same code again and again. A good idea would be to put that segment of code in a module and use it whenever required without having to code it again and again. 

Check this out, python ord

Creating Modules In Python

We all must have used the math module in Python at least once. Let's now create our own module.

def multiply(first, second):
   result = first * second
   return result

The above code defines a simple method multiply, which takes two numbers as parameters and returns the product of the two numbers. In order to make it a module, all we need to do is save it as "module_name.py". We can save it as mult.py, where mult is the name which is provided by the user and .py is the extension denoting that the file is a module.

Now that we have saved the module, it's time to use it. To use the module, we need to import it. Importing a module is a very simple process. We just need to write the import keyword followed by the module name.

Example: 

import mult
product = mult.multiply(2,6)
print(product)

Explanation:

  • We first import the mult module which we created earlier.
  • We call the multiply function using the module name and store the result in the product variable.
  • To call a function, we must call it using module_name.function().
  • Finally, the result is displayed as 12 at the console.

Variables In Module

Modules not only contain functions but also variables of all types such as arrays, objects, dictionary, etc.

Example:

myCar = {
  "brand": "TATA",
  "model": "Safari-Gold",
  "price": "40 lacs"
}

We save the above code as car.py

We can now import the car module and get the model name like this:

import car
modelName =car.myCar["model"]
print(modelName)
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

The Import Statement

After we have learned all about modules, it is important to understand how we can use them in Python. When we use the math.sqrt() function, we first import the math module. The import keyword is used to access all the functions and attributes of the module.

Syntax:

import name_of_the_module

Example:

import math
val = math.sqrt(25)
print(val)

Output:

5.0

Renaming a Module During Import

We can also rename the module while we try to import that module.

Example:

import math as m
val = m.factorial(6)
print(val)

Explanation:

We rename the math module as 'm'. Now wherever we were supposed to use math, we can simply replace that with m. Like instead of math.factorial(6), we use m.factorial(6). The output will be 720. Using math instead of m will give an error.

Example:

import math as m
val = math.factorial(6)
print(val)

Output:

NameError: name 'math' is not defined

 

Also See, Intersection in Python.

Must Read Invalid Syntax in Python.

The From Module Import Statement

This is another way to import specific functions or names from the module instead of importing the entire module.

Syntax: from module_name import required_function

Example: Instead of importing the entire math module, we can only import the sqrt() function.

from math import sqrt
val= sqrt(25)
print(val)

Output:

5.0

Explanation:

Instead of writing import math, we can write from math import sqrt.

Also see, Merge Sort Python and Convert String to List Python.

Python Module Search Path

Whenever we import a module in Python, the interpreter tries to find out the desired module having a .py extension. The order of search is in the following order:

  • The current directory
  • The list of directories contained in the PYTHONPATH environment variable, if it is set.
  • It looks into the installation-dependent default directory.
  • If the module does not exist, it will display an error.

Reloading a Module

A module is loaded only once in Python regardless of the number of times we try to import it. In case some changes are made in the module, and we want to import the module again, one way is to run the program again. Another efficient method is to use the reload() function provided by Python.

The reload() function is present in the imp module in Python.

Syntax:

imp.reload(module_name)

dir() Function

The dir() function is used to get the sorted list of all the variables, functions, and sub-modules (if any) present in a module.

Example:

import math
insideMathModule= dir(math)
print(insideMathModule)

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']

 

You can practice by yourself with the help of online python compiler.

Must read: Python Square Root

FAQs

  1. What are modules in the Python programming language?
    Modules in the Python programming language are the group of some instructions or functions or statements having a .py extension.
     
  2. Why do we use modules?
    It is used to divide large programs or codes into manageable segments, which is easy to handle and debug. Reusability of code becomes easy with modules.
     
  3. How can we create a module in Python?
    We can simply save our code file with the .py extension to make it a module.
     
  4. How can we use the modules in Python?
    We can use the modules by using the import keyword followed by the module name to import the module into our current project.
     
  5. Which function is used to list all the names present in a module?
    The dir() function is used for this purpose.

Key Takeaways

  • Modules in the Python programming language are the group of some instructions or functions or statements having a .py extension.
  • Modules not only contain functions but also variables of all types such as arrays, objects, dictionary, etc.
  • The import keyword is used to access all the functions and attributes of the module.
  • The reload() function is used to load the module again.
  • The dir() function is used to get the sorted list of all the variables, functions, and sub-modules (if any) present in a module.

Never stop learning. Explore more here.

Happy learning!

Next article
Difference Between Module and Package in Python
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass