4.1 Functions in Python
Functions are defined with def and can use positional-only, positional-or-keyword, and keyword-only parameters.
Defining and returning values
def add(a, b):
return a + b
Parameter kinds
def api(name, /, version, *, timeout=30):
return name, version, timeout
- Parameters before
/are positional-only. - Parameters after
*are keyword-only.
Defaults and common pitfall
Default values are evaluated once at function definition time.
def append_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
*args and **kwargs
def log_event(event, *args, **kwargs):
...
Annotations and docstrings
- Function annotations are metadata and do not enforce runtime types.
- Docstrings should summarize purpose and usage clearly.
Official references
- Tutorial functions: https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions
- Function definition grammar: https://docs.python.org/3/reference/compound_stmts.html#function-definitions
- Type hints module: https://docs.python.org/3/library/typing.html