Pythonic Wonders: Cache, Decorate, Parameterize, Memoize, and Mock!
The following passage was written by a friend of mine. It is so captivating. I like it! If you also like it, please reach out to him on twitter and tell him!
Enjoy!
First it was cache. And then decorate. And now parameterize, memoize, and mock!!!
Python never ceases to amaze!
So what, if any, do these have in common, besides being wrapped together in a module? A lot!
Memoization is a use case for caching, i.e., memoization is caching when the cached thing is the result of a function call; in that case, the function being cached has to be designed to maintain the cache. And if the function is not natively able to memoize, it’s easy - you decorate it! Remember, decoration is that magic that makes a function appear to do more than what it is born to do, without it having to be born again.😀 Just memoize it! By decorating it!
And after that, you can even mock it. Yes, that’s right - pretend to be the function when you are a pure fake! And it’s easy to do that too - just import Mock from unittest.mock and create a mock object and make it fake to return anything you wish! Or, if you are enjoying the pun, try MagicMock. Same stuff, with more Python magic sprinkled on it.😀
And oh, I almost forgot: while you’re at it, there is more fun - you can make multiple tests more cool - just parameterize it. That is, use one test with parameters to do several others at once, like killing several birds with one stone.
See? It’s easy when you think about it!
No cache😀
🤩Do.Pythonic.Things