Вопрос

So I read this page about decorators, but I still don't understand when decorators are useful.

Consider a piece of code defining a function f, and then calling it multiple times. For some reason we want f to do some extra work. So we have 2 ways to do it:

  1. define a new function g which calls f, and does the extra work needed. Then in the main code, replace all calls to f by calls to g
  2. define a decorator g, and edit the code to add @g before calls to f

In the end, they both achieve the same result and the advantage of 2) over 1) is not obvious to me. What am i missing?

Это было полезно?

Решение

Suppose you have a lot of functions f1, f2, f3, ... and you want a regular way to make the same change to all of them to do the same extra work.

That's what you're missing and it's why decorators are useful. That is to say, functions that take a function and return a modified version of it.

The decorator @ syntax is "just" for convenience. It lets you decorate the function as it is defined:

@decorated
def foo():
    # several lines

instead of somewhere after the function definition:

def foo():
    # several lines

foo = decorated(foo)

In fact of course the latter code is pretty horrible, since it means that by looking at the first definition of foo in the source, you don't see the same foo that users will call. So without the syntax, decorators wouldn't be so valuable because you'd pretty much always end up using different names for the decorated and undecorated functions.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top