Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

 
 
Thread Tools Display Modes
Prev Previous Post in Thread   Next Post in Thread Next
Old Feb 23rd, 2006, 5:31 PM   #1
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,886
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
<3 Decorators

After noting the power of Arevos' cache function, I wanted to see how decorators worked.

I <3 Decorators, very handy for applying a common transformation easily to your functions. It's a useful thing to learn, and very easy to understand once you see its logic.


Here's one I made for my website

def serveError(func_name, func_code, func_error):
    return """<html>
<font face="courier new">
Server has encountered an error.<br />
<br />
      Error <i>%s</i><br />
In Function <b><i>%s</i></b><br />
         At <i>%s</i><br />
<br />
</font>
</html>"""%(func_error, func_name, func_code)



from sys import exc_info
def debug_wrapper(func):
    """If an error happens inside the function
    it will be caught and appropriately acted upon."""
    def new_func(*args):
        try:
            return func(*args)
        except:
            return serveError(func.func_name, func.func_code, exc_info()[0])
    return new_func




@debug_wrapper
def foo():
    raise KeyError


print foo()


Any function I put "@debug_wrapper" before, will now display something other then a CherryPy error.

Handy. Got any interesting ones?

Edit:

Here's Arevos' cache function:

def cached(func):
    """Creates a cached function.
    Cached function cannot handle keyword or mutable arguments."""
    store = {}
    def cached_func(*args):
        if not store.has_key(args):
            store[args] = func(*args)
        return store[args]
    return cached_func

@cached
def foo(x):
    return len(x)

print foo("Hello World!") # calculates and prints 12
print foo("Hello World!") # prints 12 without calculating
Sane is offline   Reply With Quote
 

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 10:53 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC