[Python-ideas] Boundaries for unpacking

Michel Desmoulin desmoulinmichel at gmail.com
Thu Apr 7 14:24:23 EDT 2016



Le 07/04/2016 20:15, Michael Selik a écrit :
> 
>> 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?

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 at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
> 


More information about the Python-ideas mailing list