Module 7 ยท Lesson 21

Modules, Packages, and Imports

๐Ÿ Pythonโฑ 13 min read๐Ÿ“– Core Concept

Modules

A module is any Python file. When you import it, Python executes the file and makes its contents available. Modules are how you organize code into reusable units.

# mymodule.py PI = 3.14159 def circle_area(r): return PI * r ** 2 class Circle: def __init__(self, radius): self.radius = radius # main.py โ€” importing the module import mymodule print(mymodule.PI) print(mymodule.circle_area(5)) # Import specific names from mymodule import circle_area, PI print(circle_area(5)) # No module prefix needed # Import with alias import mymodule as mm from mymodule import circle_area as area print(area(5))

Import Styles

# Good: explicit imports import os import math from pathlib import Path from collections import defaultdict, Counter # Wildcard import โ€” avoid except in interactive use from math import * # Pollutes namespace, unclear what's imported # Relative imports (inside packages) from . import sibling_module # Same package from .sibling_module import some_func # Specific from sibling from .. import parent_module # Parent package

The Standard Library

Python ships with a huge standard library. You don't need to install these:

import os # OS interaction, environment variables, paths import sys # Python interpreter, sys.argv, sys.exit import re # Regular expressions import json # JSON parsing import csv # CSV files import math # Math functions import random # Random numbers import datetime # Dates and times import time # Time functions, sleep import urllib # URL handling import http # HTTP client/server import socket # Network sockets import threading # Threads import multiprocessing # Multiple processes import subprocess # Run external commands import hashlib # Cryptographic hashes import base64 # Encoding import logging # Logging framework import unittest # Unit testing import argparse # Command-line argument parsing import itertools # Iterator tools import functools # Function tools import operator # Operator functions import copy # Shallow and deep copy import io # In-memory file objects import struct # Binary data packing # Quick examples import os print(os.getcwd()) print(os.environ.get("HOME")) os.path.join("folder", "file.txt") # Cross-platform paths import datetime now = datetime.datetime.now() print(now.strftime("%Y-%m-%d %H:%M:%S"))

Creating Packages

A package is a directory containing an __init__.py file (can be empty) and Python modules.

# Project structure myapp/ __init__.py # Makes myapp a package models.py utils.py config.py api/ __init__.py # Makes api a subpackage routes.py auth.py # Import from package from myapp import models from myapp.models import User from myapp.api.routes import app from myapp.api import auth

__init__.py

# myapp/__init__.py # Controls what 'from myapp import *' gives __all__ = ["models", "utils"] # Can run initialization code print("myapp loaded") # Common pattern: expose key classes at package level from .models import User, Product from .utils import format_date, validate_email # Now users can: from myapp import User (not from myapp.models import User)

if __name__ == "__main__"

# utils.py def add(a, b): return a + b def main(): print(add(3, 4)) if __name__ == "__main__": # This runs ONLY when script is run directly: # python3 utils.py # NOT when imported: # import utils main()

Key Takeaways

Practice Exercises

  1. Create a math_utils.py module with functions for factorial, fibonacci, and is_prime. Import and test from another file.
  2. Create a package called shapes with modules for different shape types. Expose key classes from __init__.py.
  3. Write a script using argparse that takes command-line arguments and does something useful.
โ† Context Managers