Decorators not worth the effort

88888 Dihedral dihedral88888 at googlemail.com
Tue Sep 18 19:47:44 EDT 2012


Terry Reedy於 2012年9月15日星期六UTC+8上午4時40分32秒寫道:
> 2nd try, hit send button by mistake before
> 
> 
> 
> On 9/14/2012 5:28 AM, Jean-Michel Pichavant wrote:
> 
> 
> 
> > Decorators are very popular so I kinda already know that the fault is
> 
> > mine. Now to the reason why I have troubles writing them, I don't
> 
> > know. Every time I did use decorators, I spent way too much time
> 
> > writing it (and debugging it).
> 
> 
> 
> You are writing parameterized decorators, which require inverted 
> 
> currying of the wrapper maker. Perhaps that is why you have trouble. As 
> 
> I showed in response to Cameron, it may be easier to avoid that by using 
> 
> a traditional post-def wrapping call instead of decorator syntax.
> 
> 
>  
> -- 
> 
> Terry Jan Reedy

I'll give another example to show the decorators in python in
versions above 2.4 .

# a general function with the variable input : def  fname( *argc,  **argn)
# a deco is a mapping from an input  funtion to another  function

def deco( fn, *list_in, **dict_in): # use list_in and dict_in to modify fn
    """ deco wrapper """ # deco.__doc__ 

    #print list_in, dict_in, " in the deco"
 
    def wrapper( fn, *argc, **argan): # to be returned as a function
       # do things one wants before calling fn 
       result=fn(*argc, **argn)  # call the original, save the result
       # do things after calling fn   
       return result 
    # enhance the  wrapper and get info of fn
    wrapper.__doc__=fn.__doc__
    # enhance wrapper with result, fn, list_in, dict_in
    #....
     return wrapper

def f1():
   """ doc of f1"""
   print "inside f1"

f2=deco(f1, 2,3,4,5,6, MSG="deco f1 to f2")

f2() # invoke the decorated function from f1


# For a deco maps a deco to another deco  can be done similarly





More information about the Python-list mailing list