Skip to content

Instantly share code, notes, and snippets.

@lelandbatey
Created February 5, 2020 18:59
Show Gist options
  • Save lelandbatey/07c7252f2fda846ef7634782a758558a to your computer and use it in GitHub Desktop.
Save lelandbatey/07c7252f2fda846ef7634782a758558a to your computer and use it in GitHub Desktop.
Python class for tracking access to members of collections. Great for legacy code were we wonder "what's being accessed in this big dict and where is it being accessed?"
from __future__ import print_function
import inspect
import six
def fmt_stack(frames):
s = ""
for f in frames[::-1]:
s += "{}:{}: {}\n".format(f[1], f[2], '\\n'.join([x.replace('\n', '') for x in f[4]]))
return s
def print_access(item, context):
s = '.'.join([str(x) for x in context])
s = '{} = {}'.format(s, str(item))
print('\n', s, '\n', fmt_stack(inspect.stack()[2:]), '\n\n\n')
return s
class CollectionAccessTracker(object):
def __init__(self, item, context=None):
self.item = item
self.context = context if context else list()
def __getattribute__(self, name):
ctx = object.__getattribute__(self, 'context') + [name]
val = object.__getattribute__(self, 'item').__getattribute__(name)
if isinstance(val, six.string_types) or isinstance(val, (int, float, long, complex)) or isinstance(val, bool):
print_access(val, ctx)
return val
return CollectionAccessTracker(val, ctx)
def __getitem__(self, name):
ctx = object.__getattribute__(self, 'context') + [name]
val = object.__getattribute__(self, 'item')[name]
if isinstance(val, six.string_types) or isinstance(val, (int, float, long, complex)) or isinstance(val, bool):
print_access(val, ctx)
return val
return CollectionAccessTracker(val, ctx)
def __contains__(self, name):
return name in object.__getattribute__(self, 'item')
def __str__(self):
return str(object.__getattribute__(self, 'item'))
@property
def __class__(self):
cls = object.__getattribute__(self, 'item').__class__
print('\n\n', cls, '\n')
return cls
def __repr__(self):
return str(self.__class__) + repr(object.__getattribute__(self, 'item'))
def toJSON(self):
return self.item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment