How often should Python decorators be used?

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?

+3
source share
4 answers

, , - ;-). , ", "?

/ , . , , @thisonetoo ;-). - , ( ). , .

- , . , , , , ( , , , ... , Python , DRY-, !).

, , ( ) - YAGNI (Y'An't Gonna Need It) DRY; -).

+12

, , , . (, ).

, Django, . , , , @login_required.

, , , , auth.

, , .

request.user.is_authenticated():   return HttpResponseREdiect (..)

+3

- .

- , , . , :

- -

. :

AOP (- ) ?

, .

, AOP.

+3

, , .

, ( ) - , .

0

Source: https://habr.com/ru/post/1711422/


All Articles