[Tutor] function signatures for callbacks
dyoo at hkn.eecs.berkeley.edu
Tue Mar 21 22:27:35 CET 2006
> I have a piece of code that wants a callback from a client:
> The code looks like this right now:
> class pawprints:
> def __init__(self, callback_fun = None)
> at the client calling site I have something like this:
> def printme(modulename, codename, lineno, line):
> paws = pawprints(callback_fun = printme)
> My questions:
> 1) Is this the correct way to do this (the code does seem to work OK).
Yes, the passing of printme to the pawprints() looks fine.
> 2) If so, then is there a way to specify the function signature at
> callback site rather than the client site?
By "function signature", do you mean being able to properly check for
weird inputs and outputs? If so, then a qualified Yes. One possible idea
is to use a concept called "contracts":
The problem of providing good error messages for code that uses
"higher-order function" callbacks is more difficult. I'm starting to
learn about how this problem is handled by the Scheme community, and they
do attack this problem head on:
So this problem is known. I have not yet read through the PyProtocols
and perhaps this handles callbacks in a clean way too, but on a quick
glance, I don't see this yet. (That means I have to read more carefully!
*grin*) So it's possible that the research being done in this area has
yet to be fully absorbed into the APIs of more mainstream languages like
> It seems backwards to me because because if I get the function
> definition wrong in the client site then I get a traceback to the
> callback site - which is meant to be an opaque library that the client
> should not have to know about.
Yes, what you're asking makes sense: we want to "blame" the right party,
and if it's the callback provider that messed up, we should only attribute
them. (The same kind of problem happens in Tkinter, where bugs in
callbacks end up exposing Tkinter internals.)
Unfortunately, the stack traceback shows the entire stack trace at the
point where bad things happen, so it does a little more than assign proper
blame. The stack traceback is an imperfect mechanism for figuring out
what went wrong. I don't know yet what the right solution is.
Best of wishes!
More information about the Tutor