Speed up properties?!
Andrew Bennetts
andrew-pythonlist at puzzling.org
Fri May 14 01:54:28 EDT 2004
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.
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
The rest looked fine to me.
-Andrew.
More information about the Python-list
mailing list