Function wrapper in Python
William Annis
annis at biostat.wisc.edu
Mon Oct 9 13:34:39 EDT 2000
Olav.Benum at bigfoot.com writes:
> I would like to write a function-wrapper that takes a
> function and its arguments as arguments, redirect
> output, and calls the function within a try/catch
> block. Something like:
> def function_wrapper( funcname, *name **unnamed):
> try:
> funcname( name, unnamed )#??
> except OSError,error:
> print "General exception"
> if error:
> print str(error)
>
> def test_func( s ):
> print s
>
> function_wrapper( test_func , 'hello world')
One curious special method that receives too little attention
is __call__. This method is run when an instance is called like a
function. During my LISP days I became fond of memoizing functions.
That is, making them cache answers to complex questions to speed up
run time. Here's my memoizing class:
class memoize:
def __init__(self, fn):
self.fn = fn
self.args = {}
def __call__(self, *args):
if not self.args.has_key(args):
self.args[args] = apply(self.fn, args)
return self.args[args]
if __name__ == '__main__':
import math
msin = memoize(math.sin)
print msin(0), msin(math.pi/2), msin(math.pi/4)
You can wrap up your try/except block in __call__.
The other option, of course, is to use the 'apply' function,
which is more direct, which you'll notice I use in the __call__ method
above.
--
William Annis - System Administrator - Biomedical Computing Group
annis at biostat.wisc.edu PGP ID:1024/FBF64031
Mi parolas Esperanton - La Internacian Lingvon www.esperanto.org
More information about the Python-list
mailing list