Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the use of * to dump excess return in parallel assignment be made compatible in Python 2.x?

Python 3.x allows dumping excess return in a parallel assignment with *

>>> a, b, *args = range(4)
>>> a
0
>>> b
1
>>> args
[2, 3]

But 2.x doesn't:

>>> a, b, *args = range(4)
  File "<stdin>", line 1
    a,b,*args = range(4)
        ^
SyntaxError: invalid syntax

Is there some future import that can make this statement compatible with Python 2.x?

like image 554
jmborr Avatar asked Jan 05 '23 05:01

jmborr


1 Answers

AFAIK this feature is not available in Python 2, if you really need something like this – just write utility function

def unpack(iterable, elements_count):
    iterator = iter(iterable)
    for _ in range(elements_count):
        yield next(iterator)
    # maybe use `list` or leave `iterator`-object
    yield tuple(iterator)

Then

a, b, args = unpack(range(4), 2)

will give an expected behaviour

like image 61
Azat Ibrakov Avatar answered Jan 13 '23 10:01

Azat Ibrakov