[Python-checkins] CVS: python/dist/src/Lib/test test_descr.py,1.1.2.24,1.1.2.25

Guido van Rossum gvanrossum@users.sourceforge.net
Tue, 03 Jul 2001 02:24:59 -0700


Update of /cvsroot/python/python/dist/src/Lib/test
In directory usw-pr-cvs1:/tmp/cvs-serv12232

Modified Files:
      Tag: descr-branch
	test_descr.py 
Log Message:
PyDescr_IsData(): change in specification.  If the argument is not a
PyDescrObject, this returns true if the argument's type supports the
tp_descr_set slot.  This allows us to created computed attributes from
a pair of get/set functions (see test_descr.py example).

This almost works for classic classes too: there, it can be used for
read-only computed attributes, but it can't be used to trap setattr
unless we change instance setattr to look in the class dict first.
Since that's expensive (a chain of dict lookups) we don't do this.

Why is it not expensive for new-style classes?  Because the class
lookup is faster: compare _PyType_Lookup() to class_lookup().


Index: test_descr.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/Attic/test_descr.py,v
retrieving revision 1.1.2.24
retrieving revision 1.1.2.25
diff -C2 -r1.1.2.24 -r1.1.2.25
*** test_descr.py	2001/07/03 01:19:20	1.1.2.24
--- test_descr.py	2001/07/03 09:24:56	1.1.2.25
***************
*** 650,653 ****
--- 650,680 ----
      verify(D.foo(d, 1) == (d, 1))
  
+ def compattr():
+     if verbose: print "Testing computed attributes..."
+     class C(object):
+         class computed_attribute(object):
+             def __init__(self, get, set=None):
+                 self.__get = get
+                 self.__set = set
+             def __get__(self, obj, type=None):
+                 return self.__get(obj)
+             def __set__(self, obj, value):
+                 return self.__set(obj, value)
+         def __init__(self):
+             self.__x = 0
+         def __get_x(self):
+             x = self.__x
+             self.__x = x+1
+             return x
+         def __set_x(self, x):
+             self.__x = x
+         x = computed_attribute(__get_x, __set_x)
+     a = C()
+     verify(a.x == 0)
+     verify(a.x == 1)
+     a.x = 10
+     verify(a.x == 10)
+     verify(a.x == 11)
+ 
  def all():
      lists()
***************
*** 671,674 ****
--- 698,702 ----
      classmethods()
      classic()
+     compattr()
  
  all()