๐Ÿ”งFunctions: def, return, DocstringsLESSON

Functions: def, return, Docstrings

Functions are reusable blocks of code that accept inputs, perform a task, and optionally return a value. They are the primary tool for organising code, avoiding repetition, and expressing intent.

Defining Functions

A function definition consists of:

  1. def keyword
  2. Function name (follows the same rules as variable names)
  3. Parameter list in parentheses
  4. Colon
  5. Indented body

Parameters and Arguments

The Mutable Default Gotcha

This is one of the most common Python bugs for newcomers: mutable default arguments are shared across all calls.

The pattern def func(arg=None) with if arg is None: arg = [] inside the body is the idiomatic fix for any mutable default (lists, dicts, sets).

Return Values

Type Hints

Type hints (PEP 484) annotate function signatures with expected types. They don't enforce types at runtime but enable static analysis tools (mypy, pyright) and improve editor autocompletion.

Docstrings

A docstring is a string literal placed immediately after the def line. It documents what the function does, its parameters, and its return value. Tools like help(), Sphinx, and IDEs read docstrings automatically.

First-Class Functions

In Python, functions are first-class objects โ€” they can be assigned to variables, passed as arguments, and returned from other functions.

Scope: Local vs Global

Rely on global only when necessary. Most of the time, returning a value and reassigning it at the call site is cleaner and more testable than mutating globals.

Knowledge Check

What does a Python function return if it has no explicit return statement?

Why is `def func(lst=[])` considered a bug-prone pattern?

Which statement about first-class functions in Python is TRUE?