Speed up properties?!

Dr. Peer Griebel griebel at konzept-is.de
Fri May 14 01:48:29 EDT 2004


Hi,

I have a class with some properties.  I would like to verify that only
valid values are assigned to the properties using assert.  Therefore I
code setters and getters and use property() to convert these to have a
real property.

Since the verification is only performed in __debug__ runs the
property() is quite a lot of overhead.  I tried to circumvent it.  This
is my result so far:


class C(object):
     def __init__(self):
         self._x = 5
         if not __debug__:
             self.x = property(self._x, self._x)

     def getX(self):
         return self._x

     def setX(self, v):
         assert 0 <= v <= 5
         self._x = v

     if __debug__:
         x = property(getX, setX)

o = C()
def test():
     o.x

if __name__=='__main__':
     from timeit import Timer
     t = Timer("test()", "from __main__ import test")
     print t.timeit()



As you can see, in non __debug__ runs the accesses of the x property do
not result in calls to getX or setX.  There I can get a speedup of 2! 
But to be honest: I don't like this aproach. So is there some better, 
cleaner way?

Peer







More information about the Python-list mailing list