There’s an amazing pattern in Python, called function decorators. It’s a set of declarations at the top of a function definition, that slightly enhances how the function behaves without actually polluting the function definition with related logic. I find it a really neat way to define a function and to re-use these enhancements/additional logic across functions.
Here’s the short version:
Say, you have a couple of decorators.
One, which logs the return value of the function it decorates.
Two, which makes sure the function is called exactly and only once, no matter how many times it gets invoked.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Or you can go for another version, if you aren’t really a fan of two liners.
1 2 3
All done! Now every time you call your function, it passes through the decorators around it.
The logic is pretty straightforward considering you are familiar with higher order functions.
1 2 3 4 5 6 7 8 9 10 11 12
Be cautious when you write a decorator that modifies the return value / parameters of the function. This could cause potential breakage of other decorators.
Be careful when you decorate a method. Make sure
decoratedMyFunction is properly bound to the intended context. E.g