modifying def behaviour

Craig Zoretich czoretich at
Fri Aug 8 01:38:51 CEST 2003

"Terry Reedy" <tjreedy at> wrote in message news:<UXGdnRupYrf2BKyiU-KYvg at>...
> "Craig Zoretich" <czoretich at> wrote in message
> news:e7d0b08f.0308061508.5b5228c7 at
> > 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

Thanks, this was great stuff.

Another question somewhat (maybe) related.   Are there going to be any
performance issues related to doing this, speed and memory wise?  I am
assuming this will double the amount of objects that will be created
(another object for each function), but being new to python, I don't
know if functions take up a lot of memory or not, and whether I'll
notice the memory difference.


More information about the Python-list mailing list