modifying def behaviour

Terry Reedy tjreedy at udel.edu
Wed Aug 6 20:12:26 EDT 2003


"Craig Zoretich" <czoretich at octigabay.com> wrote in message
news:e7d0b08f.0308061508.5b5228c7 at posting.google.com...
> Is it possible to change how the "def" builtin command works?

Sure, if you are willing to change the interpreter.  But no, there is
not an exposed 'metafunction' facility analogous to metaclasses.

> Specifically I want  to modify def to write to a log file when a
> function executes (for instance the name of the function, when it
was
> executed - that sort of thing).  I want to avoid having to put some
> code in each and every function I write to do this logging for me.

However, the def code has nothing to do with what happens when a
function is called.  All it could do is what you don't want (put code
in eash function).  So you would need to hook into the function call
mechanism.  To do this in Python (rather than in C and recompile the
interpreter) wrap the functions you want logged as instances of a
logger class.  Others have previously posted examples like this:

class logger:
    def  __init__(self, func):
         self.func = func
    def __call__(self, *args):
        print "Called: %s with args %s" % (self.func.func_name, args)
        return self.func(*args)

def myfunc(a): return a

myfunc = logger(myfunc)

>>> myfunc(3)
Called: myfunc with args (3,)
3

Terry J. Reedy






More information about the Python-list mailing list