The goal is to create a mock class which behaves like a db resultset.
So for example, if a database query returns, using a dict expression, {'ab':100, 'cd':200}, then I would to see
>>> dummy.ab
100
So, at the beginning I thought I maybe able to do it this way
ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
def __init__(self, ks, vs):
for i, k in enumerate(ks):
self[k] = vs[i]
setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))
def fn_readonly(self, v)
raise "It is ready only"
if __name__ == "__main__":
c = C(ks, vs)
print c.ab
but "c.ab" returns a property object instead.
Replace the setattr line with
k = property(lambda x: vs[i])
It is of no use at all.
So what is the right way to create an instance property in runtime?
P.S. I am aware of an alternative here