0

I'm learning Python and am up to decorators.

I'm trying to understand why they would be used.

If I code a veeeeeery simple decorator,

def new_func(inserted_func):
    def wrap_func():
        print("Start")
        inserted_func()
        print("End")
    return wrap_func

@new_func
def existing_func():
    print("Middle")

existing_func()

It will return,

Start
Middle
End

But I could also achieve the same thing by coding,

def func1():
    print("Start")

def func2():
    print("Middle")

def func3():
    print("End")

func1()
func2()
func3()

Now I appreciate that my decorator function is very simple, but, other than "because you can", what are the reasons for choosing decorators over multiple functions?

Paul65
  • 19
  • 1
    Nothing...for the very limited case that you gave. Here are some tasks for you: 1. Add logging of arguments and return values to every single function in your python codebase 2. Add memoization to every pure function in your codebase 3. Add performance timing to every function in your codebase. Now, do you want to edit every single function in your codebase by hand, or do you want to write a couple of decorators? – Jared Smith Mar 18 '20 at 12:06
  • 1
    Simplicity's sake and reusability. The exact reason why we use functions as well. Imagine that you'd have to write the staticmethod decorator every time you start a new project! – Bram Vanroy Mar 18 '20 at 12:07
  • Or this: https://stackoverflow.com/questions/489720/what-are-some-common-uses-for-python-decorators – Jared Smith Mar 18 '20 at 12:08
  • Well, imagine that you need to call that wrapped function more than once. Would you prefer typing the three call for the price of one each time? – bipll Mar 18 '20 at 12:08

2 Answers2

1

Your example for the decorator is most likely the reason you are thinking to yourself "why, mein gott WHY!?"

but please take a look at, for example, flash solutions for routing (tutorial: https://medium.com/python-pandemonium/build-simple-restful-api-with-python-and-flask-part-1-fae9ff66a706)

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

The decorator here is doing you a great favor by letting you just create code, without having to manually type whatever is inside the @app.route() decorator.

Remember DRY? Decorators are an easy way to reuse code in many places. Again, the route example allows you to use one decorator across the entire project with different parameters, and everything just works.

Unamata Sanatarai
  • 5,920
  • 3
  • 25
  • 47
  • Gang, this question has been asked on SO multiple times already. Please don't answer dupes, flag for closure instead. – Jared Smith Mar 18 '20 at 12:09
0

You can write a decorator that:

  • measures the executiong time of a method: self explanatory
  • modifies the input parameter(s) of a method: You want to reuse the method several times but the logic differs slightly depending on the current object you have. -> You write multiple decorators that trim your input into the correct format
  • modifies the return parameter(s) of a method: same reasoning
  • ...

Decorators can be a really powerful tool to write more advanced code. You can live without them but at some point your code will get messy.

More importantly decorators are reusable and can be applied to any method. You write that logic once and slap it on any method you need.

Tin Nguyen
  • 4,803
  • 1
  • 8
  • 27
  • Gang, this question has been asked on SO multiple times already. Please don't answer dupes, flag for closure instead. – Jared Smith Mar 18 '20 at 12:09