Importing and Creating Modules in Python

8/16/2025

#Importing Creating Modules in Python

Go Back

Importing and Creating Modules in Python: A Complete Guide

Introduction

Modules in Python are files that contain reusable code. Instead of writing everything from scratch, you can import modules to use built-in or custom functionalities. Python comes with a rich set of standard modules, and you can also create your own to organize code effectively.

In this article, we’ll explore how to import modules in Python, types of imports, and how to create your own custom module with examples.


#Importing  Creating Modules in Python

What is a Module in Python?

A module in Python is simply a .py file containing Python definitions, functions, classes, or variables.

Benefits of Using Modules:

  • Reusability of code

  • Better organization

  • Avoids duplication

  • Easier debugging and maintenance


Importing Modules in Python

Python provides multiple ways to import modules:

1. Importing the Entire Module

import math

print(math.sqrt(16))  # Output: 4.0

Here, we import the math module and use its sqrt() function.


2. Importing with an Alias

import math as m

print(m.pi)  # Output: 3.141592653589793

The alias makes the module name shorter and easier to use.


3. Importing Specific Functions or Variables

from math import sqrt, pi

print(sqrt(25))  # Output: 5.0
print(pi)        # Output: 3.141592653589793

This method imports only the required functions/variables.


4. Importing All Functions

from math import *

print(factorial(5))  # Output: 120

⚠️ Not recommended in large projects as it may cause conflicts.


Creating a Custom Module in Python

You can create your own module by writing Python code in a file with a .py extension.

Example: my_module.py

def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

Now, you can import and use it in another file:

import my_module

print(my_module.greet("Shubham"))  # Output: Hello, Shubham!
print(my_module.add(5, 3))         # Output: 8

Using the dir() Function

The dir() function helps you see all the attributes and functions available in a module.

import math
print(dir(math))

Best Practices for Using Modules

  • Use aliases for long module names.

  • Import only what you need.

  • Keep custom modules small and organized.

  • Avoid circular imports.


Conclusion

Modules are an essential part of Python programming. With built-in modules, third-party modules, and custom modules, you can write cleaner, reusable, and more efficient code. Mastering module importing and creation is key to becoming a professional Python developer.

Table of content