Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #71424
| From | Mark H Harris <harrismh777@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Simple Function Decorator Sample Snippet |
| Date | 2014-05-12 23:41 -0500 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <lks7pd$gd0$1@speranza.aioe.org> (permalink) |
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 ##################################
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Simple Function Decorator Sample Snippet Mark H Harris <harrismh777@gmail.com> - 2014-05-12 23:41 -0500
Re: Simple Function Decorator Sample Snippet Steven D'Aprano <steve@pearwood.info> - 2014-05-13 05:54 +0000
Re: Simple Function Decorator Sample Snippet Mark H Harris <harrismh777@gmail.com> - 2014-05-13 01:04 -0500
Re: Simple Function Decorator Sample Snippet alister <alister.nospam.ware@ntlworld.com> - 2014-05-13 11:09 +0000
csiph-web