View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Python Modules: Import, Create, and Use Built-in Modules

Updated on 28/05/20254,974 Views

Python modules are files containing Python code that can be imported and used. They help organize code into separate files for better management. Modules contain functions, classes, and variables that solve specific programming tasks. Using Python modules makes your code more organized and reusable. You can write code once and use it many times. This saves development time and reduces errors in your programs.

Python comes with many built-in modules, such as OS, math, and time. You can also create custom modules for your specific needs. Learning how to import a module in Python is essential for every programmer. 

Modules make complex projects easier to handle and maintain. They promote code reusability across different programs and projects. Many online Software Engineering courses teach modules as fundamental programming concepts.

What is a Module in Python with an Example

A module in Python is a file containing Python statements and definitions. The file name becomes the module name with the .py extension removed. Modules help group related functions and classes together in one place.

Here's a simple example of what module is in Python with an example:

# Create a file named calculator.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

PI = 3.14159

You can use this module in another Python file:
import calculator

result = calculator.add(5, 3)
print(result)
print(calculator.PI)

Output:

8

3.14159

Python modules serve as containers for reusable code components. They prevent naming conflicts between different parts of your program. Modules also make debugging easier by organizing code logically.

Take your skills to the next level with these highly rated courses.

How to Import a Module in Python

Learning how to import a module in Python is crucial for code organization. Python provides several ways to import modules into your programs. Each method has specific use cases and benefits for different situations.

The basic import statement loads the entire module into your program. You access module contents using dot notation after the module name. This method keeps the namespace clean and prevents naming conflicts.

import math
result = math.sqrt(16)
print(result)

Output:

4.0

Different Import Methods in Python

Python offers multiple ways to import modules based on your needs. Here are the most common import methods with practical examples:

1. Import Entire Module:

import os
current_directory = os.getcwd()

2. Import with Alias:

import datetime as dt
today = dt.date.today()

3. Import Specific Functions:

from math import sqrt, pow
result = sqrt(25)  # No need for math.sqrt()

4. Import All Contents (Not Recommended):

from time import *
sleep(1)  # Direct access to sleep function

5. Import Multiple Items:

from os import path, getcwd, listdir

Each import method serves different programming scenarios effectively. Choose the method that makes your code most readable and maintainable.

Also read: Python Modules: Explore 20+ Essential Modules and Best Practices

Python Built-in Modules

Python built-in modules come pre-installed with the Python installation. These modules provide essential functionality for common programming tasks. You don't need to install anything extra to use Python's built-in modules.

Python includes over 200 built-in modules in its standard library. These modules cover areas like file handling, mathematics, networking, and data processing. Understanding Python built-in modules helps you write efficient code quickly.

Here's a comparison table of popular Python built-in modules:

Module

Purpose

Common Functions

Use Cases

os

Operating system interface

getcwd(), listdir(), mkdir()

File operations, directory management

math

Mathematical functions

sqrt(), sin(), cos(), pi

Scientific calculations

time

Time-related functions

sleep(), time(), strftime()

Time delays, formatting

re

Regular expressions

search(), match(), findall()

Pattern matching, text processing

random

Random number generation

randint(), choice(), shuffle()

Games, simulations, sampling

json

JSON data handling

loads(), dumps(), load()

API communication, data storage

Python OS Module

The Python os module provides functions for interacting with the operating system. It handles file operations, directory management, and system environment variables. The Python os module works across different operating systems seamlessly.

Common python os module functions include:

import os

# Get current working directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")

# List files in directory
files = os.listdir('.')
print(f"Files: {files}")

# Create new directory
os.mkdir('new_folder')

# Check if path exists
exists = os.path.exists('new_folder')
print(f"Folder exists: {exists}")

# Get environment variable
home = os.getenv('HOME')
print(f"Home directory: {home}")

The Python os module also handles file permissions and path manipulations. It provides cross-platform compatibility for file system operations. This module is essential for file management and system administration tasks.

Python Math Module

The Python math module provides mathematical functions and constants for calculations. It includes trigonometric functions, logarithms, and mathematical constants like pi. The Python math module handles complex mathematical operations efficiently.

Essential Python math module functions:

import math

# Basic mathematical operations
print(f"Square root of 16: {math.sqrt(16)}")
print(f"2 to the power 3: {math.pow(2, 3)}")
print(f"Value of pi: {math.pi}")

# Trigonometric functions
print(f"Sin of 90 degrees: {math.sin(math.radians(90))}")
print(f"Factorial of 5: {math.factorial(5)}")

Output:

Square root of 16: 4.0

2 to the power 3: 8.0

Value of pi: 3.141592653589793

Sin of 90 degrees: 1.0

Factorial of 5: 120

The Python math module handles floating-point arithmetic with high precision. It provides both basic and advanced mathematical functions for scientific computing. This module is perfect for engineering and scientific applications.

Python Time Module

The Python time module handles time-related operations in Python programs. It provides functions for time delays, formatting, and timestamp operations. The Python time module helps manage timing in your applications effectively.

Key Python time module functions:

import time

# Get current timestamp
current_time = time.time()
print(f"Current timestamp: {current_time}")

# Format current time
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted time: {formatted_time}")

# Sleep for 2 seconds
print("Sleeping for 2 seconds...")
time.sleep(2)
print("Done sleeping!")

# Get local time
local_time = time.localtime()
print(f"Local time: {local_time}")

Output:

Current timestamp: 1716364800.123456

Formatted time: 2024-05-22 10:30:00

Sleeping for 2 seconds...

Done sleeping!

Local time: time.struct_time(tm_year=2024, tm_mon=5, tm_mday=22, tm_hour=10, tm_min=30, tm_sec=0, tm_wday=2, tm_yday=143, tm_isdst=0)

The Python time module supports different time zones and formats. It handles time calculations and conversions between different representations. This module is essential for scheduling and time-based applications.

Check out: Python timeit(): How to Time Your Code (2025)

What are Modules and Packages in Python

Understanding what is module and package in Python helps organize large projects. A module is a single Python file with .py extension. A package is a directory containing multiple modules and an init.py file.

Modules contain related functions, classes, and variables in one file. Packages group related modules together in a directory structure. This hierarchy helps manage complex applications with many components.

Here's the difference between modules and packages:

Module Structure:

calculator.py  # This is a module

Package Structure:

math_package/          # This is a package
    __init__.py
    basic.py          # Module inside package
    advanced.py       # Another module
    geometry/         # Sub-package
        __init__.py
        shapes.py

Using package modules:

from math_package import basic
from math_package.geometry import shapes

result = basic.add(5, 3)
area = shapes.circle_area(5)
print(result)
print(area)

Output:

8

78.53981633974483

Packages enable the hierarchical organization of large codebases effectively. They prevent naming conflicts between modules with similar names. Understanding what is module and package in Python improves code structure significantly.

How to Make a Python Module

Learning how to make a Python module helps create reusable code. Creating modules involves writing functions and classes in separate files. You can then import these modules into other Python programs.

Here's how to make a Python module step by step:

  1. Create a new Python file with .py extension
  2. Write functions, classes, or variables inside the file
  3. Save the file in your project directory
  4. Import the module in other Python files

Creating Custom Modules

Creating custom modules starts with writing Python code in separate files. Name your module file with a descriptive name and .py extension. This file becomes your custom module for specific functionality.

Example: Creating a custom utility module (utils.py):

# utils.py - Custom module file
def greet(name):
    return f"Hello, {name}!"

def calculate_area(length, width):
    return length * width

def is_even(number):
    return number % 2 == 0

VERSION = "1.0.0"

Using the custom module:
import utils

# Use functions from custom module
message = utils.greet("Alice")
print(message)

area = utils.calculate_area(5, 3)
print(f"Area: {area}")

check = utils.is_even(4)
print(f"Is 4 even? {check}")

print(f"Module version: {utils.VERSION}")

Output:

Hello, Alice!

Area: 15

Is 4 even? True

Module version: 1.0.0

Custom modules should focus on specific functionality or related functions. This makes them easier to maintain and reuse across projects. Good module design improves code organization and development efficiency.

Must explore: Python While Loop Statements: Explained With Examples

Which Module in Python Supports Regular Expressions

The 're' module in python supports regular expressions for pattern matching. This module provides functions to search, match, and manipulate text patterns. Understanding which module in python supports regular expressions helps with text processing tasks.

The 're' module offers powerful text processing capabilities through pattern matching. It can find specific patterns, validate input formats, and extract data. Python Regular expressions work with strings to perform complex search operations.

Common 're' module functions:

import re

text = "Contact us at support@email.com or sales@company.org"

# Find all email addresses
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
print(f"Found emails: {emails}")

# Check if text matches pattern
phone = "123-456-7890"
pattern = r'\d{3}-\d{3}-\d{4}'
match = re.match(pattern, phone)
print(f"Phone format valid: {match is not None}")

# Replace patterns
new_text = re.sub(r'@\w+\.', '@example.', text)
print(f"Modified text: {new_text}")

# Split text by pattern
words = re.split(r'\s+', "Hello   world    python")
print(f"Split words: {words}")

Output:

Found emails: ['support@email.com', 'sales@company.org']

Phone format valid: True

Modified text: Contact us at support@example.com or sales@example.org

Split words: ['Hello', 'world', 'python']

The 're' module handles complex text processing tasks efficiently. It supports advanced pattern matching with metacharacters and groups. This module is essential for data validation and text manipulation.

Common Python Module Operations

Python modules support various operations for effective code management. These operations include importing, reloading, and inspecting module contents. Understanding common operations helps you work with modules efficiently.

Module Inspection Operations:

import math
import sys

# Get module documentation
print("Math module doc:", math.__doc__[:50])

# List module attributes
attributes = dir(math)
print(f"Math module has {len(attributes)} attributes")

# Check module file location
print(f"Math module file: {math.__file__}")

# Get module name
print(f"Module name: {math.__name__}")

# Check if attribute exists
has_sqrt = hasattr(math, 'sqrt')
print(f"Math has sqrt function: {has_sqrt}")

Output:

Math module doc: This module provides access to the mathematical func

Math module has 66 attributes

Math module file: /usr/lib/python3.9/lib-dynload/math.cpython-39-x86_64-linux-gnu.so

Module name: math

Math has sqrt function: True

Module Path Operations:

import sys

# Check module search paths
print("Python module search paths:")
for path in sys.path[:3]:  # Show first 3 paths
    print(f"  {path}")

# Add custom path for modules
sys.path.append('/custom/module/path')

# Get loaded modules
loaded_modules = len(sys.modules)
print(f"Currently loaded modules: {loaded_modules}")

Output:

Python module search paths:

  /current/working/directory

  /usr/lib/python39.zip

  /usr/lib/python3.9

Currently loaded modules: 156

These operations help debug module-related issues and understand module behavior. They provide insights into module structure and loading mechanisms. Mastering these operations improves your Python development skills.

Must read: Top Python Libraries for Machine Learning for Efficient Model Development in 2025

Practical Code Example: File Manager Module

Problem Statement: Create a file manager module that handles common file operations like reading, writing, and listing files. The module should provide easy-to-use functions for file management tasks.

# file_manager.py - Custom file manager module

import os
import json
from datetime import datetime

def read_file(filename):
    """Read contents of a file and return as string"""
    try:
        with open(filename, 'r') as file:
            return file.read()
    except FileNotFoundError:
        return f"Error: File '{filename}' not found"
    except Exception as e:
        return f"Error reading file: {str(e)}"

def write_file(filename, content):
    """Write content to a file"""
    try:
        with open(filename, 'w') as file:
            file.write(content)
        return f"Successfully wrote to '{filename}'"
    except Exception as e:
        return f"Error writing file: {str(e)}"

def list_files(directory='.'):
    """List all files in specified directory"""
    try:
        files = []
        for item in os.listdir(directory):
            item_path = os.path.join(directory, item)
            if os.path.isfile(item_path):
                size = os.path.getsize(item_path)
                modified = datetime.fromtimestamp(os.path.getmtime(item_path))
                files.append({
                    'name': item,
                    'size': size,
                    'modified': modified.strftime('%Y-%m-%d %H:%M:%S')
                })
        return files
    except Exception as e:
        return f"Error listing files: {str(e)}"

def create_backup(filename):
    """Create backup copy of a file"""
    try:
        if not os.path.exists(filename):
            return f"Error: File '{filename}' does not exist"
        
        backup_name = f"{filename}.backup"
        content = read_file(filename)
        write_file(backup_name, content)
        return f"Backup created: '{backup_name}'"
    except Exception as e:
        return f"Error creating backup: {str(e)}"

# Usage example
if __name__ == "__main__":
    # Test the file manager module
    test_content = "This is a test file for our file manager module.\nIt demonstrates module functionality."
    
    # Write test file
    result = write_file('test.txt', test_content)
    print(result)
    
    # Read test file
    content = read_file('test.txt')
    print(f"File content: {content}")
    
    # List files in current directory
    files = list_files()
    print(f"Files found: {len(files)}")
    for file_info in files[:2]:  # Show first 2 files
        print(f"  {file_info['name']} - {file_info['size']} bytes")
    
    # Create backup
    backup_result = create_backup('test.txt')
    print(backup_result)

Output:

Successfully wrote to 'test.txt'

File content: This is a test file for our file manager module.

It demonstrates module functionality.

Files found: 15

  test.txt - 87 bytes

  file_manager.py - 2341 bytes

Backup created: 'test.txt.backup'

Explanation:

This file manager module demonstrates the practical Python modules. The module contains four main functions for common file operations. Each function handles errors gracefully and returns meaningful messages.

The module uses python os module for file system operations. It also imports datetime for timestamp formatting and json for potential data handling. This shows how modules can work together effectively.

The if __name__ == "__main__": block allows testing the module directly. This is a common pattern in python modules for testing functionality. When imported, this test code won't run automatically.

Conclusion

Python modules serve as essential building blocks that enable organized and reusable code development. They help developers create maintainable applications by providing proper separation of code functionality. Understanding how to import existing modules and create custom ones significantly improves your programming efficiency.

Built-in modules like os, math, and time deliver powerful, ready-to-use functionality for common tasks. Learning these fundamental modules saves valuable development time while ensuring reliable and consistent code performance. Mastering Python modules effectively opens doors to advanced programming concepts and superior software design practices.

FAQs

1. What is the difference between import and from import in Python? 

The import statement imports the entire module and requires dot notation to access functions. For example, import math requires math.sqrt() to use the sqrt function. The from import statement imports specific functions directly into your namespace. Using from math import sqrt allows you to call sqrt() directly without the module prefix.

2. How do you create a Python module?

Creating a Python module involves writing Python code in a .py file. Save functions, classes, and variables in the file with a descriptive name. Place the file in your project directory or Python path. You can then import and use the module in other Python files using the import statement.

3. What are Python built-in modules? 

Python built-in modules are pre-installed modules that come with Python installation. These include os, math, time, re, json, and many others. They provide essential functionality for common programming tasks like file operations, mathematical calculations, and text processing. No additional installation is required to use these modules.

4. How to import a specific function from a module in Python?

Use the from module_name import function_name syntax to import specific functions. For example, from math import sqrt, pow imports only sqrt and pow functions. This approach reduces memory usage and provides direct access to functions. You can also use aliases like from datetime import datetime as dt.

5. What is the difference between a module and a package in Python? 

A module is a single Python file containing code that can be imported. A package is a directory containing multiple modules and an __init__.py file. Packages organize related modules in a hierarchical structure for better code management. Packages can contain sub-packages and multiple modules working together.

6. Which Python module is used for regular expressions? 

The re module in Python handles regular expressions for pattern matching. It provides functions like search(), match(), findall(), and sub() for text processing. This module supports complex pattern matching with metacharacters and groups. Regular expressions are powerful tools for data validation and text manipulation tasks.

7. How do you check what functions are available in a Python module?

Use the dir() function to list all attributes and functions in a module. For example, dir(math) shows all available functions in the math module. You can also use help(module_name) for detailed documentation about the module. The __doc__ attribute provides module documentation and usage information.

8. What is the Python os module used for?

The Python os module provides functions for interacting with the operating system. It handles file operations, directory management, and environment variables across different platforms. Common functions include getcwd(), listdir(), mkdir(), and path operations. This module is essential for file system manipulation and system administration tasks.

9. How do you import a module from a different directory in Python? 

Add the directory path to sys.path before importing the module. Use sys.path.append('/path/to/directory') to add the directory. Alternatively, create a package structure with __init__.py files for proper organization. You can also set the PYTHONPATH environment variable to include custom directories.

10. What is the Python math module used for?

The Python math module provides mathematical functions and constants for calculations. It includes basic operations like sqrt(), pow(), and factorial(). The module also offers trigonometric functions, logarithms, and constants like pi and e. This module is essential for scientific computing and mathematical applications requiring precision.

11. How do you reload a module in Python? 

Use importlib.reload(module_name) to reload a module after making changes. First import importlib, then call reload with the module as parameter. This is useful during development when you modify module code frequently. Note that reloading doesn't affect objects already created from the original module.

12. What happens when you import a module in Python? 

When you import a module, Python searches for the module file in the module search path. It executes the module code and creates a module object in memory. The module becomes available in your current namespace for use. Python caches the module to avoid re-executing it on subsequent imports.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.