Interesting decorator use.

Tom Willis tom.willis at gmail.com
Thu Feb 24 15:42:58 EST 2005


On Thu, 24 Feb 2005 11:15:07 -0800, Scott David Daniels
<Scott.Daniels at acm.org> wrote:
> 
> I have started doing the following to watch for exceptions in wxPython.
> I'd like any input about (A) the interface, and (B) the frame before I
> throw it in the recipes book.
> 
>      import wx, os, sys
>      errorframe = None
> 
>      def watcherrors(function):
>          '''function decorator to display Exception information.'''
>          def substitute(*args, **kwargs):
>...

Pretty cool.

Question on decorators in general. Can you parameterize those?

If I wanted to something and after the function call for example, I
would expect something like this would work.

def prepostdecorator(function,pre,post):
    def wrapper(*args,**kwargs):
        pre()
        result =  function(*args,**kwargs)
        post()
        return result
    return wrapper

def dopre():
    print "call pre"

def dopost():
    print "call post"

@prepostdecorator(pre,post)
def sayhello(Name):
    print "Hey %s, nice to meet you" % Name

#sayhello = prepostdecorator(sayhello,dopre,dopost)

if __name__=="__main__":
    sayhello("Dude")



but I get ...
TypeError: prepostdecorator() takes exactly 3 arguments (2 given)


Where as 

def prepostdecorator(function,pre,post):
    def wrapper(*args,**kwargs):
        pre()
        result =  function(*args,**kwargs)
        post()
        return result
    return wrapper

def dopre():
    print "call pre"

def dopost():
    print "call post"

def sayhello(Name):
    print "Hey %s, nice to meet you" % Name

sayhello = prepostdecorator(sayhello,dopre,dopost)

if __name__=="__main__":
    sayhello("Dude")

#outputs
call pre
Hey Dude, nice to meet you
call post

Does what I want.


I guess I'm having problems with how function get's in there similair
to how self magically gets in a method, except when you specify other
params. Got linky?



-- 
Thomas G. Willis
http://paperbackmusic.net



More information about the Python-list mailing list