<div dir="ltr"><div><div><br>def g(x): return x + 2<br><br>class Hijack:<br><br> def __init__(self, f):<br> self.f = g<br><br> def __call__(self, x):<br> return self.f(x)<br><br><br>@Hijack<br>def f(x): return x * x<br>
<br>print(f(10))<br><br>print(f(100))<br><br></div>The code above shows a decorator, Hijack, that takes a function g from the global namespace and swaps it in for another function f. <br><br>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.<br>
<br></div>A wrapper function could do the same thing plus take g as an argument:<br><br>from functools import wraps<br><br>def g(x): return x + 2<br><br>def Hijack2(newf):<br> def decorated(func):<br> @wraps(func)<br>
def swap(x):<br> return newf(x)<br> return swap<br> return decorated<br><br><br>@Hijack2(g)<br>def f(x):<br> """<br> 2nd power<br> """<br> return x * x<br>
<br>print(f(10)) # 10 + 2<br>print(f(100)) # 100 + 2<br>print(f.__doc__)<br><br>Executing:<br><br>12<br>102<br><br> 2nd power<br> <br><div><br>Kirby<br><br></div></div>