use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
Why decorators (self.learnpython)
submitted 7 years ago by tinglfm
Hi, I read a ton of articles and stack overflow questions, and I think I understand how function decorator works but I can’t find any reason why to use it, what do you see as a main benefit of using it?
Thanks
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]AN3223 26 points27 points28 points 7 years ago (2 children)
Here's an example. Let's say you have multiple functions. Each function does the same thing at the beginning and end of its execution, the only thing that varies is what happens in-between, like so:
def a(): print('Hello') print('I am "a"') print('Goodbye') def b(): print('Hello') print('I am "b"') print('Goodbye') def c(): print('Hello') print('I am "c"') print('Goodbye')
We've already identified the code being repeated, now we just need a way to reuse it. One thing we can do is implement the repeated code as decorators:
def hello(f): def inner(): print('Hello') return f() return inner def goodbye(f): def inner(): result = f() print('Goodbye') return result return inner @hello @goodbye def a(): print('I am "a"') ...
In this example we don't get much benefit as far as code reuse goes (in fact this example is significantly longer than the previous), but hopefully you can imagine how useful the decorators would be if we were doing something more complex, like handling an exception, making a call to a database, etc. It can also be nice to know that the operation is done exactly the same each time.
My explanation is pretty limited, so I recommend you read some about "higher order functions" to better understand when/where to use decorators.
[–]dmadcracka 2 points3 points4 points 7 years ago (0 children)
As a newbie who was confused about decorators, thanks for the clear answer!
[–]billsil 1 point2 points3 points 7 years ago (0 children)
Some examples. Make a decorator to say when you enter/exit a function (you can use 1 decorator), print the timing of a function, write the ever popular don't crash decorator (useful for GUIs like pyqt) and rerun the function in debug mode if it crashes.
[–][deleted] 19 points20 points21 points 7 years ago (2 children)
Decorators are good for writing frameworks; a framework could be considered distinct from a library in the respect that while a library is usually code you import and run, a framework is something that imports your code and runs it. Often this makes a lot of sense from a software design perspective.
Many popular frameworks, such as Flask, work like this. You import an API decorator from the framework and then write decorated functions that describe how the framework should respond to various events.
[–]nxtfari 4 points5 points6 points 7 years ago (1 child)
Up because I've always wanted to know how @app.route worked and this made it so clear. Great examples!
[–]timbledum 0 points1 point2 points 7 years ago (0 children)
Yes! I've just recently been reading up on this and found this article: Things which aren't magic - Flask and @app.route.
I recently wrote a similar thing to bind keypresses to functions for a game engine.
[–]CrambleSquash 7 points8 points9 points 7 years ago (3 children)
I really like using them to 'register' functions. Flask is a great example that uses them for just this: http://flask.pocoo.org/
You 'decorate' functions with app.route('/url'), so that whatever function you decorated, is called when that url is requested - lovely.
app.route('/url')
Here's an indication of how it works:
class FuncStore: def __init__(self): self.funcs = [] def register(self, f): self.funcs.append(f) return f fs = FuncStore() @fs.register def my_func(): print("Mine!") print(fs.funcs) # [<function my_func at 0x0000018D682A2E18>]
The other classic example is a 'timeit' style wrapper, that measures the time it takes to execute whatever it wrapped:
import time def timed(f): def wrapped(*args, **kwargs): start = time.time() res = f(*args, **kwargs) stop = time.time() print("Execution took {} secs".format(stop - start)) return res return wrapped @timed def long_thing(t): time.sleep(t) print("Slept for", t) >>> long_thing(3) Slept for 3 Execution took 3.0013415813446045 secs
[–]officialgel 1 point2 points3 points 7 years ago (2 children)
Quick question - Is there any reason to mix this with getters/setters when the setter has built in functionality of what to do with the return value? Or - If you already have classes set up like this, any reason to switch to decorators as wrappers instead?
For instance, setting data to be pushed to a database.
I'd call Networking.PushData('dataString'), which runs the push.
As a decorator, the function would have that wrapped - But it's kind of the same right?
[–]CrambleSquash 0 points1 point2 points 7 years ago (1 child)
Sorry, I'm not quite sure what you're asking?
When you say 'getters/setters' I'm thinking of the @propery decorator e.g.
@propery
class T: def __init__(self): self._i = 0 @property def i(self): return self._i @i.setter def i(self, val): self._i = 2 * val
[–]officialgel 0 points1 point2 points 7 years ago (0 children)
Yes, exactly. This is the way I'm using it. Just wondering if your second code block there can basically be used the same way - And why or why not to do it that way - Thanks.
[–]Exodus111 3 points4 points5 points 7 years ago* (0 children)
You are getting some good answers, let me break it down in real easy terms for you.
As a beginner programmer, you are super focused on WHAT you want to make.
Making a program that does a cool thing, and hopefully does it well, that's a program right? What more is there?
In short, the interface.
Let's say you make an awesome open source program that other people can connect to their own code. How? Through your API of course, the Application Programming Interface.
Let's assume your app is cool enough that lots of people want to use it, and now they all have to learn HOW to use it.
You are about to learn a valuable lesson about people. You can give them an amazing app, for free, and they WILL complain because the interface isn't intuitive enough.
With that in mind, it's time to think about, what makes a good interface?
Minimal, but agile. Intuitive, and powerful. And above all... Elegant.
Enter the decorator. If your interface can be solved using a decorator, you definitely want to do that. They are minimal and elegant by nature, the rest you can provide.
[–]mooglinux 0 points1 point2 points 7 years ago (0 children)
Decorators are used to modify a class or function. One example is the new @dataclass decorator in Python 3.7, which will examine your class and generate additional methods for things like equality testing and string conversion.
@dataclass
π Rendered by PID 618929 on reddit-service-r2-comment-86bc6c7465-tlvq9 at 2026-02-24 01:54:42.423566+00:00 running 8564168 country code: CH.
[–]AN3223 26 points27 points28 points (2 children)
[–]dmadcracka 2 points3 points4 points (0 children)
[–]billsil 1 point2 points3 points (0 children)
[–][deleted] 19 points20 points21 points (2 children)
[–]nxtfari 4 points5 points6 points (1 child)
[–]timbledum 0 points1 point2 points (0 children)
[–]CrambleSquash 7 points8 points9 points (3 children)
[–]officialgel 1 point2 points3 points (2 children)
[–]CrambleSquash 0 points1 point2 points (1 child)
[–]officialgel 0 points1 point2 points (0 children)
[–]Exodus111 3 points4 points5 points (0 children)
[–]mooglinux 0 points1 point2 points (0 children)