[Edu-sig] illustrating a class wrapper

Kirby Urner kurner at oreillyschool.com
Wed Apr 17 08:31:24 CEST 2013


def g(x): return x + 2

class Hijack:

    def __init__(self, f):
        self.f = g

    def __call__(self, x):
        return self.f(x)


@Hijack
def f(x): return x * x

print(f(10))

print(f(100))

The code above shows a decorator, Hijack, that takes a function g from the
global namespace and swaps it in for another function f.

This might be useful for debugging.  You have a new version of a function
you want to try and by defining it under another name, yet swapping it in
by Hijack, you get to pretend you're using the new version instead.

A wrapper function could do the same thing plus take g as an argument:

from functools import wraps

def g(x): return x + 2

def Hijack2(newf):
    def decorated(func):
        @wraps(func)
        def swap(x):
            return newf(x)
        return swap
    return decorated


@Hijack2(g)
def f(x):
    """
    2nd power
    """
    return x * x

print(f(10))   # 10 + 2
print(f(100)) # 100 + 2
print(f.__doc__)

Executing:

12
102

    2nd power


Kirby
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20130416/f11768d0/attachment.html>


More information about the Edu-sig mailing list