In short, decorators allow you to inject orthogonal behavior before or after a function is executed.
But my favorite decorator definition is related to the construction and will help you easily create them: A callable that takes a callable and returns a callable.
2/
But my favorite decorator definition is related to the construction and will help you easily create them: A callable that takes a callable and returns a callable.
2/
What do I mean by "orthogonal"?
A function should do one thing. If you want to add caching or logging, it really isn't related to the function (and could be applied to multiple functions). It is "orthogonal" behavior.
3/
A function should do one thing. If you want to add caching or logging, it really isn't related to the function (and could be applied to multiple functions). It is "orthogonal" behavior.
3/
(Although Python has other *callables* like methods, classes, lambdas, or instances with .__call__. You can implement decorators with these, but we will ignore them here.)
5/
5/
To make a caching decorator, insert the logic to look for a prior answer in #before, and stick the result of the function in the cache in #after.
Here is an example that would cache in Redis:
gist.github.com
10/
Here is an example that would cache in Redis:
gist.github.com
10/
So back to the first image.
Here's your template for decorators.
The final bit with
@wraps
(func) updates .__name__ and .__doc__ so that code completion works in editors and you can pull up documentation.
11/
Here's your template for decorators.
The final bit with
@wraps
(func) updates .__name__ and .__doc__ so that code completion works in editors and you can pull up documentation.
11/
I have a book, Intermediate Python Programming, covering decorators and other fun constructs like generators, comprehensions, and functional programming.
store.metasnake.com
store.metasnake.com
That's a wrap!
If you enjoyed this thread:
1. Follow me @__mharrison__ for more of these
2. RT the tweet below to share this thread with your audience
If you enjoyed this thread:
1. Follow me @__mharrison__ for more of these
2. RT the tweet below to share this thread with your audience
Loading suggestions...