[Tutor] Question about python decorators

avi.e.gross at gmail.com avi.e.gross at gmail.com
Mon Jul 11 13:51:01 EDT 2022


Nathan,

It depends on what you want to do.

Decorators are sort of syntactic sugar that you can sort of do on your own
if you wish. I am answering in general but feel free to look at some online
resources such as this:

https://realpython.com/primer-on-python-decorators/

The bottom line is that a function is just an object like anything else in
Python and you can wrap a function inside of another function so the new
function is called instead of the old one. This function, with the same
name, sort of decorates the original by having the ability to do something
using the arguments provided before calling the function, such as logging
the call, or making changes to the arguments or just doing validation and
then calling the function. After the inner (sort-of) function returns, it
can do additional things and return what it wishes to the original caller. 

I have no idea what your @object.event decorator is and what it does for
you, but presumably you can find one of several ways to apply it to a
completed function, including  slightly indirect methods albeit there may be
minor details that may not be quite right such as docstrings.

Say you already have a function called original() and you want to wrap it in
@interior as a decorator. Could you imagine something like this:

Copy "original" to "subordinate" so you have a new function name.

Then do this:

@interior
def original(args):
    return(subordinate(args))

Again, some details are needed such as matching the args one way or another
but the above is by your definition a new function definition, albeit with
some overhead! LOL!

Yes, I know what you are going to say. This is re-decoration!

But kidding aside, as I said, it may be even simpler and you may be able to
do something as simple as:

func = myobject.event(func)

Experiment with it. Or read a bit and then experiment. 



-----Original Message-----
From: Tutor <tutor-bounces+avi.e.gross=gmail.com at python.org> On Behalf Of
nathan tech
Sent: Monday, July 11, 2022 6:59 AM
To: Tutor at python.org
Subject: [Tutor] Question about python decorators

As I understand it, decorators are usuallyed created as:
@object.event
Def function_to_be_executed():
Do_stuff

My question is, is there a way to create this after the function is created?
So:
Def function():
Print("this is interesting stuff")

@myobject.event=function

Thanks
Nathan


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list