Importing and Creating Modules in Python
#Importing Creating Modules in Python
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.
A module in Python is simply a .py
file containing Python definitions, functions, classes, or variables.
Reusability of code
Better organization
Avoids duplication
Easier debugging and maintenance
Python provides multiple ways to import modules:
import math
print(math.sqrt(16)) # Output: 4.0
Here, we import the math
module and use its sqrt()
function.
import math as m
print(m.pi) # Output: 3.141592653589793
The alias makes the module name shorter and easier to use.
from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793
This method imports only the required functions/variables.
from math import *
print(factorial(5)) # Output: 120
⚠️ Not recommended in large projects as it may cause conflicts.
You can create your own module by writing Python code in a file with a .py
extension.
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
dir()
FunctionThe dir()
function helps you see all the attributes and functions available in a module.
import math
print(dir(math))
Use aliases for long module names.
Import only what you need.
Keep custom modules small and organized.
Avoid circular imports.
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.