Can using * to discard excess returns in a parallel assignment be compatible in Python 2.x?

Python 3.x allows you to reset excess revenue for concurrent assignments using *

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

But 2.x is not:

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

Is there any future import that might make this statement compatible with Python 2.x?

+4
source share
3 answers

AFAIK this function is not available in Python 2, if you really need something like this - just write a 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 the expected behavior

+3
source

No, there is no equivalent support for unpacking Python 2.

In some cases, you can use slicing to approximate code for cross-compatibility:

first, second, rest = val[0], val[1], val[2:]
+3

. , Python 2.7 __future__, .

(Note that the module __future__is not actually involved in the magic of future operations. This is mainly for documentation purposes and to avoid confusing tools that expect all imports to match the real module.)

+3
source

Source: https://habr.com/ru/post/1674505/


All Articles