function local namespace question

Dave Angel davea at
Thu Jul 9 08:44:18 EDT 2009

Paul LaFollette wrote:
> Kind people,
> Using Python 3.1 under FreeBSD and WinXP.
> I've been tearing my hair out trying to solve this myself, but I need
> to ask for help.   I want (for obscure reasons) to be able to log
> transactions in the namespace(s) of a script.  Specifically I would
> like to log creation of identifiers, changes in the binding of
> identifiers ("assignment") and lookups.  This turns out to be pretty
> easy in the global and local namespaces... I simply subclass dict,
> override the appropriate operations to include the logging operations
> I want, and then exec the code using my dictionaries as the global and
> local namespaces.  All  of this  works just dandy until I try to
> extend it to functions.
> I cannot figure out any way to get a hook into the local namespace of
> a user defined function.  I have tried making a wrapper class that
> grabs the function call and then uses exec to invoke
> myfunction.__code__ with my own dictionaries.  This runs the (no
> argument) function properly (losing the return value, but I can deal
> with that) but never accesses the local logging dictionary that I
> specify in the exec() call. Perhaps the local namespace of a function
> is not a dict at all?
> Anyway, is there any way (however clumsy) to do what I want to do?
> Thank you for your help.
> Paul
> ---------------------------
> Paul LaFollette
> CIS Department
> Temple University
> paul.lafollette(at)
Is there a way?  Undoubtedly.

The simplest way that occurs to me is to have a pre-pass that rewrites 
the .pyc files, adding instrumentation to the byte-code.  You could also 
recompile the Python interpreter, with some extra hooks in it.  That 
could get tricky, as you don't want to instrument the code that's doing 
the tracking.  Fnally, you could hook into the byte-code loader, doing 
the changes at that time.

As always, if the code is for commercial use, beware of infringing on 
patents.  I have a few in the 3rd area (though the ownership is with 
other companies;  I was just the inventor.)


More information about the Python-list mailing list