Skip to content

Python Functions: def, args, kwargs, closures, and decorators

  • Defining functions with def, default values, and return type annotations.
  • Positional, keyword, *args, **kwargs, and positional-only parameters.
  • Closures and how Python captures variables from enclosing scopes.
  • Lambdas: when they help and when to use def instead.
  • Decorators: the pattern, common uses, and how to write your own.

Functions are first-class objects in Python — they can be assigned to variables, passed as arguments, returned from other functions, and stored in data structures. This enables higher-order functions, closures, and the decorator pattern that appears throughout the standard library and third-party frameworks.

Save examples as .py and run with python examples.py (Python 3.9+).

def calculate_total(subtotal: float, tax_rate: float = 0.08) -> float:
"""Return subtotal plus tax, rounded to two decimal places."""
return round(subtotal * (1 + tax_rate), 2)
print(calculate_total(100.0)) # 108.0
print(calculate_total(100.0, 0.05)) # 105.0

The docstring (triple-quoted string as the first statement) is accessible via help(calculate_total) and read by documentation generators. Write it.

Python lets callers pass arguments positionally or by name:

def create_order(order_id: str, customer: str, amount: float) -> dict:
return {"id": order_id, "customer": customer, "amount": amount}
# Positional
order = create_order("ORD-001", "BensonCo", 149.99)
# Keyword — order doesn't matter
order = create_order(customer="BensonCo", amount=149.99, order_id="ORD-001")
# Mixed: positional first, then keyword
order = create_order("ORD-001", amount=149.99, customer="BensonCo")
def send_notification(
message: str,
recipient: str = "admin@orders.example.test",
priority: str = "normal",
) -> None:
print(f"[{priority.upper()}] To {recipient}: {message}")
send_notification("Order shipped")
# [NORMAL] To admin@orders.example.test: Order shipped
send_notification("Payment failed", priority="high")
# [HIGH] To admin@orders.example.test: Payment failed

Warning — mutable defaults: Python evaluates default argument values once at function definition time, not at each call. A mutable default is shared across all calls:

# BUG: the same list is shared by all callers
def add_tag(tag: str, tags: list = []) -> list:
tags.append(tag)
return tags
print(add_tag("sale")) # ['sale']
print(add_tag("clearance")) # ['sale', 'clearance'] — unexpected!
# FIX: use None and create a new list inside the function
def add_tag_fixed(tag: str, tags: list | None = None) -> list:
if tags is None:
tags = []
tags.append(tag)
return tags

*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dict.

def log_event(event_type: str, *args: str, **kwargs) -> None:
"""
log_event("order.created", "ORD-001", customer="BensonCo", amount=149.99)
"""
print(f"Event: {event_type}")
for arg in args:
print(f" positional: {arg}")
for key, value in kwargs.items():
print(f" {key}: {value}")
log_event("order.created", "ORD-001", "extra_detail", customer="BensonCo", amount=149.99)
# Event: order.created
# positional: ORD-001
# positional: extra_detail
# customer: BensonCo
# amount: 149.99

Unpacking at the call site with * and **:

def create_order(order_id: str, customer: str, amount: float) -> dict:
return {"id": order_id, "customer": customer, "amount": amount}
args = ("ORD-001", "BensonCo")
kwargs = {"amount": 149.99}
order = create_order(*args, **kwargs) # unpacks at the call site

Keyword-only and positional-only parameters

Section titled “Keyword-only and positional-only parameters”

Keyword-only parameters (after *) must be passed by name:

def apply_discount(amount: float, *, pct: float, reason: str = "") -> float:
"""pct and reason are keyword-only."""
return round(amount * (1 - pct), 2)
apply_discount(100.0, pct=0.10) # fine
apply_discount(100.0, pct=0.10, reason="loyalty") # fine
apply_discount(100.0, 0.10) # TypeError: pct must be keyword

Positional-only parameters (before /, Python 3.8+) cannot be passed by name:

def parse_id(value: str, /) -> int:
return int(value.lstrip("ORD-"))
parse_id("ORD-001") # fine: 1
parse_id(value="ORD-001") # TypeError: positional-only

A closure is a function that captures variables from its enclosing scope. The inner function “closes over” the outer variable.

