[Python-Dev] Replacing __slots__ with addmembers()
Michael McLay
mclay@erols.com
Sun, 11 Nov 2001 05:24:51 -0500
I just submitted a patch that replaces the __slots__ notation with a new
syntax that is more like the property descriptor. The old syntax looked as
follows:
>>> class B(object):
"""class B's docstring
"""
__slots__ = ['a','b','c','d']
The following example will create the eequivalent of this __slots__ example.
>>> class B(object):
"""class B's docstring
"""
a = addmember()
b = addmember()
c = addmember()
d = addmember()
The next example show the use of the three parameters for addmember.
The doc parameter becomes the docstring for the attribute. The types
parameter can be a single type or a tuple. If it is present the
member_set and member_get functions will call PyObject_IsInstance to
verify the member is of the defined types. The default parameter must
be of one of the defined types. If the member is not populated prior
to accessing the member the default value will be returned as the
value of the member.
>>> class B(object):
"""class B's docstring
"""
a = addmember(types=int, default=56, doc="a docstring")
b = addmember(types=int, doc="b's docstring")
c = addmember(types=(int,float), default=5.0, doc="c docstring")
d = addmember(types=(str,float), default="ham", doc="d docstring")
>>> b = B()
>>> b.a
56
>>> B.a.__doc__
'a docstring'
>>> b.d
'ham'
>>> b.b
Traceback (most recent call last):
File "<pyshell#8>", line 1, in ?
b.b
TypeError: The value of B.b is of type 'type'. This is not one of the defined
types
>>> b.d = 23.3
>>> b.d = (34,)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in ?
b.d = (34,)
TypeError: The type 'tuple' is not one of the declared types for B.d
The zip file submitted with the patch includes a more detailed description of
the patch. I hope the feature freeze won't rule out the patch for 2.2. The
whole patch, including all of the test cases is less than 500 lines. My
concern is that if __slots__ isn't fixed prior to releasing 2.2 we'll be
stuck with the rather limited and ugly syntax Guido cooked up to test the
capabilities of member descriptors. The patch also takes steps to isolate
the member descriptor code from type_new. The type checking code is brain
dead simple and only required about 20 lines of code. It is fully contained
in the new member descriptor that was added. The cost to test if a type
check is required is a single C compare.
I'll be at an out of town meeting until next Saturday and I'm not sure if
I'll have Internet access.