On Sun, Mar 1, 2020 at 11:35 PM Alex Hall <alex.moj...@gmail.com> wrote:
>
> Currently this code:
>
> d = {"key": "value"}
> for key, value in d:
>     pass
>
> produces this error:
>
> ValueError: too many values to unpack (expected 2)
>
> I suggest that the error message should also have:
>
> 1. The name of the type of the unpacked value
> 2. The length of the unpacked value, if it exists and (to not execute 
> arbitrary __len__ implementations) if the type belongs to a safe subset, e.g. 
> only builtin types.
>
> Then the error message could be:
>
> ValueError: too many values to unpack (expected 2, found 3) from object of 
> type str
>

Adding the type name would be pretty safe to do. Adding the length,
though, is a bit harder. Consider:

>>> def gen():
...     for n in range(50):
...             print("Yielding", n)
...             yield n
...
>>> a, b = gen()
Yielding 0
Yielding 1
Yielding 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

So the only way would be to call len(), and if it fails, fall back on
the "expected 2" form. And I'm not sure if that would be worthwhile,
given that it's going to have to run arbitrary code just for the sake
of the error message.

+0.5 for showing the type name, -0.5 for trying to show the length.

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/J7S35JHCXJVN5PDBIL4GPW2TITHXMR7Y/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to