Created
June 6, 2017 21:58
-
-
Save christabor/d38bbca466d6bfc4ba903c9839a1955f to your computer and use it in GitHub Desktop.
Instrumentation through descriptors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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