Function wrapper in Python

Steve Holden sholden at holdenweb.com
Mon Oct 9 13:34:22 EDT 2000


Olav.Benum at bigfoot.com wrote:
> 
> 
>  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.

You appear to be searching for the "apply" built-in function.

>						  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')
> 

Well, a simplistic implementation would be as follows:

>>> def wrapfunc(f, *positional, **keyword):
	try:
		apply(f, positional, keyword)
	except OSError, error:
		print "General exception"
		if error:
			print str(error)

>>> def test_func( *anon, **named):
	print "Anonymous positionals:"
	for a in anon:
		print a
	print "Keyword arguments:"
	for k, v in named.items():
		print k, ":", v

>>> wrapfunc(test_func, "hello world", "goodbye world", a=1, b=2, c=3)
Anonymous positionals:
hello world
goodbye world
Keyword arguments:
b : 2
c : 3
a : 1

It traps OSError correctly:

>>> wrapfunc(os.fstat, 123)
General exception
[Errno 9] Bad file descriptor
 
And it doesn't trap other errors:

>>> wrapfunc(open, "No such file")
Traceback (innermost last):
  File "<pyshell#19>", line 1, in ?
    wrapfunc(open, "No such file")
  File "<pyshell#9>", line 3, in wrapfunc
    apply(f, positional, keyword)
IOError: [Errno 2] No such file or directory: 'No such file'

> 
>  (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)
> 
>  Thanks!
>   Olav
> 
Does this give you enough to go on?

regards
 Steve

-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/



More information about the Python-list mailing list