[Tutor] Data persistence problem

Alan Gauld alan.gauld at btinternet.com
Sat Jun 22 09:44:22 CEST 2013


On 22/06/13 03:26, Jim Mooney wrote:

>> if isinstance(dict(),typein):
>>     try: newdict = dict(zip(dl[::2],dl[1::2]))
>>     except TypeError:
>>      raise ValueError("input lists must be an even length")
>
> Not sure why TypeError and ValueError is used.

I used them because that's what I got in my testing of dict
on Python 2.7. The zip() may actually obviate the need since
it stops zipping when it runs out of matches.

And the reason I changed from your Exception type is that using the base 
Exception is nearly always wrong. It means that you then have
to catch the top level Exception which will include every possible
error that could occur. So if somebody hits Ctl-C for instance 
(KeyboardInterrupt) you will still be telling them to pass even
length input. So it's better to either use a standard exception
type or invent a new one. In this case TypeError was what it was 
throwing and ValueError seemed to me to describe an invalid
length list...

> StopIteration

This is usually used to force a stop of a loop - usually because
you've ran out of data. Since I wasn't using an explicit loop it
didn't seem appropriate but I could see how you might consider
it an option. Certainly better than Exception..


> iterables in the zip, but it looks like dict knows tostop

No, it's zip() that knows when to stop.

In 2.7 I get:

 >>> dict([1,2],[1,2,3])
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: dict expected at most 1 arguments, got 2
 >>> zip([1,2],[1,2,3])
[(1, 1), (2, 2)]
 >>>

The behaviour may have changed in 3.3...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list