Dangerous behavior of list(generator)

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sun Dec 13 22:29:38 EST 2009


On 02:50 am, lie.1296 at gmail.com wrote:
>On 12/14/2009 9:45 AM, exarkun at twistedmatrix.com wrote:
>>On 08:18 pm, steve at remove-this-cybersource.com.au wrote:
>>>On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote:
>>>>>StopIteration is intended to be used only within the .__next__
>>>>>method of
>>>>>iterators. The devs know that other 'off-label' use results in the
>>>>>inconsistency you noted, but their and my view is 'don't do that'.
>>>>
>>>>Which is unfortunate, because it's not that hard to get 
>>>>StopIteration
>>>>without explicitly raising it yourself and this behavior makes it
>>>>difficult to debug such situations.
>>>
>>>I can't think of any way to get StopIteration without explicitly 
>>>raising
>>>it yourself. It's not like built-ins or common data structures 
>>>routinely
>>>raise StopIteration. I don't think I've *ever* seen a StopIteration 
>>>that
>>>I didn't raise myself.
>>
>>Call next on an iterator. For example: iter(()).next()
>
>.next() is not meant to be called directly

Doesn't matter.  Sometimes it makes sense to call it directly.  And I 
was just giving an example of a way to get StopIteration raised without 
doing it yourself - which is what Steve said he couldn't think of.
>>
>>I'm surprised to hear you say that the magical faerie land behavior
>>isn't desirable either, though. I'd love a tool that did what I 
>>wanted,
>>not what I asked. The only serious argument against this, I think, is
>>that it is beyond our current ability to create (and so anyone 
>>claiming
>>to be able to do it is probably mistaken).
>
>In your world, this is what happens:
> >>> list = [a, b, c]
> >>> # print list
> >>> print list
>["a", "b", "c"]
> >>> # make a copy of list
> >>> alist = list(llst) # oops a mistype
> >>> alist = alist - "]" + ", "d"]"
> >>> print alist
>["a", "b", "c", "d"]
> >>> alist[:6] + "i", + alist[6:]
> >>> print alist
>["a", "i", "b", "c", "d"]
> >>> print alist
> >>> # hearing the sound of my deskjet printer...
> >>> C:\fikle.text.write(alist)
> >>> print open("C:\file.txt").read()
><h1>a</h1>
><ul>
><li>i</li>
><li>b</li>
><li>c d</li>
> >>> # great, exactly what I needed

I don't understand the point of this code listing, sorry.  I suspect you 
didn't completely understand the magical faerie land I was describing - 
where all your programs would work, no matter what mistakes you made 
while writing them.

Jean-Paul



More information about the Python-list mailing list