Thoughts on PEP284
Sean Ross
sross at connectmail.carleton.ca
Tue Sep 23 10:40:30 EDT 2003
Here's a quick hack of an int class that supports iteration using the slice
notation, plus simple iteration on the class itself (for i in int: ...).
This can certainly be improved, and other issues need to be addressed, but I
just wanted to see what Stephen's idea would look like in practice. (Not
bad. Actually, pretty good.)
# using python 2.2.2
from __future__ import generators
class xint(int):
class __metaclass__(type):
def __iter__(cls):
return cls.__getitem__()
def __getitem__(cls, index=None):
if hasattr(index, "start"):
for i in range(index.start, index.stop, index.step):
yield i
elif isinstance(index, int):
yield index
elif index is None:
i = 0
while True:
yield i
i += 1
else:
raise Exception
__getitem__ = classmethod(__getitem__)
print "iteration on int"
for i in xint:
if i >= 10:
break
print i
print "\niteration on int slice"
for i in xint[0:22:2]:
print i
#
# OUTPUT
#
iteration on int
0
1
2
3
4
5
6
7
8
9
iteration on int slice
0
2
4
6
8
10
12
14
16
18
20
More information about the Python-list
mailing list