Assigning generator expressions to ctype arrays

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Oct 28 03:21:47 EDT 2011


On Thu, 27 Oct 2011 17:09:34 -0700, Patrick Maupin wrote:

> On Oct 27, 5:31 pm, Steven D'Aprano <steve
> +comp.lang.pyt... at pearwood.info> wrote:
>> From the outside, you can't tell how big a generator expression is. It
>> has no length:
> 
> I understand that.
> 
>> Since the array object has no way of telling whether the generator will
>> have the correct size, it refuses to guess.
> 
> It doesn't have to guess.  It can assume that I, the programmer, know
> what the heck I am doing, and then validate that assumption -- trust,
> but verify.  It merely needs to fill the slice and then ask for one more
> and check that StopIteration is raised.

Simple, easy, and wrong.

It needs to fill in the slice, check that the slice has exactly the right 
number of elements (it may have fewer), and then check that the iterator 
is now empty.

If the slice has too few elements, you've just blown away the entire 
iterator for no good reason.

If the slice is the right length, but the iterator doesn't next raise 
StopIteration, you've just thrown away one perfectly good value. Hope it 
wasn't something important.


>> I would argue that it should raise a TypeError with a less misleading
>> error message, rather than a ValueError, so "bug".
> 
> And I would argue that it should simply work, unless someone can present
> a more compelling reason why not.

I think that "the iterator protocol as it exists doesn't allow it to work 
the way you want" is a pretty compelling reason.


>> The simple solution is to use a list comp instead of a generator
>> expression.
> 
> I know how to work around the issue.  I'm not sure I should have to. It
> violates the principle of least surprise for the ctypes array to not be
> able to interoperate with the iterator protocol in this fashion.

Perhaps you're too easily surprised by the wrong things.


-- 
Steven



More information about the Python-list mailing list