How to inspect a variable (sys.modules) for changes in the execution of a program?

Chris Rebert clp2 at
Wed Feb 16 00:54:47 CET 2011

On Tue, Feb 15, 2011 at 1:29 PM, Emile van Sebille <emile at> wrote:
> On 2/15/2011 10:19 AM Chris Rebert said...
>> On Tue, Feb 15, 2011 at 7:17 AM, Jorge Vargas<jorge.vargas at>
>>  wrote: <snip>
>>> I have the following situation. In a big project that involves many
>>> dependencies (and sadly some sys.module hacks) we have a bug, and it
>>> will really help if i could monitor all changes made to that variable.
>>> Is there a way to trace those changes ?
>> Is the variable's value of a mutable or immutable type? What is the
>> variable's scope (e.g. module-level global, or object attribute)? Is
>> the variable subject to getting rebound to an entirely new
>> value/object?
>> The answers to these questions will determine how much work will be
>> required to trace "changes" to the variable. I know of no built-in way
>> to directly do such a thing, but the underlying functionality
>> necessary to implement such a feature (e.g. sys.settrace,
>> __getattribute__, __setattr__) does exist.
> Out of curiosity, if it's immutable, what approach might you try to
> capture/trace reassignment?  I've got a toy tracer that breaks with simple
> assignment:
>>>> A=tracer(3)
>>>> A
> 3
>>>> A+=3
> value changed by 3 by add

I was thinking of a trace (as in sys.settrace()) function that'd grab
the value (or possibly object ID) of the variable every time it was
called (possibly excluding certain event types) and see whether it
changed vs. the value the variable had the last time it was called.
This would obviously be rather inefficient.


More information about the Python-list mailing list