If I had to make a syntax suggestion, I think it would be

    a, b, c = iterable or defaults

although making or both pseudo None-coalescing and pseudo error-coalescing might be a bit too much sugar. However I think it clearly expresses the idea.

That said, I have to ask what the usecase is for dealing with fixed length unpacking where you might not have the fixed length of items. That feels smelly to me. Why are you trying to name values from a variable length list?

-Josh

On Thu, Apr 7, 2016 at 2:24 PM Michel Desmoulin <desmoulinmichel@gmail.com> wrote:


Le 07/04/2016 20:15, Michael Selik a écrit :
>
>> On Apr 7, 2016, at 6:44 PM, Todd <toddrjen@gmail.com> wrote:
>>
>> On Thu, Apr 7, 2016 at 1:03 PM, Michel Desmoulin <desmoulinmichel@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?

Well, there is nothing wrong with:

a = mylist[0]

b = mylist[1]

c = mylist[2]

But we still prefer unpacking. And this is way more verbose.



>
>>>> 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')

They all work, but they are impossible to remember, plus you will need a
comment everytime you use them outside of the shell.

>
>
> 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')

Same problem, and as you said, you can forget about generators.

>
>
>
> 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))

Not a bad idea. Built in would be better, but I can live with itertools.
I import it so often I'm wondering if itertools shouldn't be in
__builtins__ :)

> _______________________________________________
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/