[Tutor] Question about python decorators

Peter Otten __peter__ at web.de
Mon Jul 11 12:57:17 EDT 2022


On 11/07/2022 12:58, nathan tech wrote:
> 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

@deco
def fun():
    ...

is basically a syntactic sugar for

def fun():
     ...

fun = deco(fun)

In your case you would write

function = object.event(function)

As this is just an ordinary function call followed by an ordinary
assignment you can of course use different names for the decorated and
undecorated version of your function and thus keep both easily accessible.


More information about the Tutor mailing list