[Python-ideas] Default values in multi-target assignment

Guido van Rossum guido at python.org
Thu Apr 12 11:12:32 EDT 2018


I hear where you're coming from but I really don't think we should do this.
If you don't have the right expectation already it's hard to guess what it
means. I would much rather spend effort on a proper matching statement.

On Thu, Apr 12, 2018 at 2:54 AM, Serhiy Storchaka <storchaka at gmail.com>
wrote:

> Yet one crazy idea. What if allow default values for targets in
> multi-target assignment?
>
>     >>> (a, b=0) = (1, 2)
>     >>> a, b
>     (1, 2)
>     >>> (a, b=0) = (1,)
>     >>> a, b
>     (1, 0)
>     >>> (a, b=0) = ()
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     ValueError: not enough values to unpack (expected at least 1, got 0)
>     >>> (a, b=0) = (1, 2, 3)
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in <module>
>     ValueError: too many values to unpack (expected at most 2)
>
> Currently you need either explicitly check the length of the right-hand
> part (if it is a sequence and not an arbitrary iterator),
>
>     if len(c) == 1:
>         a, = c
>         b = 0
>     elif len(c) == 2:
>         a, b = c
>     else:
>         raise TypeError
>
> or use an intermediate function:
>
>     def f(a, b=0):
>         return a, b
>     a, b = f(*c)
>
> The latter can be written as an ugly one-liner:
>
>     a, b = (lambda a, b=0: (a, b))(*c)
>
> _______________________________________________
> 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/
>



-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180412/081c0979/attachment.html>


More information about the Python-ideas mailing list