[Python-ideas] Possible PEP 380 tweak

Ron Adam rrr at ronadam.com
Sun Oct 31 08:26:11 CET 2010



On 10/30/2010 07:35 PM, Nick Coghlan wrote:
> On Sun, Oct 31, 2010 at 2:54 AM, Ron Adam<rrr at ronadam.com>  wrote:
>>> However, I think sentinel values are likely a better way to handle
>>> this in a pure PEP 380 context.
>>
>> Sentinel values aren't always better because they require a extra comparison
>> on each item.
>
> Yep, Guido's example made me realise I was wrong on that front.

BTW: A sentinal could still work, and the 'except <exception>' could be 
optional.

The finish function isn't needed in this one.


def gtally(end_tally):
   # Tallies numbers until sentinel is passed in
   count = tally = 0
   while 1:
     value = yield
     if value is end_tally:
       break
     count += 1
     tally += value
   yield count, tally

def gaverage(end_avg):
   yield from gtally(end_avg)
   yield tally / count

def main():
   g = gaverage(None)
   next(g)
   for x in range(100):
     g.send(x)
   return g.send(None)


Using sentinels not always wrong either. The data may have natural sentinel 
values in it.  In those cases, value testing is what you want.

I would like to be able to do it both ways myself. :-)

Cheers,
    Ron







More information about the Python-ideas mailing list