Skip to content

Instantly share code, notes, and snippets.

@dnozay
Created January 4, 2021 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnozay/d0dc461583caa723d014f71e654a6e0f to your computer and use it in GitHub Desktop.
Save dnozay/d0dc461583caa723d014f71e654a6e0f to your computer and use it in GitHub Desktop.
spy on variable in python
# https://stackoverflow.com/a/34620310/1733117
import sys
import dis
import random
watchme = 123
def foo():
global watchme
watchme = 122
def wait_for_changes():
curr_val = watchme
def tracefn(frame, event, arg):
global watchme
global changed_frame
if event == 'call':
frame.f_trace_opcodes = True
if watchme != curr_val:
changed_frame = frame
if event == 'opcode':
opcode = frame.f_code.co_code[frame.f_lasti]
opname = dis.opname[opcode]
print(f"XXX value changed to {watchme} in frame {frame} by opcode {opname}")
watchme = curr_val
return tracefn
sys.settrace(tracefn)
for i in range(100):
exec(f"""
def foo_{i}():
global watchme
watchme = {i}
""")
wait_for_changes()
def random_call():
n = random.randint(0, 99)
exec(f"foo_{n}()")
random_call()
random_call()
random_call()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment