Typical Uses and Uses for Python Decorators

Having recently read this article about Python decorators, she cited the memoization technique as an example of a Python decorator application. Although I have a good understanding of Python decorators, I would like to learn about such effective cases of using decorators and how you usually use them in your everyday code.

+3
source share
4 answers

There are a number of built-decorators, which may be useful, for example classmethod, property, staticmethodand functools.wrap. It is often convenient to write a decorator that registers the use of functions for debugging purposes. There are many examples of decorators on this page of the Python wiki , although in my opinion at least some of them are more aimed at showing how flexible Python is actually providing useful functions.

+2
source

Since Python 3 supports type annotations, decorators can be used as a way to validate.

def check(f):
    def _f(x):
        if type(x) != f.__annotations__['x']:
            raise TypeError(type(x))
        val = f(x)
        if 'return' in f.__annotations__ and f.__annotations__['return'] != type(val):
            raise TypeError(type(val))
        return val
    return _f

@check
def f(x: int) -> int:
    return x * 2

>>> f(2)
4

>>> f('x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in _f
TypeError: <class 'str'>
+1
source

python - Django auth docs. ( ) , ..

0
source

This is a practical example. Take a look at the sum of a Fibonacci series with and without a record.

from functools import wraps
def memo(func): 
    cache = {}
    @wraps(func)
    def wrap(*args):
        if args not in cache: 
            cache[args] = func(*args)
        return cache[args] 
    return wrap

def fib(i):
    if i < 2: return 1
    return fib(i-1) + fib(i-2)

@memo
def fib_memo(i):
    if i < 2: return 1
    return fib_memo(i-1) + fib_memo(i-2)

And now check the speed difference!

>>> print fib(200)
...
>>> print fib_memo(200)
...
0
source

All Articles