[Python-ideas] Boundaries for unpacking
Michael Selik
mike at selik.org
Thu Apr 7 14:15:26 EDT 2016
> On Apr 7, 2016, at 6:44 PM, Todd <toddrjen at gmail.com> wrote:
>
> On Thu, Apr 7, 2016 at 1:03 PM, Michel Desmoulin <desmoulinmichel at gmail.com> wrote:
> Python is a lot about iteration, and I often have to get values from an
> iterable. For this, unpacking is fantastic:
>
> a, b, c = iterable
>
> One that problem arises is that you don't know when iterable will
> contain 3 items.
>
> In that case, this beautiful code becomes:
>
> iterator = iter(iterable)
> a = next(iterator, "default value")
> b = next(iterator, "default value")
> c = next(iterator, "default value")
I actually don't think that's so ugly. Looks fairly clear to me. What about these alternatives?
>>> from itertools import repeat, islice, chain
>>> it = range(2)
>>> a, b, c = islice(chain(it, repeat('default')), 3)
>>> a, b, c
(0, 1, 'default')
If you want to stick with builtins:
>>> it = iter(range(2))
>>> a, b, c = [next(it, 'default') for i in range(3)]
>>> a, b, c
(0, 1, 'default')
If your utterable is sliceable and sizeable:
>>> it = list(range(2))
>>> a, b, c = it[:3] + ['default'] * (3 - len(it))
>>> a, b, c
(0, 1, 'default')
Perhaps add a recipe to itertools, or change the "take" recipe?
def unpack(n, iterable, default=None):
"Slice the first n items of the iterable, padding with a default"
padding = repeat(default)
return islice(chain(iterable, padding), n))
More information about the Python-ideas
mailing list