On this page
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
- > Parameter Kinds (`/`, `*`, `*args`, `**kwargs`)
- > Scope Rules (LEGB)
- > `lambda` Expressions & First-Class Functions
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:
- Positional-only (before
/) - Positional-or-keyword (default)
- Var-positional (
*args) - Keyword-only (after
*or*args) - 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:
- Local (L) — inside the current function.
- Enclosing (E) — inside any enclosing function(s) (closures).
- Global (G) — module-level namespace.
- 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
- tuts/python3/tutorials/core_fundamentals Linked here; links to this page; shared tags: #fundamentals, #tutorials
- tuts/python3/tutorials/core_fundamentals/control_flow Linked here; links to this page; shared tags: #fundamentals, #tutorials
- tuts/python3/python functions Linked here; links to this page; shared tags: #functions
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/python3/tutorials/intermediate_python_and_software_engineering Linked here; shared tags: #tutorials
- tuts/python3/python decorators Linked here
- tuts/python3/stdlib_module/functools Linked here
- tuts/python3/stdlib_module/inspect Linked here
- tuts/javascript/tutorials/functions_closures_and_this shared tags: #functions, #tutorials
- tuts/python3/tutorials/core_fundamentals/builtin_data_structures shared tags: #fundamentals, #tutorials