I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing:
def visit1():
login()
do_stuff()
logout()
I could instead do
@handle_login
def visit1():
do_stuff()
However, after some experimenting, I have found that decorators are not as simple as I had hoped. First, I was confused by the different decorator syntax I found in different examples, until I learned that decorators behave very differently when they take arguments. Then I tried decorating a method, and eventually learned that it wasn't working because I first have to turn my decorator into a descriptor by adding a __get__
method. During this whole process I've ended up confused more than a few times and still find that debugging this "decorated" code is more complicated than it normally is for Python. I'm now re-evaluating whether I really need decorators in my code, since my initial motivation was to save a bit of typing, not because there was anything that really required higher-order functions.
So my question is: should decorators be used liberally or sparingly? Is it ever more Pythonic to avoid using them?