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

Reply via email to