Why is
>>> a, *b = ''
not possible, when
>>> a, *b = ' '
>>> a, b
(' ', []) # b == empty list here anyway.
and
>>> type('')
<class 'str'>
I mean, why isn't it
>>> a, *b = ''
>>> a, b # a could == ''
('', [])
Why is
>>> a, *b = ''
not possible, when
>>> a, *b = ' '
>>> a, b
(' ', []) # b == empty list here anyway.
and
>>> type('')
<class 'str'>
I mean, why isn't it
>>> a, *b = ''
>>> a, b # a could == ''
('', [])
Based on PEP 3132 :
The function
unpack_iterable()
inceval.c
is changed to handle the extended unpacking, via an argcntafter parameter. In the UNPACK_EX case, the function will do the following:
So it will failed in first step because there is no mandatory targets in your string.
For more info you can check unpack_iterable
in caval.c
:
unpack_iterable(PyObject *v, int argcnt, int argcntafter, PyObject **sp)
{
int i = 0, j = 0;
Py_ssize_t ll = 0;
PyObject *it; /* iter(v) */
PyObject *w;
PyObject *l = NULL; /* variable list */
assert(v != NULL);
it = PyObject_GetIter(v);
if (it == NULL)
goto Error;
for (; i < argcnt; i++) {
w = PyIter_Next(it);
if (w == NULL) {
/* Iterator done, via error or exhaustion. */
if (!PyErr_Occurred()) {
if (argcntafter == -1) {
PyErr_Format(PyExc_ValueError,
"not enough values to unpack (expected %d, got %d)",
argcnt, i);
}
else {
PyErr_Format(PyExc_ValueError,
"not enough values to unpack "
"(expected at least %d, got %d)",
argcnt + argcntafter, i);
}
}
goto Error;
}
*--sp = w;
}
if (argcntafter == -1) {
/* We better have exhausted the iterator now. */
w = PyIter_Next(it);
if (w == NULL) {
if (PyErr_Occurred())
goto Error;
Py_DECREF(it);
return 1;
}
Py_DECREF(w);
PyErr_Format(PyExc_ValueError,
"too many values to unpack (expected %d)",
argcnt);
goto Error;
}
l = PySequence_List(it);
if (l == NULL)
goto Error;
*--sp = l;
i++;
ll = PyList_GET_SIZE(l);
if (ll < argcntafter) {
PyErr_Format(PyExc_ValueError,
"not enough values to unpack (expected at least %d, got %zd)",
argcnt + argcntafter, argcnt + ll);
goto Error;
}
/* Pop the "after-variable" args off the list. */
for (j = argcntafter; j > 0; j--, i++) {
*--sp = PyList_GET_ITEM(l, ll - j);
}
/* Resize the list. */
Py_SIZE(l) = ll - argcntafter;
Py_DECREF(it);
return 1;
Error:
for (; i > 0; i--, sp++)
Py_DECREF(*sp);
Py_XDECREF(it);
return 0;
}
Because there is one mandatory variable specified.
The right side should have at least one item (one character for string).
According to PEP-3131: