Simple Function Decorator Sample Snippet
Mark H Harris
harrismh777 at gmail.com
Tue May 13 00:41:18 EDT 2014
hi folks, I've come up with a simple snippet that intends to explain the
concept of decorations without an article (for on app help), while being
succinct and concise, while not being overly complicated.
Does this work? I have another one coming for args, similar, if this
works... comments appreciated. thanks.
> # BEGIN FUNCTION DECORATOR SIMPLE ################################
> #
> # define the function decorator (wrapper function)
> def enter_exit(f):
> def new_f():
> print("entering", f.__name__)
> f()
> print(f.__name__, "exited !", end="\n\n")
> return new_f
>
> # the above "function decoration" takes a 'callable' as an argument
> # and returns a 'callable' new function that is used to
> # replace the original function (function is decorated), which
> # adds functionality to the original function being decorated ...
>
> # define the original function
> def f1():
> print(" inside f1()")
>
> # replace the original function (above) with the new decorated
> # 'wrapped' function using the function decoration 'enter_exit'...
> f1 = enter_exit(f1)
>
> # (OR) accomplish the same thing with decoration lines as below:
>
> # functions wrapped with decoration lines syntax (annotations)
> # as below, accomplish the same 'decoration' as above
> # by using some 'syntactic sugar' to accomplish same ...
>
> @enter_exit
> def f2():
> print(" inside f2()")
>
> @enter_exit
> def f3():
> print(" inside f3()")
>
> # demo the new 'decorated' functions
> f1()
> f2()
> f3()
>
> # END FUNCTION DECORATOR SIMPLE ##################################
More information about the Python-list
mailing list