[Zope-PTK] Hooks

Fabio Forno sciasbat@inorbit.com
Mon, 21 Aug 2000 18:16:21 +0200


"Dan L. Pierson" wrote:
> 
> Shane Hathaway writes:
>  > Fabio Forno wrote:
>  > >
>  > > Perhaps it's a crazy idea, but what about a fully configurable hook map,
>  > > so that we allow the users to add the hook they want?
>  >
>  > An interesting idea.  The one concern I have is that users really won't
>  > care about writing hooks for most things.  For any sufficiently sizable
>  > change, users will want to write subclasses, not hook implementations.
>  > If you can develop an argument against that, I see no reason why we
>  > shouldn't write a generalized "hookable tool generator" that does all
>  > the work for us.
> 
> Seems like you're starting to reinvent a Lisp advice system.  This is
> an interface for wrapping a function or method in a new function such
> that all calls will automagically go through the wrapper.
> The docs for a simple version that's part of GNU Emacs are at the end
> of this message.  A Python interface might look like:
> 
> def advise(func, context, where, body, doc = None):
>     """ Wrap function 'func' so that 'body' is executed in the
> relationship to func specified by 'where'.  'context' is the class or
> module that func is part of (i.e. context.__dict__ will be modified to
> accomplish this wrapping).  'where' can be one of: ADVISE_BEFORE,
> ADVISE_AFTER, ADVISE_AROUND.  The advised function will be available
> as 'self.__advised__' and the next advice wrapper to be called will be
> available as 'self.__advise_next__' (if there is no inner advice
> wrapper, self.__advised__ and self.__advise_next__ will be the same).
> 'body' is a string that will be used to construct the real definition
> of func.  'doc' is an optional doc string for func. """
> 
>     # Implementation left as an exercise for the reader :-)
> 
> I think that the main pain in implementing this is likely to be that
> body has to be a string because there's nothing like Lisp macros in
> Python.  On the other hand, this shouldn't be too hard with triple
> quoted strings.
> 

I think this can be done avoiding to pass the body as a string, but
manipulating the class dictionary inserting a call_hook function
provided by a class implementing the hookability. The call_hook function
should go in the dictionary at the place of the hooked fuction; this one
is moved in a second dictionary looked up by call_hook, which is invoked
at it place and can call the hook before and after the function.

ByE,
FF