CS Pathfinder Logo CS Pathfinder


Unit 4 · Modules and File Handling

Modules in Python

Learn what modules are, how to import and use them, and understand the different import styles and module search mechanisms in Python.

Introduction

As Python programs grow larger, it becomes essential to organize code into separate, reusable files. Modules are Python files that contain functions, classes, and variables which can be imported and used in other programs.

Using modules promotes code reuse, keeps programs organized, and avoids duplication. Python's standard library provides hundreds of built-in modules, and you can also create your own.

University Definition

A module in Python is a file containing Python definitions, statements, and functions that can be imported and used in other Python programs. Modules provide a mechanism for code reuse and help organize programs into separate namespaces. A module is essentially any .py file.

Table of Contents

What is a Module?

A module is simply a .py file that contains Python code. Any Python file can be treated as a module. Modules can contain functions, classes, variables, and runnable code.

# file: mymodule.py
def greet(name):
    return f"Hello, {name}!"

PI = 3.14159

class Calculator:
    def add(self, a, b):
        return a + b

Real-life Analogy: A module is like a toolbox. Each toolbox contains specific tools (functions, classes, variables) for a particular task. You bring the toolbox (import the module) and use its tools as needed.

Different Ways to Import Modules

Method 1: import module_name

import math
print(math.sqrt(25))      # 5.0
print(math.pi)            # 3.141592653589793
print(math.factorial(5))  # 120

Imports the entire module. Access items using module.item. Safest method, avoids naming conflicts.

Method 2: from module import item

from math import sqrt, pi
print(sqrt(25))  # 5.0
print(pi)        # 3.141592653589793

Imports specific items. Use them directly without module prefix. Risk of name conflicts.

Method 3: from module import *

from math import *
print(sqrt(25))  # 5.0
print(ceil(4.3)) # 5

Imports everything. Not recommended as it pollutes the namespace.

Method 4: import module as alias

import math as m
print(m.sqrt(25))  # 5.0

Creates a shorter name. Very common: import numpy as np, import pandas as pd.

Method 5: from module import item as alias

from math import factorial as fact
print(fact(5))   # 120
print(fact(10))  # 3628800

Exploring Modules with dir() and help()

University Definition

dir() returns a list of all names defined in a module. help() provides detailed documentation about a module, class, or function.

import math
print(dir(math))      # List all items in math module
help(math.sqrt)       # Detailed help for sqrt function

Module Search Path

When you import a module, Python searches in this order:

  1. Current directory — where the script is running
  2. PYTHONPATH — environment variable listing directories
  3. Default directories — installation-dependent standard paths
  4. site-packages — third-party modules installed via pip
import sys
print(sys.path)  # Shows the list of directories Python searches

pip — Package Installer for Python

pip is the standard package manager for Python. It downloads and installs packages from the Python Package Index (PyPI).

# Install a package
pip install requests

# Install a specific version
pip install requests==2.28.0

# Install multiple packages
pip install numpy pandas matplotlib

# List installed packages
pip list

# Uninstall a package
pip uninstall requests

# Save dependencies to a file
pip freeze > requirements.txt

# Install from requirements file
pip install -r requirements.txt

University Exam Tip

Remember: pip installs third-party packages, sys.path shows the search path, and dir() lists module contents. These are frequently asked in exams.

Practical Examples

# Example 1: Using math module
import math

print("Square root of 144:", math.sqrt(144))
print("Power of 2^10:", math.pow(2, 10))
print("Ceiling of 4.3:", math.ceil(4.3))
print("Floor of 4.7:", math.floor(4.7))
print("Factorial of 6:", math.factorial(6))
print("Value of pi:", math.pi)

# Output:
# Square root of 144: 12.0
# Power of 2^10: 1024.0
# Ceiling of 4.3: 5
# Floor of 4.7: 4
# Factorial of 6: 720
# Value of pi: 3.141592653589793
# Example 2: Using random module
import random

print("Random float:", random.random())
print("Random int 1-10:", random.randint(1, 10))
print("Random choice:", random.choice(["a", "b", "c"]))

# Output:
# Random float: 0.7134 (varies)
# Random int 1-10: 7 (varies)
# Random choice: b (varies)
# Example 3: Creating and importing your own module
# File: myutils.py
def is_even(n):
    return n % 2 == 0

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

# File: main.py
from myutils import is_even, factorial

print(is_even(4))    # True
print(factorial(5))  # 120

Key Points

Any .py file can be used as a module.

import module is the safest import method.

from module import * is not recommended in production.

as keyword creates aliases for modules or items.

dir() lists all attributes of a module.

sys.path shows the module search path.

pip installs third-party packages from PyPI.

pip freeze > requirements.txt saves dependencies.

Common Mistakes

Mistake 1: Using from module import *

This imports all names and can overwrite your existing variables:

from math import *   # Imports everything including 'log'
log = "my variable"  # Overwrites math.log!
print(log)           # "my variable" — math.log is lost

Mistake 2: Circular Import

When two modules import each other, it causes an error:

# module_a.py imports module_b
# module_b.py imports module_a
# This creates a circular import error!

Import Methods Comparison

Method Syntax Pros Cons
import import math No namespace conflicts Longer to type
from...import from math import sqrt Shorter access Possible name clash
from...import * from math import * Convenient Pollutes namespace
import as import math as m Short alias Must remember alias

Practice Questions

Q1: What is the difference between import math and from math import *?

Answer: import math imports the whole module; you access items with math.sqrt(). from math import * imports all names directly into the current namespace.

Q2: How do you find what functions a module provides?

Answer: Use dir(module_name) to list all attributes, or help(module_name) for detailed documentation.

Q3: What is the module search path in Python?

Answer: Python searches: current directory, PYTHONPATH directories, default installation directories, and site-packages. Check with import sys; print(sys.path).

Q4: How do you install external packages in Python?

Answer: Use pip install package_name in the terminal. For example: pip install requests.

Q5: How do you save and restore project dependencies?

Answer: Save with pip freeze > requirements.txt and restore with pip install -r requirements.txt.

Summary

A module is any .py file containing reusable Python code.

Five import methods: import, from...import, from...import *, import as, from...import...as.

dir() lists module contents; help() provides documentation.

Python searches current directory, PYTHONPATH, and site-packages for modules.

pip is the standard package manager for installing third-party modules.

Use pip freeze > requirements.txt to save project dependencies.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.