Python Modules

1. What is a Module

# file: math_utils.py
def add(a, b):
    return a + b

A module is a file containing Python code (functions, variables, classes) that can be imported and reused in other programs.


2. Importing a Module

import math

print(math.sqrt(25))  # Output: 5.0

The import keyword loads the entire module and accesses its content using dot notation.


3. Importing Specific Functions from a Module

from math import sqrt, pow

print(sqrt(16))     # Output: 4.0
print(pow(2, 3))    # Output: 8.0

Imports only selected items, reducing namespace clutter.


4. Renaming a Module using as

Useful for improving readability or avoiding name conflicts.


5. Creating and Using a Custom Module

Custom modules help organize reusable logic.


6. Using __name__ in Modules

Ensures code runs only when the file is executed directly, not when imported.


7. Built-in Modules Example

Python provides rich built-in modules like os, sys, math, datetime, and random.


8. Exploring Module Content with dir()

Lists all available attributes and methods inside a module.


9. Using help() for Module Documentation

Displays detailed documentation of a module and its components.


10. Module Search Path (sys.path)

Shows directories Python searches to locate modules, including:

  • Current directory

  • Standard library path

  • Site-packages


Last updated