Sub topic 2
Putting Parameters in the Right Order
Assume you know how to define functions, use positional and keyword arguments, and work with tuples and dictionaries.
Parameter order
Python requires function parameters in this order:
- Regular parameters
- Parameters with defaults
*args- Keyword-only parameters
**kwargs
*args collects extra positional arguments in a tuple. After it, parameters are keyword-only.
def describe(name, count=1, *items, style="plain", **metadata):
return name, count, items, style, metadata
print(describe("box", 2, "red", "large", style="short", id=7))
# ('box', 2, ('red', 'large'), 'short', {'id': 7})A parameter with a default cannot come before a required positional parameter. However, required keyword-only parameters can follow *args.
def configure(name, *values, required_option, mode="safe", **extra):
return name, values, required_option, mode, extra
print(configure("app", 1, 2, required_option=True))Unpacking values into calls
At a call site, * unpacks an iterable into positional arguments. ** unpacks a dictionary into keyword arguments.
def area(width, height):
return width * height
dimensions = (3, 4)
print(area(*dimensions)) # 12
options = {"width": 2, "height": 5}
print(area(**options)) # 10The dictionary keys must match parameter names. Do not provide the same parameter twice.
def greet(name):
return f"Hello, {name}"
data = {"name": "Bob"}
print(greet(**data)) # Hello, Bob
# This raises TypeError:
# greet("Ada", **data)> callout note > Unpacking does not copy the function's signature. It only supplies values. Python still checks the final call for missing, duplicate, or unexpected arguments.
Forwarding arguments in wrappers
A wrapper can accept and pass on any arguments with *args and **kwargs. functools.wraps preserves the wrapped function's metadata.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b=0):
return a + b
print(add(1, b=2))
# calling add
# 3Exercise
In def f(a, *args, option, **kwargs):, where does option=3 go when calling f(1, 2, option=3)?
Show answer
It goes into the keyword-only parameter option; args becomes (2,), and kwargs remains empty.