Skip to content

Instantly share code, notes, and snippets.

@ByK95
Last active June 1, 2021 08:15
Show Gist options
  • Save ByK95/b58228b3791e297678dcaf06f1db6628 to your computer and use it in GitHub Desktop.
Save ByK95/b58228b3791e297678dcaf06f1db6628 to your computer and use it in GitHub Desktop.
ipdb custom functionality wrapper
import sys
import types
import ipdb
"""
Functionality that monkey patches ipdb.set_trace method and allows
adding custom functions and etc for better debugging
usage:
define function and append to globals dictionary like
dictionary key should be unique
global_ref['pretty_json'] = pretty_json
warning: asigning key with builtin module or function names can overwrite them.
from dev_tools import ipdb;ipdb.set_trace()
example:
pretty_json function will be available while debugging with ipdb as
global function
"""
def copy_func(f, name=None):
return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
f.func_defaults, f.func_closure)
func_ref = copy_func(ipdb.set_trace)
def pretty_json(data, file='dump'):
import json
f = open(file + '.json', 'w')
f.write(json.dumps(data, indent=1))
f.close()
def measure_exec_time(callable_):
def inner(*args, **kwargs):
import time
start_time = time.time()
ipdb.set_trace()
result = callable_(*args, **kwargs)
print("--- %s seconds ---" % (time.time() - start_time))
return result
return inner
def set_trace_wrapper(*args, **kwargs):
frame = kwargs.get('frame')
if frame is None:
kwargs['frame'] = sys._getframe().f_back
global_ref = kwargs['frame'].f_globals
global_ref['pretty_json'] = pretty_json
global_ref['measure_exec_time'] = measure_exec_time
return func_ref(*args, **kwargs)
ipdb.set_trace = set_trace_wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment