Speed up properties?!
david mugnai
guardian at supereva.it
Fri May 14 06:50:01 EDT 2004
Dr. Peer Griebel wrote:
> 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:
What do you think about this:
import types
class Meta1(type):
def __new__(mcl,classname,bases,classdict):
if not __debug__:
return type.__new__(mcl,classname,bases,classdict)
GetterName="_%s__get_" % classname
SetterName="_%s__set_" % classname
Properties={}
for x in classdict:
if isinstance(classdict[x],types.FunctionType):
if x.startswith(GetterName):
name=x[len(GetterName):]
Properties[name]=property(classdict[x],
classdict[SetterName+name])
classdict.update(Properties)
return type.__new__(mcl,classname,bases,classdict)
class A(object):
__metaclass__=Meta1
def __init__(self):
self.x=5
def __get_x(self):
return self._x
def __set_x(self,value):
if value>5:
raise ValueError,value
self._x=value
S=A()
print S.x
S.x=12
print S.x
---------------------------
HTH
dvd
--
Being married to a programmer is like having a cat. You talk to it but
you're never really sure if it hears you, much less comprehends what you say
More information about the Python-list
mailing list