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
_______________________________________________ Edu-sig mailing list Edu-sig@python.org http://mail.python.org/mailman/listinfo/edu-sig