Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.etla.org!aioe.org!.POSTED!not-for-mail From: Mark H Harris Newsgroups: comp.lang.python Subject: Simple Function Decorator Sample Snippet Date: Mon, 12 May 2014 23:41:18 -0500 Organization: Aioe.org NNTP Server Lines: 52 Message-ID: NNTP-Posting-Host: RbLuqvdjwUNhJiyJQaji5Q.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:24.0) Gecko/20100101 Thunderbird/24.5.0 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.python:71424 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 ##################################