go back  14 - Write DRY Code With Decorators




This challenge write-up first appeared on PyBites.

There is nothing like a challenge to bring out the best in man. - Sean Connery

Hi Pythonistas, a new week, a new 'bite' of Python coding! This week we let you practice with decorators, a nice way to abstract away common functionality. It allows you to alter the behavior of a callable without modifying the callable itself. We agree with Dan Bader that 'understanding decorators is a milestone for any serious Python programmer.' Enjoy!

What is a decorator?

Decorators dynamically alter the functionality of a function, method, or class without having to directly use subclasses or change the source code of the function being decorated. (wiki)

It's basically a wrapper and it is a common design pattern.

If you are new to this concept we recommend Dan's nice walk-through he published last week: Python Decorators: A Step-By-Step Introduction.

Another great article is RealPython's Primer on Python Decorators.

Roll your own!

In this week's challenge we invite you to come up with useful decorators for yourself or the greater community. We have included a bit of material in our repo to get started.

Tomorrow we will post an article on how to write decorators that take optional arguments. This caused us some pain, but we got it working. It might be useful to write more flexible decorators. Stay tuned ...

Getting ready

See our INSTALL doc how to fork our challenges repo to get cracking. If you want to share your solution do a PR and we will add it to our community branch and link to it in our end-of-the-week review.

Archive

You can find all our code challenges so far here. If you have ideas for a future challenge or find any issues, please contact us or open a GH Issue.

Last but not least: there is no best solution, only learning more and better Python. Good luck!


Keep Calm and Code in Python!

-- Bob and Julian