[C++-sig] vector_indexing_suite too defensive ...
Mike Thompson
mike.thompson at day8.com.au
Sun Sep 28 14:12:44 CEST 2003
I've found a small difference between the behaviour of python lists and
vector's wrapped by using the talented vector_indexing_suite.
Let's say I write a python function which forces a list to be a particular size
by padding it (if below the required size), or chopping it down (if above the
required size):
>>> def padOrChop(lst, size, padValue=0):
... diff = size- len(lst)
... lst[size:] = [padValue] * diff
...
This function work nicely with normal python lists ....
>>>
>>> L = [2, 3, 4, 5]
>>> padOrChop(L, 10)
>>> L
[2, 3, 4, 5, 0, 0, 0, 0, 0, 0]
>>> padOrChop(L, 2)
>>> L
[2, 3]
>>>
but it will fail with an object created through vector_indexing_suite whenever
it has to pad:
>>> L = IntVec() # really a vector<int>
>>> L[:] = [2, 3, 4, 5]
>>> padOrChop(L, 10)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in padOrChop
IndexError: Index out of range
>>> padOrChop(L, 2)
>>> [i for i in L]
[2, 3]
>>>
The IndexError arises because vector_indexing_suite defends against an slice
index being too big, rather than the python list approach which regards a slice
index > len(L) as equal to len(L). So, the line of padOrChop() which says:
lst[size:] = [padValue] * diff
causes an exception when size > len(lst).
Should vector_indexing_suite be altered to give behaviour more like that of
lists in this regard?
--
Mike
More information about the Cplusplus-sig
mailing list