Peek at variables without adding a ton of logging or debugging code.
Decorate a function with @watch and every time a watched local variable is rebound, your handlers are
called. Requires Python 3.12+ (uses sys.monitoring).
import logging
from endoscope import watch, raise_if, log_change
logging.basicConfig(level=logging.DEBUG)
@watch("total", on_change=[log_change, raise_if(lambda c: c.new < 0, "total went negative")])
def process(costs):
total = 0
for cost in costs:
total += cost
return total@watch: watch all locals, log changes withlog_change.@watch("a", "b", on_change=handler_or_list): watch selected locals. Unknown names raiseValueError.unwatch(func)— stop watching.
A handler is any callable handler(change: Change) -> None, defined anywhere. Handlers are called in order and
return values are ignored. Anything a handler raises propagates out of the watched function at the offending line.
Change fields:
| field | meaning |
|---|---|
var |
variable name |
old |
previous value, or UNBOUND on first assignment |
new |
new value, or UNBOUND after del |
lineno |
line whose execution caused the rebind |
filename |
source file of the watched function |
func |
qualified name of the watched function |
frame_id |
identifies the invocation (recursion, threads, generators) |
Built-in helpers:
log_change: logs at DEBUG on theendoscopelogger.raise_if(predicate, message=None, exc=AssertionError): builds a handler that raises whenpredicate(change)is true (see below).
raise_if does not check anything when it is called. It returns a handler that you pass to on_change.
That handler then runs on every rebind:
- It calls
predicate(change)with theChangedescribed above. - If the result is falsy, nothing happens and execution continues.
- If the result is truthy, it raises
exc(defaultAssertionError) from inside the watched function, formatted as"<message>: <func> line <lineno>: <var> = <new> (was <old>)".messagedefaults to"raise_if condition met".
In other words, it's an assert that runs automatically after every rebind, except that the condition describes the forbidden case.
@watch("balance", on_change=raise_if(lambda c: c.new < 0, "balance went negative"))
def withdraw(balance, amount):
balance = balance - amount
return balance
withdraw(100, 130)
# AssertionError: balance went negative: withdraw line 3: balance = -30 (was 100)Because the predicate gets the whole Change, it can check more than the new value:
raise_if(lambda c: c.old is not UNBOUND and c.new < c.old) # transition: must never decrease
raise_if(lambda c: c.var == "total" and c.new < 0) # only constrain one of several watched variables
raise_if(lambda c: c.old is not UNBOUND, exc=ValueError) # must never be reassigned after its first valueThings to know:
- The predicate runs for every watched variable in that
@watch. If you watch several, usec.varto choose which one it applies to. - On a first assignment,
c.oldisUNBOUND. Afterdel,c.newisUNBOUND. ComparingUNBOUNDwith<raisesTypeError, which propagates instead ofexc. Guard withc.old is not UNBOUND and ...when needed. - It raises explicitly instead of using an
assertstatement, so it still runs underpython -O. UseENDOSCOPE_DISABLEDto turn it off. raise_ifis only a convenience. Any handler that raises does the same job.
- Only rebinding is detected: the name now refers to a different object (
is not). In-place mutation (items.append(x)) is not reported, and neither isx = x, orx += 0on a cached small int. This is for performance reasons (it would requiredeepcopy, which can be very expensive). - Changes are detected between lines, so several rebinds on one line (
x = 1; x = 2, orfor i in range(3): x = i) are reported as a single change from the value before the line to the value after it. - Function arguments are initial values; only later rebinds of them are reported.
- Only the decorated function's own frame is watched; functions it calls (and nested
defs) are untraced. You canwatchthose if you want. - Closure variables rebound via
nonlocalfrom an inner function are seen by the outer frame. - Watched functions called from inside a handler do not report their changes (so a watcher doesn't trigger itself).
- Endoscope claims a free
sys.monitoringtool ID (neverDEBUGGER_ID), so pdb/debuggers keep working.
Set ENDOSCOPE_DISABLED=1 (or true/yes/on). It is checked when the decorator is applied (import time):
@watch then returns the original function untouched.
poetry install
poetry run pytest tests/