Real Python Cheat Sheet
Real Python Cheat Sheet
Real Python Cheat Sheet
realpython.com
The normal way of using a decorator is by specifying it just before the definition of If you don’t want to change the decorated function, a decorator is simply a func-
the function you want to decorate: tion taking in and returning a function:
If you want to decorate an already existing function you can use the following syn- Example: Register a list of decorated functions.
tax:
def register(func):
f = decorator(f) """Register a function as a plug-in"""
PLUGINS[func.__name__] = func
return func
realpython.com 1
Python Decorators Examples
Basic decorator
Template for basic decorator that can modify the decorated function: Example: A timer decorator that prints the runtime of a function.
If you want your decorator to take arguments, create a decorator factory that can Example: Rate limit your code by sleeping a given amount of seconds before call-
create decorators: ing the function.
realpython.com 2
Python Decorators Examples
If you want your decorator to be able to be called with or without arguments, you Example: Rate limit your code by sleeping an optionally given amount of seconds
need a dummy argument, _func, that is set automatically if the decorator is called before calling the function.
without arguments:
import functools
import functools import time
If you need your decorator to maintain state, use a class as a decorator: Example: Count the number of times the decorated function is called.
realpython.com 3