intermediate Step 10 of 20

Modules and Imports

Python Programming

Modules and Imports

As your programs grow larger, keeping all code in a single file becomes unmanageable. Python's module system lets you organize code into separate files and reuse code across projects. A module is simply a Python file containing definitions and statements. A package is a directory containing multiple modules along with a special __init__.py file. Python's extensive standard library is organized as a collection of modules and packages, and the import system is how you access all of this functionality.

Importing Modules

# Import entire module
import math
print(math.pi)        # 3.141592653589793
print(math.sqrt(16))  # 4.0

# Import with alias
import datetime as dt
now = dt.datetime.now()
print(now)

# Import specific items
from math import pi, sqrt, ceil, floor
print(pi)         # No need for math. prefix
print(sqrt(25))   # 5.0

# Import with alias
from datetime import datetime as dt
now = dt.now()

# Import all (generally avoid — pollutes namespace)
from math import *
print(sin(pi / 2))  # 1.0

Useful Standard Library Modules

# os — operating system interface
import os
print(os.getcwd())                    # Current working directory
print(os.listdir("."))                # List files in directory
print(os.path.exists("myfile.txt"))   # Check if file exists
print(os.path.join("folder", "file.txt"))  # OS-appropriate path

# sys — system-specific parameters
import sys
print(sys.version)          # Python version
print(sys.platform)         # 'darwin', 'linux', 'win32'
# sys.argv                  # Command-line arguments

# json — JSON encoding/decoding
import json
data = {"name": "Alice", "age": 30, "scores": [95, 87, 92]}
json_string = json.dumps(data, indent=2)
print(json_string)
parsed = json.loads(json_string)
print(parsed["name"])  # "Alice"

# random — random number generation
import random
print(random.randint(1, 100))        # Random integer 1-100
print(random.choice(["a", "b", "c"]))  # Random choice
print(random.random())               # Random float 0-1
items = [1, 2, 3, 4, 5]
random.shuffle(items)                # Shuffle in place

# collections — specialized data structures
from collections import Counter, defaultdict, deque
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = Counter(words)
print(counts)                  # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(counts.most_common(2))   # [('apple', 3), ('banana', 2)]

Creating Your Own Modules

# File: utils/math_helpers.py
def factorial(n):
    """Calculate factorial of n."""
    if n <= 1:
        return 1
    return n * factorial(n - 1)

def is_prime(n):
    """Check if n is a prime number."""
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

PI = 3.14159265358979

# File: utils/__init__.py
from .math_helpers import factorial, is_prime, PI

# File: main.py
from utils import factorial, is_prime
print(factorial(5))    # 120
print(is_prime(17))    # True

Package Structure

# Typical project structure:
# my_project/
# ├── main.py
# ├── config.py
# ├── requirements.txt
# ├── utils/
# │   ├── __init__.py
# │   ├── math_helpers.py
# │   └── string_helpers.py
# ├── models/
# │   ├── __init__.py
# │   ├── user.py
# │   └── product.py
# └── tests/
#     ├── __init__.py
#     ├── test_math.py
#     └── test_models.py

# Relative imports (within a package)
# In models/product.py:
from .user import User              # Same package
from ..utils import math_helpers    # Parent package

The if __name__ == "__main__" Pattern

# File: my_module.py
def main():
    print("Running as main program")

def helper():
    return "I'm a helper function"

# This block only runs when the file is executed directly
# It does NOT run when the file is imported as a module
if __name__ == "__main__":
    main()

# When imported: only functions/classes are available
# When run directly: main() executes
Pro tip: Use from module import specific_item instead of from module import *. The wildcard import pollutes your namespace and makes it unclear where names come from. Explicit imports make your code more readable and easier to debug.

Key Takeaways

  • A module is a Python file; a package is a directory with an __init__.py file containing modules.
  • Use import module, from module import item, or import module as alias to access code from other files.
  • Python's standard library includes essential modules like os, sys, json, random, datetime, and collections.
  • Use if __name__ == "__main__": to separate reusable code from executable scripts.
  • Organize larger projects into packages with clear directory structures and use relative imports within packages.