Skip to content

Instantly share code, notes, and snippets.

@unkn-one
Last active August 29, 2015 14:20
Show Gist options
  • Save unkn-one/9636798599b03986462a to your computer and use it in GitHub Desktop.
Save unkn-one/9636798599b03986462a to your computer and use it in GitHub Desktop.
Function for augmenting object to print stack trace whenever watched attributes are accessed, changed or removed.
def patch(obj, attrs):
import traceback
class o(object): pass
class Spy(o):
def __getattribute__(self, a):
if a in attrs:
traceback.print_stack()
return object.__getattribute__(obj, a)
def __setattr__(self, a, value):
if a in attrs:
traceback.print_stack()
object.__setattr__(obj, a, value)
def __delattr__(self, a):
if a in attrs:
traceback.print_stack()
object.__delattr__(obj, a)
Spy.__name__ = obj.__class__.__name__
cls = obj.__class__
obj.__class__ = Spy
obj.__class__.__bases__ = (cls, )
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment