Speed up properties?!

Dr. Peer Griebel griebel at konzept-is.de
Fri May 14 04:30:15 EDT 2004


Andrew Bennetts wrote:

> On Fri, May 14, 2004 at 07:48:29AM +0200, Dr. Peer Griebel wrote:
> 
>>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)
> 
> 
> This doesn't really do what you want: properties (and descriptors in
> general) only work their magic when they are attributes of classes, not
> instances.

Oh yes you are right. I didn't look at x to discover that it is a 
property object.

> I think a simpler approach in your __init__ would do what you want:
> 
>     def __init__(self):
>         if __debug__:
>             self.x = 5   # ordinary attribute
>         else:
>             self._x = 5  # use properties

But this means I have to replace _all_ occurences of _x by x (or vice 
versa).  This has to be performed in all methods of C and all other 
methods using C!
What I am looking for is a mechanism to create an alias x for _x so that 
in non __debug__ mode I can access _x by using x. (In debug mode the 
property creates this alias by using the setter and getter method.)

> The rest looked fine to me.
> 
> -Andrew.

Thank you,
   Peer






More information about the Python-list mailing list