[Tutor] casting string to integer in a list of lists

Marc Tompkins marc.tompkins at gmail.com
Fri Jan 9 00:11:13 CET 2009


On Thu, Jan 8, 2009 at 2:21 PM, wesley chun <wescpy at gmail.com> wrote:

> except:
>    pass
>
> try not to code these 2 lines in anything that you do because it will
> come back to haunt you when something is not working right but you
> can't find any errors. that's because this code masks and throws away
> everything!!
>
> if you are guaranteed that the strings all contain valid integers,
> then you don't have to worry about problems calling int().
>

OP said we couldn't be sure that all rows would have the same number of
elements; I'm afraid I extrapolated that we also might not be sure they were
all integers (or, I should say, strings representing integers...), so there
are two potential error types: IndexError and ValueError.  I assumed that if
either one occurred, we would want to leave that particular list member (if
it exists) as-is (hence the pass).

I see three ways around this:
- test each list for length, and each member for integer-ness, before
casting anything;
- catch the exception, test to see whether it's an IndexError or a
ValueError, and if not then do something;
- print/log every exception.

The first one violates "It's better to ask forgiveness than to ask
permission" (and it's slow), the second one's a pain in the butt; the third
one gets slow if LoL is large and has many non-standard members.  Is there a
fourth way?

Actually, I'm asking because I've run into similar situations and been
dissatisfied with my own solution.  Generally, if there are two or more
"acceptable" errors that you can foresee, but you still want to catch any
others, what's an elegant, readable,  and computationally-cheap way to do
it?  Maybe a dictionary of exceptions...?

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090108/cf1611ce/attachment.htm>


More information about the Tutor mailing list