Python 3D Academyবাংলা

Wrappers that fit any function

🌍 In real life. A travel adapter has holes that fit any plug, and passes the electricity straight through to whatever you plug in. It doesn't care whether it's a phone charger or a hair dryer.

The wrappers in the last lesson only fitted functions with exactly one argument. A wrapper written with *args and **kwargs (Chapter 15) is like that adapter:

  • def wrapper(*args, **kwargs): accepts any arguments
  • func(*args, **kwargs) passes them straight through to the real function
  • so one decorator now fits every function, whatever its parameters

The idea in one sentence: a wrapper written as def wrapper(*args, **kwargs): accepts any arguments and passes them straight on with func(*args, **kwargs), so one decorator fits every function.

Its words:

  • *args, **kwargs: collect any positional and keyword arguments (Chapter 15)
  • pass-through: func(*args, **kwargs) spreads them back out for the original
  • function attribute: a value stored on the wrapper itself, like wrapper.calls
import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(func.__name__, "called with", args, kwargs)
        return func(*args, **kwargs)
    return wrapper

@log
def add(a, b):
    return a + b

@log
def greet(name, polite=False):
    return ("Good day, " if polite else "Hi, ") + name

print(add(2, 3))
print(greet("Ana", polite=True))
print(add.__name__)
@functools.wraps(func) copies the real function's name onto the wrapper, so add.__name__ still says add.

A wrapper can remember things, step by step. A shop counter clicks once for every customer. A decorator can count calls the same way:

  1. the wrapper is a function, and functions can carry attributes, like wrapper.calls = 0
  2. each time it runs, the wrapper adds one: wrapper.calls += 1
  3. after a few calls, greet.calls tells you how many there were
def counted(func):
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper

@counted
def serve(customer):
    return "served " + customer

serve("Ana")
serve("Bo")
serve("Cy")
print(serve.calls)

Mistakes and edge cases.

  • A wrapper with fixed parameters. def w(): around add(a, b) gives TypeError: d.<locals>.w() takes 0 positional arguments but 2 were given.
  • Forgetting the stars when passing on. func(args, kwargs) passes a tuple and a dict as two arguments; it must be func(*args, **kwargs).
  • Losing the function's name. The decorated function's __name__ becomes wrapper; @functools.wraps(func) above the wrapper keeps the original name and docstring.
  • Counting on the wrong object. Store the count on the wrapper (wrapper.calls), which is what the decorated name now points to.

Quiz

  1. What does this print?

    def passthrough(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        return wrapper
    
    @passthrough
    def area(w, h=1):
        return w * h
    
    print(area(3, h=4), area(5))
  2. Why write the wrapper as def wrapper(*args, **kwargs)?

    • So the decorator fits functions with any arguments
    • To make the function run faster
    • Because wrappers can't have named parameters
  3. What does this print?

    def counted(func):
        def wrapper(*args):
            wrapper.calls += 1
            return func(*args)
        wrapper.calls = 0
        return wrapper
    
    @counted
    def ping():
        return "pong"
    
    for _ in range(4):
        ping()
    print(ping.calls)
  4. What does this print?

    import functools
    
    def plain(func):
        def wrapper(*args):
            return func(*args)
        return wrapper
    
    def neat(func):
        @functools.wraps(func)
        def wrapper(*args):
            return func(*args)
        return wrapper
    
    @plain
    def one():
        return 1
    
    @neat
    def two():
        return 2
    
    print(one.__name__, two.__name__)
  5. Which line has a mistake? (log should work on any function.)

    def log(func):
        def wrapper():
            print("calling")
            return func()
        return wrapper
    
    @log
    def add(a, b):
        return a + b
    
    print(add(2, 3))

Coding tasks

  1. Write a decorator passthrough whose wrapper accepts any arguments and keywords, passes them to the function, and returns its result.

  2. Write a decorator counted that keeps a count of how many times the function has been called, in an attribute calls on the wrapper (starting at 0).

  3. Write a decorator keep_name that passes any arguments through and uses functools.wraps, so the decorated function keeps its own __name__.