PEP 276 (was Re: Status of PEP's?)
Carel Fellinger
cfelling at iae.nl
Sat Mar 2 13:05:25 EST 2002
Emile van Sebille <emile at fenx.com> wrote:
> "Carel Fellinger"
>> You specify that the
>> integer to iterate over should be possitive, why not allow for
>> negative values and do the sensible thing, like:
>>
>> >>> [i for i in -3]
>> [-1, -2, -3]
> If you change the sensible thing to mean:
> [-3, -2, -1]
> I'd like it better. ;-)
I noted the smiley, but just in case someone might think you have a
point: what would be the benefit of that? It just let you loop over a
sequence in the standard order, but now with negative indici. And the
range call to get this isn't that hard either: range(-3,0).
My proposal makes iterating in *reverse* order simple.
The tutorial could introduce it like:
In python integers are objects too. And objects know how to do
things, e.g. integer objects know how to add and just recently
they learned how to count. Positive integers count from zero
upto but not including the number itself, whereas negative
integers count from -1 downto and including the number itself.
A common place where this feature of integers is used is in for
loops and list comprehension. e.g.
>>> s = "silly walk".split()
>>> print " ".join([s[i] for i in len(s)])
silly walk
>>> print " ".join([s[i] for i in -len(s)])
walk silly
Although the first print statement is generally written as:
>>> print " ".join([x for x in s])
The implementation is dead simple, to play around with it in 2.2:
class Int(int):
def __neg__(self):
return Int(int(self).__neg__())
def __iter__(self):
i = 0
if self >= 0:
while i < self:
yield i
i += 1
else:
while i > self:
i -= 1
yield i
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.
--
groetjes, carel
More information about the Python-list
mailing list