PEP 276 (was Re: Status of PEP's?)
James_Althoff at i2.com
James_Althoff at i2.com
Mon Mar 4 16:10:55 EST 2002
[Carel Fellinger]
> and define your classes to let __len__ return an Int object.
>
> class List(list):
> def __len__(self):
> return Int(len(list(self)))
>
> trying it out, yack it doesn't work, len forces it into an int again:(
>
> >>> spam = List("spam")
> >>> type(spam.__len__())
> <class '__main__.Int'>
> >>> type(len(spam))
> <type 'int'>
>
> I think this qualifies as a bug.
Here's a similar way to try out PEP 276.
Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> from __future__ import generators
>>>
>>> class iint(int):
... def __iter__(self):
... i = 0
... while i < self:
... yield i
... i += 1
... raise StopIteration
...
>>> __len = len
>>>
>>> def len(seq):
... return iint(__len(seq))
...
>>> l = ['a','b','c','d','e','f','g','h']
>>>
>>> for i in len(l):
... if i % 2 == 0:
... print l[i]
...
a
c
e
g
>>> # PEP 276 in action <wink>
...
>>>
BTW, if anyone knows how to add a method to class int (without resorting to
the C code), let me know. I can't seem to get around int.__dict__ being a
dict-proxy that can't be subclassed, modified, etc. Probably by design
<0.1 wink>.
Jim
More information about the Python-list
mailing list