Code snippets for Decorators and Descriptors Decoded

Functions as objects


In [ ]:
fruit = ['banana', 'grapefruit', 'lime', 'pineapple']
sorted(fruit, key=len)

In [ ]:
def fibonacci(n:int) -> int:
    '''returns the nth Fibonacci number'''
    a, b = 0, 1
    while n > 0:
        a, b = b, a + b
        n -= 1
    return a

In [ ]:
[fibonacci(n) for n in range(12)]

In [ ]:
# ?fibonacci

In [ ]:
fibonacci.__doc__

In [ ]:
fibonacci.__annotations__

In [ ]:
fibonacci.__code__.co_varnames

In [ ]:
from inspect import signature
signature(fibonacci).parameters

Decorators 101

Decorators are syntactic sugar


In [ ]:
def square(n):
    return n * n

square(3)

In [ ]:
from decolib import floatify

In [ ]:
@floatify
def square(n):
    return n * n

square(3)

In [ ]:
square

In [ ]:
??square

Decorators may replace the decorated function


In [ ]:
def deco(f):
    def inner():
        return 'inner result'
    return inner

@deco
def target():
    return 'original result'
    
target()

In [ ]:
target

In [ ]:
def double(n):
    return n * 2

double(4)

In [ ]:
blessed = []

def bless(f):
    blessed.append(f)
    return f  # Important: return a function!

In [ ]:
def double(n):
    return n * 2

In [ ]:
bless(double)

In [ ]:
@bless
def triple(n):
    return n * 3

In [ ]:
blessed

In [ ]:
def triple(n):
    return n * 3

triple = bless(triple)

In [ ]:
def square(n):
    return n * n

In [ ]:
square(3)

In [ ]:
square

functools.wraps


In [1]:
from decolib2 import floatify

@floatify
def square(n):
    """returns n squared"""
    return n * n

square(3)


Out[1]:
9.0

In [2]:
square


Out[2]:
<function __main__.square>

In [3]:
help(square)


Help on function square in module __main__:

square(n)
    returns n squared


In [4]:
??square

In [ ]: