Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions primer-on-python-decorators/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Primer on Python Decorators

Code examples from the [Primer on Python Decorators](https://realpython.com/primer-on-python-decorators/) tutorial on [Real Python](https://realpython.com/).

## Decorators

As noted in the article, most decorators are stored in the file [`decorators.py`](https://github.com/realpython/materials/blob/master/primer-on-python-decorators/decorators.py). The exceptions are those decorators that depend on third party packages ([Flask](http://flask.pocoo.org/) and [Pint](https://pint.readthedocs.io/)), which are available in [`decorators_flask.py`](https://github.com/realpython/materials/blob/master/primer-on-python-decorators/decorators_flask.py) and [`decorators_unit.py`](https://github.com/realpython/materials/blob/master/primer-on-python-decorators/decorators_unit.py), respectively.

## Examples

Most of the code examples from the article are available in the [`examples.py`](https://github.com/realpython/materials/blob/master/primer-on-python-decorators/examples.py) file.
173 changes: 173 additions & 0 deletions primer-on-python-decorators/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""Examples of decorators

See https://realpython.com/primer-on-python-decorators/

The decorators with dependencies outside of the standard library (Flask
and Pint) are available in separate files.
"""

import functools
import time


PLUGINS = dict() # Dictionary used by @register to store plugins


def do_twice(func):
"""Run the decorated function twice"""

@functools.wraps(func)
def wrapper_do_twice(*args, **kwargs):
func(*args, **kwargs)
return func(*args, **kwargs)

return wrapper_do_twice


def timer(func):
"""Print the runtime of the decorated function"""

@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Finished {func.__name__!r} in {run_time:.4f} secs")
return value

return wrapper_timer


def debug(func):
"""Print the function signature and return value"""

@functools.wraps(func)
def wrapper_debug(*args, **kwargs):
args_repr = [repr(a) for a in args]
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
signature = ", ".join(args_repr + kwargs_repr)
print(f"Calling {func.__name__}({signature})")
value = func(*args, **kwargs)
print(f"{func.__name__!r} returned {value!r}")
return value

return wrapper_debug


def slow_down_1sec(func):
"""Sleep 1 second before calling the function"""

@functools.wraps(func)
def wrapper_slow_down(*args, **kwargs):
time.sleep(1)
return func(*args, **kwargs)

return wrapper_slow_down


def register(func):
"""Register a function as a plug-in"""
PLUGINS[func.__name__] = func
return func


def repeat(_func=None, *, num_times=2):
"""Run the decorated function the given number of times"""

def decorator_repeat(func):

@functools.wraps(func)
def wrapper_repeat(*args, **kwargs):
for _ in range(num_times):
value = func(*args, **kwargs)
return value

return wrapper_repeat

if _func is None:
return decorator_repeat
else:
return decorator_repeat(_func)


def count_calls(func):
"""Count the number of calls made to the decorated function"""

@functools.wraps(func)
def wrapper_count_calls(*args, **kwargs):
wrapper_count_calls.num_calls += 1
print(f"Call {wrapper_count_calls.num_calls} of {func.__name__!r}")
return func(*args, **kwargs)

wrapper_count_calls.num_calls = 0
return wrapper_count_calls


class CountCalls:
"""Count the number of calls made to the decorated function"""

def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.num_calls = 0

def __call__(self, *args, **kwargs):
self.num_calls += 1
print(f"Call {self.num_calls} of {self.func.__name__!r}")
return self.func(*args, **kwargs)


def slow_down(_func=None, *, rate=1):
"""Sleep given amount of seconds before calling the function"""

def decorator_slow_down(func):

@functools.wraps(func)
def wrapper_slow_down(*args, **kwargs):
time.sleep(rate)
return func(*args, **kwargs)

return wrapper_slow_down

if _func is None:
return decorator_slow_down
else:
return decorator_slow_down(_func)


def singleton(cls):
"""Make a class a Singleton class (only one instance)"""

@functools.wraps(cls)
def wrapper_singleton(*args, **kwargs):
if not wrapper_singleton.instance:
wrapper_singleton.instance = cls(*args, **kwargs)
return wrapper_singleton.instance

wrapper_singleton.instance = None
return wrapper_singleton


def cache(func):
"""Keep a cache of previous function calls"""

@functools.wraps(func)
def wrapper_cache(*args, **kwargs):
cache_key = args + tuple(kwargs.items())
if cache_key not in wrapper_cache.cache:
wrapper_cache.cache[cache_key] = func(*args, **kwargs)
return wrapper_cache.cache[cache_key]

wrapper_cache.cache = dict()
return wrapper_cache


def set_unit(unit):
"""Register a unit on a function"""

def decorator_set_unit(func):
func.unit = unit
return func

return decorator_set_unit
43 changes: 43 additions & 0 deletions primer-on-python-decorators/decorators_flask.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Examples of decorators that work with Flask

See https://realpython.com/primer-on-python-decorators/

These decorators depend on the third party package Flask:

http://flask.pocoo.org/
"""

import functools

# pip install Flask
from flask import abort, g, request, redirect, url_for


def login_required(func):
"""Make sure user is logged in before proceeding"""

@functools.wraps(func)
def wrapper_login_required(*args, **kwargs):
if g.user is None:
return redirect(url_for("login", next=request.url))
return func(*args, **kwargs)

return wrapper_login_required


def validate_json(*expected_args):
"""Validate that a json-request contains the expected parameters"""

def decorator_validate_json(func):

@functools.wraps(func)
def wrapper_validate_json(*args, **kwargs):
json_object = request.get_json()
for expected_arg in expected_args:
if expected_arg not in json_object:
abort(400)
return func(*args, **kwargs)

return wrapper_validate_json

return decorator_validate_json
38 changes: 38 additions & 0 deletions primer-on-python-decorators/decorators_unit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""Examples of decorators dealing with units

See https://realpython.com/primer-on-python-decorators/

These decorators depend on the third party package Pint:

http://pint.readthedocs.io/
"""

import functools

import pint # pip install Pint


def set_unit(unit):
"""Register a unit on a function"""

def decorator_set_unit(func):
func.unit = unit
return func

return decorator_set_unit


def use_unit(unit):
"""Have a function return a Quantity with given unit"""
use_unit.ureg = pint.UnitRegistry()

def decorator_use_unit(func):

@functools.wraps(func)
def wrapper_use_unit(*args, **kwargs):
value = func(*args, **kwargs)
return value * use_unit.ureg(unit)

return wrapper_use_unit

return decorator_use_unit
Loading