Function wrapper in Python
Alex Martelli
aleaxit at yahoo.com
Tue Oct 10 05:22:39 EDT 2000
<Olav.Benum at bigfoot.com> wrote in message
news:39E1F408.A03AF6E7 at yahoo.com...
>
> 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)
All of these arguments are misleadingly named (the first
one, as shown from later example, is a function and NOT
a function-name, etc), but, anyway:
def function_wrapper(thefunc, *args, **kwds):
try:
return apply(thefunc, args, kwds)
except OSError, error:
print "General exception"
if error: print str(error)
In Python 2.0 you can change the return-line to:
return thefunc(*args, **kwds)
but that's not much of an advantage, in this case,
over using the builtin function apply, so I'd
suggest using apply anyway.
> (Ideally I would like something like having an abstract
> base-class with the function name as an abstract method,
> from this I would derive a class for my function, and
> then call the init function like FucntionInstance(
> Arguments)
Sorry, but this part of your request is not very clear to
me. It's certainly feasible to wrap a function through a
class instance, or to wrap a class instance, etc, but what
you exactly want, I can't quite fathom -- also, again I
think I see some confusion between a function and its name.
Maybe if you post a complete, short example of code where
you would like to USE the desired construct, as you did
for the function-wrapping-function case, we could help...
Alex
More information about the Python-list
mailing list