Idiom for default values when unpacking a tuple

Carlos Ribeiro carribeiro at gmail.com
Thu Nov 18 12:49:27 CET 2004


On Thu, 18 Nov 2004 03:34:42 GMT, Steven Bethard
<steven.bethard at gmail.com> wrote:
> Well, it doesn't quite exist in itertools, but it's there with just a
> simple composition:
> 
>  >>> def iterfixed(seq, times, defaultitem=None):
> ...     return it.islice(it.chain(iter(seq), it.repeat(defaultitem)), times)
> ...

After I posted the previous recipe I polished it up a little bit more
and renamed it as "iunpack". It now returns the remaining part of the
tuple as the last item. As it is, it's a good candidate for itertools
-- it's way more convenient than the composition option, and judging
by how many times the issue was brought up here, it's a relatively
common problem.
 
>  >>> tuple(iterfixed((1,2,3,4), 3))
> (1, 2, 3)
>  >>> tuple(iterfixed((1,2,3,4), 6))
> (1, 2, 3, 4, None, None)
>  >>> a,b,c = iterfixed((1,2,3,4), 3)
>  >>> a,b,c
> (1, 2, 3)
>  >>> a,b,c,d,e,f = iterfixed((1,2,3,4), 6)
>  >>> a,b,c,d,e,f
> (1, 2, 3, 4, None, None)
> 
> > The only catch is that, if you have only one parameter, then all you
> > will get is the generator itself. But that's a corner case, and not
> > the intended use anyway.
> 
> Not exactly sure what you mean here.  If you only have one item in your
> unpack tuple, I believe things still work, e.g.:
> 
>  >>> a, = iterfixed((1,2,3,4), 1)
>  >>> a
> 1
> 
> But I'm probably just misunderstanding your statement...

No -- it's that you remembered to include the comma. My example was to
assign it it one item only, which really isn't tuple unpacking; but
this is a easy mistake to do in this case. Anyway, it should work as
intended.

BTW, I never saw it mentioned before that iterators can be used at the
right side of an assignment with the tuple meaning. Nice side effect,
I think.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list