Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are decorators useful? [closed]

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?

like image 549
usual me Avatar asked Jan 23 '26 01:01

usual me


1 Answers

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.

like image 187
Steve Jessop Avatar answered Jan 27 '26 00:01

Steve Jessop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!