ValueError vs IndexError, unpacking arguments with string.split

Morten W. Petersen morphex at gmail.com
Fri Nov 30 11:57:04 EST 2018


On Fri, Nov 30, 2018 at 4:25 PM Dan Sommers <
2QdxY4RzWzUUiLuE at potatochowder.com> wrote:

> On 11/30/18 7:35 AM, Morten W. Petersen wrote:
>
> > ... but isn't it logical that the
> > string is parsed and split, and then later the unpacking operation fails
> > with an IndexError?
>
> With slightly simpler code and the full text of the exception,
> the details becomes more apparent:
>
>  >>> x, y = [4]
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> ValueError: not enough values to unpack (expected 2, got 1)
>
> Python validates that the right hand side contains exactly the
> right number of elements before beginning to unpack, presumably
> to ensure a successful operation before failing part way through.
>
> Effectively, Python is saying that you can't unpack a one-element
> array into two pieces *before* it gets to the indexing logic.
>


Hm.  Well I like the simplicity and abstraction of Python, it makes it
a very productive language.

And since iterable object can be used, I guess it makes sense to
raise a ValueError.

And trying

>>> a,b,c = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
>>>

raises a TypeError, and this is all in-hand with the Python docs.

But since you mention it, why is it necessary to ensure a successful
operation?

Is it so that when

a,b,c = [1,2]

fails, none of the variables a,b,c have been assigned to, and because of
that, one avoids "rolling back" any assignment that would have been
done without checking the right-hand argument first ?

Regards,

Morten

-- 
Videos at https://www.youtube.com/user/TheBlogologue
Twittering at http://twitter.com/blogologue
Blogging at http://blogologue.com
Playing music at https://soundcloud.com/morten-w-petersen
Also playing music and podcasting here:
http://www.mixcloud.com/morten-w-petersen/
On Google+ here https://plus.google.com/107781930037068750156
On Instagram at https://instagram.com/morphexx/



More information about the Python-list mailing list