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