black magic question

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

black magic question

Mark C. Brighton
Hello,

I have a problem that probably has a simple answer, but it's been vexing me.  

I'm looking for a way to log an object's method calls and their results. Right now each method has a section of boiler-plate code that logs the method name, arguments, and results.  It's cluttered and hard to maintain.  It seems like a prime place to use a metaclass or decorator.  The Python Cookbook (great book btw) has a recipe for this in section 20.6 (and using metaclasses in 20.7).  I've tried it, and it works, except....  the object "looses" the method's argument information.  For most objects, this isn't a problem, but we use this object interactively from the interpreter.  If I were to make the tool tips unhelpful, I would immediately get complaints from my coworkers; and to be honest, I wouldn't like it either.  

So is there a way to use decorators (or the like) to add functionality around a class without obscuring its signature?  

thanks in advance,

Mark Brighton

_______________________________________________
Baypiggies mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/baypiggies
Reply | Threaded
Open this post in threaded view
|

Re: black magic question

Alex Martelli
On 12/5/05, Mark C. Brighton <[hidden email]> wrote:
> Hello,
>
> I have a problem that probably has a simple answer, but it's been vexing me.
>
> I'm looking for a way to log an object's method calls and their results. Right now each method has a section of boiler-plate code that logs the method name, arguments, and results.  It's cluttered and hard to maintain.  It seems like a prime place to use a metaclass or decorator.  The Python Cookbook (great book btw) has a recipe for this in section 20.6 (and using metaclasses in 20.7).  I've tried it, and it works, except....  the object "looses" the method's argument information.  For most objects, this isn't a problem, but we use this object interactively from the interpreter.  If I were to make the tool tips unhelpful, I would immediately get complaints from my coworkers; and to be honest, I wouldn't like it either.
>
> So is there a way to use decorators (or the like) to add functionality around a class without obscuring its signature?

Yes, it's a lot of painstakign detailed work but it's feasible.  Use
module inspect to find out everything about the function you're
decorating, and build a new function object "on the fly" (perhaps
easiest, by building up the sourcecode for it as a string and then
using the built-in compile function to turn that into bytecode) to
mimic those aspects you want to preserve, such as the exact signature
(argument names).


Alex
_______________________________________________
Baypiggies mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/baypiggies