How Best to Coerce Python Objects to Integers?

Steve D'Aprano steve+python at pearwood.info
Tue Jan 3 17:39:20 EST 2017


On Wed, 4 Jan 2017 09:47 am, 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 why? That makes no sense. If his intention is to return None on failure, no 
matter what happens, then he *should* catch SystemExit. Otherwise:

class Unint:
    def __int__(self):
        raise SystemExit

int_or_else(Unint)


will exit instead of returning None. Surely that's not what he wants, given 
that he wants to cover up other programming errors like NameError and 
TypeError?

The problem here is not so much the use of try...except but the *intention* 
that "Anything whatsoever should be coerced to int". If you have something 
like:

left_margin = int_or_else(ftp_server)

that's surely a programming error that needs fixing, rather than something that 
should just return a default value.



--
Steve
â £Cheer up,â Ø they said, â £things could be worse.â Ø So I cheered up, and
sure
enough, things got worse.



More information about the Python-list mailing list