I recently started experimenting with Python decorators (and higher-order functions) because it looked like they could make my Django universal tests more concise. for example, instead of writing:
def visit1():
login()
do_stuff()
logout()
Instead, I could
@handle_login
def visit1():
do_stuff()
However, after some experimentation, I found that decorators are not as simple as I had hoped. Firstly, I was confused by the syntax of different decorators, which I found in different examples, until I found out that decorators behave differently when they accept arguments . Then I tried to decorate the method and eventually found out that it does not work, because I must first turn my decorator into a descriptor by adding__get__. Throughout this process, I ended up embarrassing more than a few times, and still find that debugging this "decorated" code is more complicated than usual for Python. I am now overestimating if I really need decorators in my code since my initial motivation was to save a bit of input, and not because there was something really requiring higher functions.
So my question is: should decorators be used liberally or sparingly? Is it even more pythonic not to use them?
source
share