[Python-Dev] decorators: If you go for it, go all the way!!! :)
alex_nanou at cs.msu.su
alex_nanou at cs.msu.su
Thu Aug 26 12:58:30 CEST 2004
the inability to decorate anything but a function, is quite a limitation,
though I must agree that decorating classes is not such a common task, but
using the syntax to *decorate* attributes would indeed prove useful (in
both the readability department and the uniformity of code)..
here is an example we use quite often:
---cut---
import time
import sys
def intonly(obj=0, doc=None):
'''
intonly(int) -> descriptor
the resulting descriptor will prevent both the deletion of the
attribute and assignments of any value other than ints.
'''
if type(obj) is not int:
raise TypeError, 'value must be int (got: %s)' % obj
f_locals = sys._getframe(1).f_locals
# name the attr (I know this is ugly ^_^ )
while True:
name = '_priv_' + str(int(time.time()*10**8))
if name not in f_locals:
f_locals[name] = obj
break
# the descriptor reader function...
def read(self):
return getattr(self, name)
# the descriptor writer...
def write(self, val):
if type(val) is not int:
raise TypeError, 'value must be int (got: %s)' % val
setattr(self, name, val)
# now create the descriptor and return it...
return property(read, write, doc=doc)
--uncut--
and here are a couple of usage examples:
the desired decorator syntax:
---cut---
class A(object):
@intonly
i = 123
--uncut--
the current usage syntax:
---cut---
class A(object):
i = intonly(123)
--uncut--
// sorry if I bring this up agen! :)
thanks!
---
Best Regards...
Alex.
More information about the Python-Dev
mailing list