On this page
Decorators and Closures
Prev: Iterators and Generators | Up: Advanced Python Internals | Next: Concurrency and Parallelism
Rel: python decorators, python metaprogramming, functools, property
Ref: docs.python.org — functools
Tags: #public #python3 #tutorials #internals #decorators #closures
Contents
- > Closures & Free Variables
- > Function Decorators & `@functools.wraps`
- > Parameterized & Class Decorators
- > Built-in & Stdlib Decorators (`functools`)
Closures & Free Variables
A closure is a nested function that captures references to variables from its enclosing scope inside cell objects (fn.__closure__), even after the enclosing function has returned.
def make_multiplier(factor: int):
def multiply(value: int) -> int:
return value * factor
return multiply
double = make_multiplier(2)
print(double(21)) # 42
print([cell.cell_contents for cell in double.__closure__]) # [2]
Function Decorators & @functools.wraps
@decorator is syntactic sugar for func = decorator(func). Always apply [[stdlib_module/functools|@functools.wraps(func)]] to the wrapper so __name__, __doc__, __qualname__, and __wrapped__ are preserved.
from functools import wraps
import time
def timed(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = (time.perf_counter() - start) * 1000
print(f"{func.__name__} took {elapsed:.3f} ms")
return wrapper
@timed
def compute_sum(n: int) -> int:
"""Sum integers from 0 to n - 1."""
return sum(range(n))
assert compute_sum.__name__ == "compute_sum"
print(compute_sum(10_000))
Parameterized & Class Decorators
A parameterized decorator is a decorator factory (an outer function returning the actual decorator). A class decorator takes a class object, augments or wraps it, and returns a class.
from functools import wraps
def retry(attempts: int = 3):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
last_exc = None
for _ in range(attempts):
try:
return func(*args, **kwargs)
except Exception as exc:
last_exc = exc
raise last_exc
return wrapper
return decorator
def register_in(registry: dict):
def decorator(cls):
registry[cls.__name__] = cls
return cls
return decorator
PLUGINS: dict[str, type] = {}
@register_in(PLUGINS)
class CsvExporter:
pass
print(PLUGINS) # {'CsvExporter': <class '...CsvExporter'>}
Built-in & Stdlib Decorators (functools)
functools.lru_cache/functools.cache— memoize pure functions.functools.singledispatch— dispatch a generic function by the type of its first argument.functools.total_ordering— derive<, <=, >, >=from__eq__and one ordering method.
from functools import cache, singledispatch
@cache
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
@singledispatch
def serialize(value) -> str:
return str(value)
@serialize.register
def _(value: list) -> str:
return "[" + ", ".join(serialize(v) for v in value) + "]"
print(fib(30), serialize([1, 2, 3]))
Linked from
- tuts/python3/python decorators
- tuts/python3/tutorials
- tuts/python3/tutorials/advanced_python_internals
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism
- tuts/python3/tutorials/advanced_python_internals/decorators_and_closures
- tuts/python3/tutorials/advanced_python_internals/iterators_and_generators
Related notes
- tuts/python3/tutorials/advanced_python_internals Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/concurrency_and_parallelism Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/iterators_and_generators Linked here; links to this page; shared tags: #internals, #tutorials
- tuts/python3/python decorators Linked here; links to this page; shared tags: #decorators
- tuts/python3/tutorials links to this page; shared tags: #tutorials
- tuts/python3/__builtins__/property Linked here
- tuts/python3/python metaprogramming Linked here
- tuts/python3/stdlib_module/functools Linked here
- tuts/javascript/tutorials/prototype_chain_and_new_flow shared tags: #internals, #tutorials
- tuts/python3/tutorials/advanced_python_internals/foreign_function_interfaces shared tags: #internals, #tutorials