How to add property to a class dynamically?

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 like to see:

>>> dummy.ab
100

At first I thought maybe I could 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.

Replacing the setattr line with k = property(lambda x: vs[i]) is of no use at all.

So what is the right way to create an instance property at runtime?

P.S. I am aware of an alternative presented in How is the __getattribute__ method used?

25 Answers
25

Leave a Comment