Understanding Python Decorators in 12 Easy Steps!
pythondecoratorsfunctional-programmingclosuresmetaprogramming
Abstraction: Step-by-step tutorial building Python decorators from first principles
Key points:
- Builds understanding from scratch: scope rules, variable lifetimes, nested functions, first-class functions, closures, then decorators
- Functions are first-class objects in Python — they can be passed as arguments and returned as values from other functions
- Closures: inner functions remember their enclosing scope at definition time via
func_closure; enables custom function factories - A decorator is a callable that takes a function and returns a replacement function;
@wrappersyntax is syntactic sugar forfoo = wrapper(foo) *argsand**kwargsenable generic decorators that can wrap functions with any signature@decorator syntax introduced in Python 2.4;functools.wrapspreserves the wrapped function's signature and docstring
Connections: Python · Decorators · Closures · Functional Programming
Source: http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/