Modules

Modules in Python: As your programs grow from 10 lines to 10,000 lines, keeping everything in a single file becomes impossible.

Concept Explanation

As your programs grow from 10 lines to 10,000 lines, keeping everything in a single file becomes impossible. Modules are simply Python files (.py) that contain functions, classes, and variables.

By splitting your code into modules, you make it easier to manage, test, and share. If you write a great math library, you can "import" it into any other project without rewriting a single line of code. Python also comes with a "Standard Library"—a collection of thousands of pre-written modules for everything from web servers to zip file compression.


Syntax or Core Structure

The Three Ways to Import

  1. Standard Import: Imports the whole module. You must use the module name to access its tools.
  • import math -> math.sqrt(16)
  1. Specific Import: Imports only what you need. You don't need the module name.
  • from math import sqrt -> sqrt(16)
  1. Alias Import: Gives the module a shorter nickname.
  • import pandas as pd -> pd.DataFrame()

Code Example #1 (Basic)

Using the built-in random and datetime modules.

import random
from datetime import datetime

# Get a random number
secret_number = random.randint(1, 100)

# Get the current time
now = datetime.now()

print(f"Generated {secret_number} at {now.strftime('%H:%M:%S')}")

Code Example #2 (Intermediate)

Creating your own custom module. Imagine you have a file called calculator.py.

# --- In calculator.py ---
def multiply(a, b):
    return a * b

# --- In your main.py ---
import calculator

result = calculator.multiply(10, 5)
print(f"The result is {result}")

Real World Example

When you install a library like Requests or Flask (which we'll cover later), you are essentially downloading professional modules written by other developers and importing them into your project.

# 📦 External Module Usage
# First, you would run: pip install requests
import requests

# This module handles all the complex networking code for you!
response = requests.get("https://api.github.com")

if response.status_code == 200:
    print("Success! The internet is working.")

Common Mistakes

  1. Naming Conflicts: If you name your file random.py, you will "shadow" the built-in Python random module, and your import random calls will fail or behave strangely. Never name your files the same as standard libraries!
  2. Circular Imports: If Module A imports Module B, and Module B imports Module A, Python will get stuck in a loop and crash.
  3. *Importing Everything ()**: Avoid using from module import *. It makes it impossible for other developers to know where a function came from (did show() come from your code or the library?).

Best Practices

  • Alphabetic Order: Imports should be at the very top of the file, grouped by (1) Standard Libraries, (2) Third-party Libraries, and (3) Your own modules.
  • Use if __name__ == "__main__":: When writing a module, put your testing code inside this block. It ensures that the test code ONLY runs when you execute the module file directly, and NOT when someone imports it.

Practice Exercises

  1. Math Explorer: Import the math module. Use it to calculate the square root of 625 and the value of Pi rounded to 2 decimal places.
  2. The Nickname: Import the os module (which handles file paths) and give it the alias system. Print the current directory using system.getcwd().
  3. Custom Utility: Create a second script file with a function that calculates a person's birth year from their current age. Import it into your main script and call it.