Code Challenge 14 - Write DRY Code With Decorators - Review

PyBites, Sat 15 April 2017, Challenges

codechallenges, decorators, design patterns, DRY, learning

It's end of the week again so we review the code challenge of this week: Write DRY Code With Decorators. It's never late to join, just fork us and start coding.

Our solution and learning

Getting our hands on decorators we enriched our Python toolkit! This one was also a lot of fun. See our solution here. We did a simple timeit one and a more complex mute_exception one. For the latter we needed this week's article: How to Write a Decorator with an Optional Argument?.

Some other things we learned:

Output 2 stacked decorators

When you run our solution it will print (fake) timings and mute/log the ZeroDivisionError exception:

$ python decorator-pb.py

div of args: (1, 4) took 0.755037784576416
div 1/4 = 0.25

div of args: (2, 5) took 0.763498067855835
div 2/5 = 0.4

div of args: (3, 0) took 0.09057903289794922
div 3/0 = 0

The program did not crash by the divide by 0, logging the exception:

$ tail decorators.log
...
...
00:58:36 root         DEBUG    div called for args (1, 4)
00:58:36 root         DEBUG    div called for args (2, 5)
00:58:37 root         DEBUG    div called for args (3, 0)
00:58:37 root         ERROR    div raised exception ZeroDivisionError for args: (3, 0)

Community

But there is more ... we got a nice PR with two other cool decorators:

Next Up

As you might have noticed (here and here) we are learning Flask so we thought it would be a great topic for our next challenge coming Monday. Stay tuned ...

We hope you are enjoying these challenges, learning along the way. Let us know if you have any issue and/or contact us if you want to submit a cool challenge. See you next week ...

PyBites Python Tips

Do you want to get 250+ concise and applicable Python tips in an ebook that will cost you less than 10 bucks (future updates included), check it out here.

Get our Python Tips Book

"The discussions are succinct yet thorough enough to give you a solid grasp of the particular problem. I just wish I would have had this book when I started learning Python." - Daniel H

"Bob and Julian are the masters at aggregating these small snippets of code that can really make certain aspects of coding easier." - Jesse B

"This is now my favourite first Python go-to reference." - Anthony L

"Do you ever go on one of those cooking websites for a recipe and have to scroll for what feels like an eternity to get to the ingredients and the 4 steps the recipe actually takes? This is the opposite of that." - Sergio S

Get the book