Skip to content

Instantly share code, notes, and snippets.

@christabor
Created June 6, 2017 21:58
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 christabor/d38bbca466d6bfc4ba903c9839a1955f to your computer and use it in GitHub Desktop.
Save christabor/d38bbca466d6bfc4ba903c9839a1955f to your computer and use it in GitHub Desktop.
Instrumentation through descriptors
from pprint import pprint as ppr
from collections import defaultdict
from datetime import datetime as dt
class Db(object):
def default_obj(self):
return dict(
last_modified=None,
current=None,
values=[],
accessed=0,
)
def __init__(self, url):
self.host = url
self.db = defaultdict(self.default_obj)
def read(self, k):
self.db[k]['accessed'] += 1
def write(self, k, v):
self.db[k]['values'].append(v)
self.db[k]['current'] = v
self.db[k]['last_modified'] = dt.now()
@property
def data(self):
return self.db
def configure(db):
"""Configure the instrumented descriptor with some values."""
class Instrumented(object):
def __init__(self, name, val):
self.name = name
self.val = val
self.db = db
def __get__(self, obj, objtype):
self.db.read(self.name)
return self.val
def __set__(self, obj, val):
self.db.write(self.name, self.val)
self.val = val
return Instrumented
mydb = Db('https://MY.SWEET.DATASTORE.com:8091')
InstrumentedField = configure(mydb)
class MyClass(object):
field1 = InstrumentedField('field-1', 1)
field2 = InstrumentedField('field-2', 'radSauce')
cls1 = MyClass()
# Demonstrating accessing the var writes to a "db"
map(lambda x: cls1.field1, range(10))
cls1.field1 = 'Boom'
cls1.field2
ppr(mydb.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment