Paramclasses Academy - Blog

Tutorials Details

←
Post 13 of 20
→

Python Modules & Packages: Import, Create and Use Modules

Python Modules & Packages: Import, Create and Use Modules

October 17, 2026

Python Modules and Packages: Import, Create and Use Modules

Introduction to Python Modules and Packages

Python provides modules and packages to help developers organize code into reusable and manageable components.

As a Python application grows, keeping every function, class, and variable in a single file can make the project difficult to maintain. Modules and packages help divide a large program into smaller, organized parts.

In this tutorial, you will learn what Python modules and packages are, how to import built-in modules, how to create your own modules, how to use aliases, and how to organize code into packages.

1. What Is a Module in Python?

A module is a Python file containing code such as functions, classes, and variables that can be reused in other Python files.

A Python module normally has a .py extension.

For example, a file named calculator.py can contain mathematical functions that another Python file can import and use.

Example: Creating a Module

Create a file named calculator.py.

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

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

def multiply(a, b):
    return a * b

This file contains three reusable functions.

Now create another file named main.py in the same directory.

import calculator

print(calculator.add(10, 5))
print(calculator.subtract(10, 5))
print(calculator.multiply(10, 5))

Output:

15
5
50

The import calculator statement makes the module available to the program. Its functions can then be accessed using the module name followed by a dot.

2. Why Do We Use Python Modules?

Modules provide several important advantages:

  1. Code Reusability: Use existing functions and classes in multiple files.

  2. Better Organization: Separate related functionality into different files.

  3. Easy Maintenance: Update code in one module without searching through a large file.

  4. Readability: Make applications easier to understand.

  5. Namespace Management: Access names through a module instead of placing every imported name directly in the current namespace.

  6. Team Collaboration: Different developers can work on separate modules.

Modules are useful for small scripts, websites, automation tools, and large Python applications.

3. Types of Python Modules

Python modules are commonly grouped into three categories.

A. Built-in Modules

Built-in modules are provided as part of Python's standard library. Some are implemented in C, while others are implemented in Python.

Examples include:

  • math — mathematical functions and constants.

  • random — random selections and number generation.

  • datetime — dates and times.

  • os — operating-system interfaces.

  • sys — access to interpreter-related information and functionality.

  • json — encoding and decoding JSON data.

Example using the math module:

import math

print(math.sqrt(64))
print(math.factorial(5))
print(math.pi)

Output:

8.0
120
3.141592653589793

B. User-Defined Modules

User-defined modules are created by programmers to organize their own code.

For example, you can create greetings.py containing a reusable greeting function.

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

Then import it into another Python file:

import greetings

print(greetings.greet("Rahul"))

Output:

Hello, Rahul!

C. Third-Party Modules

Third-party modules are created and distributed by developers or organizations outside the Python standard library.

Examples include:

  • requests — making HTTP requests.

  • numpy — numerical computing.

  • pandas — data analysis.

  • flask — building web applications.

  • django — developing web applications.

Many third-party packages can be installed using pip.

For example, to install Requests, run this command in your terminal:

python -m pip install requests

Then use it in a Python file:

import requests

response = requests.get(
    "https://example.com",
    timeout=10
)

print(response.status_code)

This example requires an internet connection and the Requests package to be installed. The actual status code depends on the server response.

4. Different Ways to Import Modules

Python supports several import styles.

A. Import the Entire Module

import math

print(math.sqrt(25))

Output:

5.0

The module name is used to access its members.

B. Import a Specific Function

from math import sqrt

print(sqrt(36))

Output:

6.0

This allows you to use sqrt() directly without writing math.sqrt().

C. Import Multiple Functions

from math import sqrt, factorial

print(sqrt(49))
print(factorial(4))

Output:

7.0
24

D. Import a Module With an Alias

An alias provides a shorter or alternative name for a module.

import math as m

print(m.sqrt(81))
print(m.pi)

Output:

9.0
3.141592653589793

E. Import a Function With an Alias

from math import factorial as fact

print(fact(5))

Output:

120

F. Using from module import *

Python also supports wildcard imports.

from math import *

print(sqrt(16))

Although this syntax is valid, it is generally discouraged in professional code because it can introduce unexpected names and make the origin of functions less clear.

Prefer import module or import specific names when appropriate.

5. How to Create Your Own Python Module

Let's create a reusable module for calculating areas.

Step 1: Create a File

Create a file named area.py.

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

def square_area(side):
    return side * side

def triangle_area(base, height):
    return 0.5 * base * height

Step 2: Create the Main Program

Create a second file named main.py in the same directory.

import area

print("Rectangle Area:", area.rectangle_area(10, 5))
print("Square Area:", area.square_area(4))
print("Triangle Area:", area.triangle_area(6, 8))

Output:

Rectangle Area: 50
Square Area: 16
Triangle Area: 24.0

Step 3: Run the Main File

Open a terminal in the project directory and run:

python main.py

If your system uses the py launcher on Windows, you can also run:

py main.py

The main program imports the area module and reuses its functions.

6. The __name__ Variable and __main__

Python provides a special variable named __name__.

When a Python file is executed directly, its __name__ is set to "__main__". When the file is imported as a module, __name__ is normally set to that module's name.

This distinction is useful when a file contains reusable functions as well as code intended only for direct execution.

Example

Create calculator.py:

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

if __name__ == "__main__":
    print("Calculator module is running directly.")
    print(add(10, 20))

Now run the file directly:

python calculator.py

Output:

Calculator module is running directly.
30

If you import calculator from another file, the code inside the if __name__ == "__main__": block will not execute as part of that import.

For example, in main.py:

import calculator

print(calculator.add(5, 7))

Output:

12

The conditional block makes it possible to keep test or demonstration code in a module without running it whenever the module is imported.

7. What Is a Python Package?

A package is a way to organize related Python modules into a directory structure.

For example, a shopping application may have separate modules for products, customers, and orders. These modules can be grouped inside a package named shopping.

A traditional regular package commonly includes an __init__.py file. Modern Python also supports namespace packages that do not require this file in every package directory.

Example Package Structure

my_project/
│
├── main.py
│
└── shopping/
    ├── __init__.py
    ├── products.py
    └── orders.py

In this structure:

  • shopping is the package.

  • products.py is a module.

  • orders.py is another module.

  • __init__.py marks a regular package and can contain package initialization code.

Step 1: Create shopping/products.py

def show_product():
    print("Product: Laptop")
    print("Price: 50000")

Step 2: Create shopping/orders.py

def create_order():
    print("Order created successfully.")

Step 3: Create shopping/__init__.py

For this example, the file can be empty.

Step 4: Import Package Modules in main.py

from shopping import products, orders

products.show_product()
orders.create_order()

Output:

Product: Laptop
Price: 50000
Order created successfully.

This structure keeps related functionality together and makes larger applications easier to manage.

8. Importing From a Package

Python supports several ways to import package modules.

A. Import a Module From a Package

import shopping.products

shopping.products.show_product()

B. Import a Module Using from

from shopping import products

products.show_product()

C. Import a Specific Function

from shopping.products import show_product

show_product()

All three approaches can be valid. Choose the one that keeps the code clear and avoids confusing names.

D. Relative Imports Inside Packages

Relative imports can be useful when one module needs another module within the same package.

For example, inside a package module, you might write:

from .products import show_product

The dot refers to the current package. Relative imports should be used within an appropriate package context; running such a file directly as a standalone script may cause import errors.

9. What Is pip in Python?

pip is a package installer commonly used to install and manage Python packages from package indexes.

For example, install Requests with:

python -m pip install requests

Check the installed pip version:

python -m pip --version

List installed packages:

python -m pip list

Display information about an installed package:

python -m pip show requests

Uninstall a package:

python -m pip uninstall requests

Using python -m pip helps run pip through the selected Python interpreter, reducing confusion when multiple Python installations are present.

For project-specific dependencies, developers often use a virtual environment.

Creating a Virtual Environment

python -m venv .venv

On Windows Command Prompt, activate it with:

.venv\Scripts\activate

On macOS or Linux, use:

source .venv/bin/activate

Once the environment is active, install the project's dependencies there.

10. The Python Module Search Path

When Python imports a module, it searches locations defined by its import system. These commonly include the script or current working directory, configured paths, and installed library locations.

The sys.path list shows the search locations used by the standard path-based import system.

import sys

for path in sys.path:
    print(path)

The exact output depends on the Python installation, how the program is launched, and the environment configuration.

If Python cannot find a module, check:

  1. Whether the filename is correct.

  2. Whether the module is in an appropriate import location.

  3. Whether the intended virtual environment is active.

  4. Whether the package is installed in that environment.

  5. Whether a local file is unintentionally shadowing a standard library or third-party module.

11. Common Module Import Errors

A. ModuleNotFoundError

This error usually means Python could not locate the requested module.

Example:

import unknown_module

If the module does not exist or is not available on the import path, Python raises ModuleNotFoundError.

How to fix it:

  • Check the module spelling.

  • Install the required third-party package if necessary.

  • Check the active Python interpreter and virtual environment.

  • Confirm that the module is in the correct directory.

B. ImportError

An ImportError may occur when Python finds a module but cannot import the requested name.

Example:

from math import unknown_function

The requested name does not exist in the math module.

How to fix it:

  • Verify the function or class name.

  • Confirm that you are importing from the correct module.

  • Check the package version if the name depends on a particular version.

C. Circular Imports

A circular import can occur when two modules depend on each other during initialization.

For example, module A imports module B, while module B also imports module A. Depending on the import sequence, this can lead to partially initialized modules or missing names.

How to avoid it:

  • Keep module responsibilities clear.

  • Move shared functionality into a third module.

  • Reconsider dependencies between modules.

  • Use local imports only when they are appropriate and genuinely improve the design.

D. Naming Conflicts

Avoid naming your own files after standard library modules or installed packages when possible.

For example, naming a file random.py can interfere with importing Python's random module.

Choose descriptive names such as random_demo.py instead.

12. Practical Project: A Simple Shopping Application

Let's organize a small shopping application using modules and a package.

Project Structure

shopping_project/
│
├── main.py
│
└── shopping/
    ├── __init__.py
    ├── products.py
    └── cart.py

File 1: shopping/products.py

products = {
    1: {"name": "Keyboard", "price": 1200},
    2: {"name": "Mouse", "price": 600},
    3: {"name": "Monitor", "price": 12000}
}

def show_products():
    for product_id, product in products.items():
        print(
            f"{product_id}. {product['name']} - "
            f"Rs. {product['price']}"
        )

File 2: shopping/cart.py

def calculate_total(items):
    return sum(items)

File 3: shopping/__init__.py

Leave this file empty for the example.

File 4: main.py

from shopping.products import products, show_products
from shopping.cart import calculate_total

show_products()

cart_prices = [
    products[1]["price"],
    products[2]["price"]
]

total = calculate_total(cart_prices)

print("Cart Total: Rs.", total)

Output:

1. Keyboard - Rs. 1200
2. Mouse - Rs. 600
3. Monitor - Rs. 12000
Cart Total: Rs. 1800

This example demonstrates how modules can separate product data and display logic from cart calculations.

It is a learning example rather than a production-ready shopping cart. A real application would also need quantities, stock checks, input validation, and appropriate handling of prices.

13. Best Practices for Python Modules and Packages

Follow these practices when organizing Python projects:

  1. Use descriptive module and package names.

  2. Follow Python naming conventions, commonly using lowercase names and underscores where appropriate.

  3. Keep each module focused on a related set of responsibilities.

  4. Avoid wildcard imports in production code.

  5. Use if __name__ == "__main__": for code intended to run only when a module is executed directly.

  6. Avoid circular dependencies where possible.

  7. Use virtual environments to isolate project dependencies.

  8. Keep third-party dependencies documented, for example in a requirements.txt file.

  9. Do not name files after standard library modules or important third-party packages.

  10. Write docstrings and tests for important reusable functionality.

Example: Creating a Requirements File

After installing the packages your project needs, you can create a dependency list.

python -m pip freeze > requirements.txt

Install the listed dependencies in another environment with:

python -m pip install -r requirements.txt

For production projects, review dependency versions and use an appropriate dependency-management strategy.

14. Python Modules and Packages: Practice Exercises

Try these exercises to strengthen your understanding:

  1. Create a module containing functions for addition, subtraction, multiplication, and division.

  2. Create a module that calculates the area of a circle and rectangle.

  3. Import the math module and display the square root of a number.

  4. Use the datetime module to display the current date.

  5. Create a module with a greeting function and import it into another file.

  6. Create a package containing separate modules for students and teachers.

  7. Create a products package and add a module that displays product details.

  8. Use __name__ == "__main__" to separate reusable functions from direct-execution code.

  9. Create a virtual environment and install a third-party package.

  10. Create a small project that separates data, calculations, and display logic into different modules.

15. Python Modules and Packages Interview Questions

Q1. What is a Python module?

A module is a Python file containing reusable code such as functions, classes, and variables.

Q2. What is a Python package?

A package organizes related Python modules into a directory structure.

Q3. What is the difference between a module and a package?

A module is generally a Python file, while a package organizes modules within a directory structure.

Q4. Which keyword is used to import a module?

The import keyword.

Q5. What is the purpose of the from keyword in imports?

It allows you to import specific names from a module or package.

Q6. What is an alias in Python imports?

An alias provides an alternative name for an imported module or object using as.

Q7. What is __name__ == "__main__" used for?

It checks whether a file is being executed directly as the main program rather than imported as a module.

Q8. What is pip?

pip is a package installer commonly used to install and manage Python packages.

Q9. What is sys.path?

It is a list of locations used by the standard path-based import system to find modules.

Q10. What is a circular import?

A circular import occurs when modules depend on each other during the import process.

Q11. What is __init__.py?

It is a file used to mark and optionally initialize a regular Python package. It can also expose selected package-level names.

Q12. Why are virtual environments useful?

They help isolate project dependencies so that different projects can use different package versions.

Conclusion

Python modules and packages are essential for building organized, reusable, and maintainable applications. By learning built-in modules, user-defined modules, import statements, packages, pip, virtual environments, and common import errors, you can structure Python programs more professionally.

Practice creating small modules and packages before moving on to file handling and exception handling.

←
Post 13 of 20
→