How Best to Coerce Python Objects to Integers?

Chris Angelico rosuav at
Tue Jan 3 17:59:18 EST 2017

On Wed, Jan 4, 2017 at 10:39 AM, Steve D'Aprano
<steve+python at> wrote:
> 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.

Agreed. There are certainly times when you want to say "coerce any
*string* to an int", and there are times when you want to say "coerce
any string to int or None" (maybe you want to take the average of a whole lot 
of values, ignoring the ones that say "N/A"), but I don't know of any time I 
want to say "coerce any programming error to int or None", unless you count the 
exit code of a process.

I used the word "improved" rather loosely.


More information about the Python-list mailing list