Function wrapper in Python

Alex Martelli aleaxit at yahoo.com
Wed Oct 25 12:09:04 EDT 2000


<olavb at my-deja.com> wrote in message news:8t6sar$cf7$1 at nnrp1.deja.com...
> In article <8runes02q1 at news2.newsguy.com>,
>   "Alex Martelli" <aleaxit at yahoo.com> wrote:
> > <Olav.Benum at bigfoot.com> wrote in message
> > 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...
> >
>
> In C++/Python/Delphi inspired pseudo-code
>
> class Wrapper:
>     abstract wrapped_function()
>     call_func(*positional, **keyword):
>         try:
>             apply( wrapped_function, positional. keyword)
>         except OSError, error:
>             log_exception( "Fatal general exception", error )
>             if error:
>                 print str(error)
>                 print "General exceptiom, see logs"
>     Wrapper((*positional, **keyword):#constructor
>             #construct object
>             call_func( positional, keyword )
>
> class Wrapp_set_opt( Wrapper):
>     wrapped_function( dir, level ):
>         set_opt( dir, level )
>
> Wrapp_set_opt( dir, level)

The presence of 'self' should not be too big a change
to this scheme.  The derived class would take a form
such as:

class Wrapped_set_opt(Wrapper):
    def wrapped_function(self, dir, level):
        set_opt(dir, level)

To enable this, the baseclass Wrapper just needs a
few changes from your scheme...:

class Wrapper:
    def __init__(self, *positional, **keyword):
        try:
            self.wrapped_function(*positional, **keyword)
        except OSError, error:
            log_exception("Fatal general exception", error)
            if error:
                print error
                print "General exception, see logs"

This is working Python 2.0 code (putting the definition
of the base class before that of the deriving one, and
defining the set_opt and log_exception functions to
appropriate dummies).

The only big problem I see with this approach is that
it will not work if the wrapped function (in case it
does not raise the trapped error) returns a useful
result -- not transparently, that is (you _could_
set the function's return to, say, self.value, and
invoke with "Wrapped_set_opt(foo,bar).value" -- or
other several possible approaches), because the call
to a class always returns an instance of that class,
not the other-whatever-kind-of-object that the wrapped
function might be returning.  If you can leave with
that, good.  Else, the client code needs to call, not
the derived wrapper-class directly, but rather a
function that will call it and return the .value
of the instance (or whatever).


Alex






More information about the Python-list mailing list