Chapter 7: Functions & Modules

Define reusable functions, document them with docstrings, handle flexible arguments, and organize code into modules & packages.

Download chapter7.py

Objectives

1. Defining Functions

Use def keyword. Specify parameters and return a value:

def greet(name):
    """Return a greeting string for the given name."""
    return f"Hello, {name}!"

msg = greet("Alice")
print(msg)  # Hello, Alice!

Parameters can have default values:

def power(base, exp=2):
    return base ** exp

print(power(5))     # 25
print(power(2, 3))  # 8

2. Docstrings & Scope

Document functions with a triple-quoted string immediately below def:

def add(a, b):
    """
    Add two numbers.

    Args:
        a (int): first addend
        b (int): second addend

    Returns:
        int: sum of a and b
    """
    return a + b

help(add)

Variables inside functions are local by default:

x = 10

def foo():
    x = 5  # local x
    return x

print(foo(), x)  # 5 10

Use global to modify a module-level variable:

counter = 0

def inc():
    global counter
    counter += 1

3. *args & **kwargs

Accept arbitrary positional args:

def summarize(*args):
    return sum(args)

print(summarize(1,2,3,4))  # 10

Accept arbitrary keyword args:

def config(**kwargs):
    for key, val in kwargs.items():
        print(f"{key} = {val}")

config(host="localhost", port=8080)

Combine both:

def mixed(a, *args, **kwargs):
    print(a, args, kwargs)

mixed(1,2,3, x=10, y=20)

4. Modules & Packages

Every .py file is a module. Import with:

# file: math_utils.py
def square(x):
    return x*x

# in another file
import math_utils
print(math_utils.square(5))

Use from … import … to bring names into scope:

from math_utils import square
print(square(6))

Group modules in a directory with an __init__.py to form a package:

project/
└── utils/
    ├── __init__.py
    └── math_utils.py

Protect script entry point:

if __name__ == "__main__":
    # code to run when executed directly
    pass

Exercises

  1. Write a function multiply(a, b=1) and test it with different args.
  2. Create stats.py module with mean() and median(), then import and use them.
  3. Implement a function accepting any number of positional and keyword args, and print them.
  4. Build a package mypkg with two modules and demonstrate importing from it.