On this page
  1. Functions
  2. Contents
  3. Defining Functions & Default Arguments
  4. Parameter Kinds (/, *, *args, **kwargs)
  5. Scope Rules (LEGB)
  6. lambda Expressions & First-Class Functions

Functions

Prev: Control Flow | Up: Core Fundamentals | Next: Intermediate Python & Software Engineering
Rel: python functions, python decorators, functools, inspect
Ref: docs.python.org — Defining Functions
Tags: #public #python3 #tutorials #fundamentals #functions


Contents


Defining Functions & Default Arguments

Functions are defined with def, documented with docstrings, and return None if no return statement is executed.

Avoid mutable default arguments (def f(items=[]):), because default expressions are evaluated once at function definition time. Use None as a sentinel instead:

def append_item(item: str, bucket: list[str] | None = None) -> list[str]:
    """Append item to a list, creating a fresh list if none is supplied."""
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(append_item("a"))  # ['a']
print(append_item("b"))  # ['b']

Parameter Kinds (/, *, *args, **kwargs)

Python supports five parameter categories in strict order:

  1. Positional-only (before /)
  2. Positional-or-keyword (default)
  3. Var-positional (*args)
  4. Keyword-only (after * or *args)
  5. Var-keyword (**kwargs)
def log_event(event: str, /, level: str = "INFO", *tags: str, timestamp: bool = True, **meta):
    return {"event": event, "level": level, "tags": tags, "timestamp": timestamp, "meta": meta}

print(log_event("startup", "DEBUG", "boot", "init", timestamp=False, host="local"))

Scope Rules (LEGB)

Python resolves unqualified names in LEGB order:

  1. Local (L) — inside the current function.
  2. Enclosing (E) — inside any enclosing function(s) (closures).
  3. Global (G) — module-level namespace.
  4. Built-in (B) — [[__builtins__|builtins]] namespace.

Use nonlocal to rebind an enclosing-scope variable and global to rebind a module-level variable.

counter_global = 0

def make_counter(start: int = 0):
    count = start
    def increment(step: int = 1) -> int:
        nonlocal count
        count += step
        return count
    return increment

inc = make_counter(10)
print(inc(), inc(5))  # 11 16

lambda Expressions & First-Class Functions

Functions are first-class objects: they can be stored in data structures, passed as arguments, and returned from other functions. lambda creates small anonymous single-expression functions, typically for sort keys or callbacks.

records = [("pear", 3), ("apple", 1), ("banana", 2)]
by_count = sorted(records, key=lambda pair: pair[1])
print(by_count)  # [('apple', 1), ('banana', 2), ('pear', 3)]

Linked from

Related notes