def make_tax_calculator(tax_rate: float):
"""Return a function that applies a fixed tax rate."""
def calculate(subtotal: float) -> float:
return round(subtotal * (1 + tax_rate), 2) # tax_rate is captured
return calculate
uk_tax = make_tax_calculator(0.20)
us_tax = make_tax_calculator(0.08)
print(uk_tax(100.0)) # 120.0
print(us_tax(100.0)) # 108.0

Each call to make_tax_calculator creates a new closure with its own tax_rate. Closures are the foundation of the decorator pattern.

A lambda is a one-expression anonymous function. It is syntactic sugar for a simple def:

double = lambda x: x * 2
print(double(5)) # 10
# Most useful when passed inline to map, filter, or sorted
orders = [
{"id": "ORD-003", "amount": 50.0},
{"id": "ORD-001", "amount": 200.0},
{"id": "ORD-002", "amount": 75.0},
]
# Sort by amount
sorted_orders = sorted(orders, key=lambda o: o["amount"])
print([o["id"] for o in sorted_orders]) # ['ORD-003', 'ORD-002', 'ORD-001']
# Filter to orders over $100
large = list(filter(lambda o: o["amount"] > 100, orders))

Use lambda only for one-liners passed directly as an argument. If you find yourself naming a lambda (f = lambda x: ...), write a def instead — it has a name in tracebacks and supports a docstring.

A decorator is a function that wraps another function to add behavior before or after it runs. The @decorator syntax is shorthand for function = decorator(function).

import functools
import time
def timed(func):
"""Decorator that prints how long a function took."""
@functools.wraps(func) # preserves the wrapped function's __name__ and __doc__
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed*1000:.1f}ms")
return result
return wrapper
@timed
def process_orders(count: int) -> list[str]:
"""Simulate processing orders."""
return [f"ORD-{i:04d}" for i in range(count)]
result = process_orders(1000)
# process_orders took 0.3ms

Decorators with arguments need an extra layer of nesting:

def retry(max_attempts: int = 3, delay: float = 1.0):
"""Decorator factory: retry on exception up to max_attempts times."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except Exception as e:
if attempt == max_attempts:
raise
print(f"Attempt {attempt} failed: {e}. Retrying...")
time.sleep(delay)
return wrapper
return decorator
@retry(max_attempts=3, delay=0.5)
def fetch_order(order_id: str) -> dict:
# Might fail transiently
...
  • Mutable default argument. Already covered above — the most common beginner bug.
  • Missing functools.wraps. Without @functools.wraps(func) in a decorator, the wrapped function loses its __name__, __doc__, and __module__, making debugging harder.
  • Naming a lambda. f = lambda x: x * 2 should be def f(x): return x * 2. Named lambdas appear in tracebacks as <lambda>, which makes errors harder to trace.
  • Modifying a closure variable without nonlocal. You can read outer-scope variables in a closure freely, but to rebind them you need nonlocal:
def counter():
count = 0
def increment():
nonlocal count # required to rebind count
count += 1
return count
return increment
c = counter()
print(c()) # 1
print(c()) # 2

1. How does Python evaluate default argument values? Once at function definition time, not at each call. This is why def f(items=[]) is a bug — the same list is shared by all callers. The idiomatic fix is to use None as the default and create the mutable object inside the function body.

2. What is the difference between *args and **kwargs? *args collects all extra positional arguments into a tuple named args. **kwargs collects all extra keyword arguments into a dict named kwargs. Both names are conventions; the * and ** are the actual syntax. They allow functions to accept arbitrary numbers of arguments, which is useful for wrapper functions and variadic APIs.

3. Senior scenario: an OrdersPortal service needs to add request tracing (inject a correlation ID into every log line) across 50 endpoints without modifying each endpoint function. How would you implement this? Write a decorator that extracts or generates a correlation ID from the request context, injects it into the logging context (using logging.LoggerAdapter or a context variable via contextvars.ContextVar), calls the wrapped function, and removes it on exit. Apply the decorator to each endpoint, or — better — configure the web framework’s middleware to apply it globally. This way the 50 endpoint functions stay clean; the cross-cutting concern lives in one place.

  • Functions are first-class objects in Python — assign, pass, and return them.
  • Mutable defaults are shared across calls; use None and initialize inside the body.
  • *args collects positional extras into a tuple; **kwargs collects keyword extras into a dict.
  • Closures capture variables from enclosing scopes — the foundation of decorators.
  • Use @functools.wraps(func) in every decorator to preserve the wrapped function’s metadata.