Skip to content

Instantly share code, notes, and snippets.

@amirouche
Created August 2, 2018 09:37
Show Gist options
  • Save amirouche/502d30f31cf499c0c899b3000da246fd to your computer and use it in GitHub Desktop.
Save amirouche/502d30f31cf499c0c899b3000da246fd to your computer and use it in GitHub Desktop.
amirouche@neitram:~/tmp$ cat debugproperty.py
from traceback import print_stack
from weakref import WeakKeyDictionary
class DebugProperty:
def __init__(self, name):
self.name = name
self.data = WeakKeyDictionary()
def __get__(self, instance, owner):
print('Property {} of {} accessed at:'.format(self.name, instance))
print_stack()
return self.data[instance]
def __set__(self, instance, value):
print('Property {} of {} changed to {} at:'.format(self.name, value, instance))
print_stack()
self.data[instance] = value
class VeryComplicatedClass:
_very_important_value = DebugProperty('_very_important_value')
def __init__(self, value):
self._very_important_value = value
def test_traceback(my_object):
my_object._very_important_value = 42
return my_object._very_important_value
my_object = VeryComplicatedClass(101)
out = test_traceback(my_object)
assert out == 42
amirouche@neitram:~/tmp$ python3 debugproperty.py
Property _very_important_value of 101 changed to <__main__.VeryComplicatedClass object at 0x7fbab0fd4128> at:
File "debugproperty.py", line 35, in <module>
my_object = VeryComplicatedClass(101)
File "debugproperty.py", line 27, in __init__
self._very_important_value = value
File "debugproperty.py", line 18, in __set__
print_stack()
Property _very_important_value of 42 changed to <__main__.VeryComplicatedClass object at 0x7fbab0fd4128> at:
File "debugproperty.py", line 38, in <module>
out = test_traceback(my_object)
File "debugproperty.py", line 31, in test_traceback
my_object._very_important_value = 42
File "debugproperty.py", line 18, in __set__
print_stack()
Property _very_important_value of <__main__.VeryComplicatedClass object at 0x7fbab0fd4128> accessed at:
File "debugproperty.py", line 38, in <module>
out = test_traceback(my_object)
File "debugproperty.py", line 32, in test_traceback
return my_object._very_important_value
File "debugproperty.py", line 13, in __get__
print_stack()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment