[PATCH] A compromise on case - another suggestion

Andrew Dalke dalke at acm.org
Sun May 28 00:38:51 EDT 2000


Peter Schneider-Kamp wrote:
>Andrew Dalke wrote:
>>
>> The IndexError check is also used to signify the end of the list, as in:
>
>Is that really so? From a quick look at the relevant sources I saw
>at least some places where IndexError is checked. So you may be right.
>
>But does it have to be like that? Can't we use the length of the list
>to check?


You can check by implementing your own list-like object:

class List:
  def __getitem__(self, i):
    if i == 5:
      raise IndexError, i
    return i
  def __len__(self):
    return 2

>>> for x in List():
...  print x
...
0
1
2
3
4
>>>

I believe Python 1.4 was the switch from using __len__ to using an
IndexError.  The problem with __len__ comes when implementing
list-like interfaces to objects which don't know their length, like
a forward iterator.  One example is the FileInput class in the standard
library module 'fileinput'.


>> BTW, the failure goes from O(1) to O(N) because it has to check
>> every available value.  I don't know internals well enough to know
>> if getattr() is also affected by the patch - it shouldn't be.  That
>> would leave an O(1) test available.
>
>I don't understand this part. I would think printing the range
>is O(1).


Sorry, my fault for the confusion.  That comment was meant to refer
to the NameError exception patch of Nick's.  I just assumed you would
read my mind :)

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list