How Best to Coerce Python Objects to Integers?

Erik python at lucidity.plus.com
Tue Jan 3 19:22:17 EST 2017


On 03/01/17 22:47, Chris Angelico wrote:
> On Wed, Jan 4, 2017 at 9:42 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> Aside from calling "except Exception" a "naked except"
>
> If you read the comments, you'll see that he originally had an actual
> bare except clause, but then improved the code somewhat in response to
> a recommendation that SystemExit etc not be caught.

But, as stated at the top of the article, his brief was: "The strings 
come from a file that a human has typed in, so even though most of the 
values are good, a few will have errors ('25C') that int() will reject.".

What he *should* have done is just validated his input strings before 
presenting the string to int() - i.e., process the input with knowledge 
that is specific to the problem domain before calling the 
general-purpose function.

He mentions temperature sensors, so perhaps stripping a trailing 'c' or 
'C' is a reasonable thing to do (or even, if there's a trailing 'f' or 
'F', performing a numerical conversion after the value is known).

Instead, he tried to patch around int() rejecting the strings. And then 
decided that he'd patch around int() rejecting things that weren't even 
strings even though that's not what the function has (apparently) been 
specified to receive.

The "bulletproof" result will convert "25C" to None even though 25 is 
probably a reasonable result for that string in his domain problem domain.

E.





More information about the Python-list mailing list