[Python-Dev] itertools addition: getitem()
Kevin Jacobs <jacobs@bioinformed.com>
bioinformed at gmail.com
Sun Jul 8 17:49:59 CEST 2007
On 7/8/07, Guido van Rossum <guido at python.org> wrote:
>
> Ahem. I hope you have a better use case for getitem() than that
> (regardless of the default issue). I find it clearer to write that as
>
> try:
> compid = root[ns.company_id].next()
> except StopIteration:
> compid = None
> else:
> compid = int(compid)
>
> While this is more lines, it doesn't require one to know about
> getitem() on an iterator. This is the same reason why setdefault() was
> a mistake -- it's too obscure to invent a compact spelling for it
> since the compact spelling has to be learned or looked up.
>
Apropos of this discussion, I've occasionally wanted a faster version of the
following:
_nothing=object()
def nth_next(seq,n,default=_nothing):
'''
Return the n'th next element for seq, if it exists.
If default is specified, it is return when the sequence is too short.
Otherwise StopIteration is raised.
'''
try:
for i in xrange(n-1):
seq.next()
return seq.next()
except StopIteration:
if default is _nothing:
raise
return default
The nice thing about this function is that it solves several problems in
one: extraction of the n'th next element, testing for a minimum sequence
length given a sentinel value, and just skipping n elements. It also leaves
the sequence in a useful and predictable state, which is not true of the
Python-version getitem code. While cute, I can't say if it is worthy of
being an itertool function.
Also vaguely apropos:
def ilen(seq):
'Return the length of the hopefully finite sequence'
n = 0
for x in seq:
n += 1
return n
Why? Because I find myself implementing it in virtually every project.
Maybe I'm just an outlier, but many algorithms I implement need to consume
iterators (for side-effects, obviously) and it is sometimes nice to know
exactly how many elements were consumed.
~Kevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/python-dev/attachments/20070708/af8ba064/attachment.htm
More information about the Python-Dev
mailing list