Functions & Parameters
Objective
Write functions with various parameter types, use decorators, and add type annotations.
Tools & Technologies
def*args**kwargsdecoratorslambdatype hints
Key Commands
def func(*args, **kwargs):@functools.wrapslambda x: x**2def greet(name: str) -> str:functools.partialArchitecture Overview
graph LR
CALL[greet name='Alice' title='Dr'] -->|positional| P[positional\nparams]
CALL -->|keyword| K[keyword\nparams]
CALL -->|extra pos| A[*args\ntuple]
CALL -->|extra kw| KW[**kwargs\ndict]
P --> FUNC[Function body]
K --> FUNC
A --> FUNC
KW --> FUNC
FUNC --> RET[return value]
style FUNC fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
Step-by-Step Process
01
Parameter Types
Understand all ways to pass arguments.
def create_user(name, age, *, admin=False, **extra):
# name, age = positional required
# admin = keyword-only (after *)
# extra = catch-all keyword args
print(name, age, admin, extra)
create_user('Alice', 25)
create_user('Bob', 30, admin=True, dept='Engineering')
# *args and **kwargs
def log(*args, **kwargs):
print(args, kwargs)
02
Decorators
Functions that wrap other functions.
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f'{func.__name__} took {time.time()-start:.3f}s')
return result
return wrapper
@timer
def slow_function():
time.sleep(0.1)
return 42
03
Type Hints
Add type annotations for better tooling and documentation.
from typing import Optional, Union, List
def greet(name: str, times: int = 1) -> str:
return ('Hello, ' + name + '! ') * times
def find_user(user_id: int) -> Optional[dict]:
# Returns dict or None
...
def process(data: Union[str, bytes]) -> List[str]:
...
Challenges & Solutions
- Mutable default arguments are shared across calls: def f(lst=[]): — use None instead
- functools.wraps preserves function metadata through decoration — always include it
Key Takeaways
- @staticmethod and @classmethod serve different purposes — understand both
- Type hints are not enforced at runtime but enable mypy static checking