ValueError vs IndexError, unpacking arguments with string.split

Peter Otten __peter__ at web.de
Fri Nov 30 09:59:46 EST 2018


Morten W. Petersen wrote:

> Hi there.
> 
> I was adding a port specification feature to my surveil project as shown
> here:
> 
> 
https://github.com/morphex/surveil/commit/703318f87c4c450a37944b565a10718ef27b57b4
> 
> A bit later I was surprised when the script raised an exception, and that
> I had to catch a ValueError instead of an IndexError:
> 
> 
https://github.com/morphex/surveil/commit/d5c49c54d4037557aaca1f78178b76441853c7af
> 
> I've been reading up on a bit of C++, Assembler etc. lately, so maybe my
> mind expected an IndexError because of that, but isn't it logical that the
> string is parsed and split, and then later the unpacking operation fails
> with an IndexError?

You might think that

a, b = c

is equivalent to

a = c[0]
b = c[1]

but the c above can be an arbitrary iterable:

>>> a, b = iter("ab")
>>> a, b
('a', 'b')
>>> a, b = iter("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

So there is not necessarily a lookup by index.




More information about the Python-list mailing list