Add a default option to int() to use if conversion fails

Mark Bell suggested:

x = int(user_input, default=0)

We might agree that converting the empty string to some default value is
(sometimes) a reasonable thing to do, but the empty string is not the
only input that raises a ValueError. Silencing arbitrary ValueErrors by
replacement with a default value is surely going to lead to “Garbage In,
Garbage Out” data processing.

I cannot imagine a scenario where I, as the user, would consider it
acceptable to use 0 because I entered “635.1” when an int was expected,
or because I typoed “97w5” when I meant 9735.

But what you do in your code is up to you. I’m not suggesting
that you shouldn’t be permitted to do whatever error handling you
prefer, including not handling it at all but merely replacing it with
some arbitrary default you plucked from thin air. Go for it, it’s your
code, I’m not judging.

But I would not want this raised up to an official supported and
recommended design, baked into the int and other builtins. That makes
it too much of an “attractive nuisance”, something that encourages
people to handle errors without thought, when they really do need to
think about it.

The other builtin functions that offer defaults tend to have these two
things in common:

  • the error condition they support is only missing data, not malformed
    data;

  • and it is hard, or inefficient, to “Look Before You Leap” and check
    for the error condition ahead of time.

For example, getattr(obj, name, default), dict.get(key, default),
next(iterator, default), unicodedata.name(char, default).

They aren’t intended to suppress arbitrary errors. (Historically, we’ve
had lots of problems with getattr, for example, suppressing errors
that it shouldn’t have.)

Neither of those conditions is true for your suggestion. Catching any
ValueError and replacing it with a default is too greedy to build it
into the function. And LBYL on the empty string is trivially easy, not
hard or inefficient.

2 Likes