[Python-ideas] Default return values to int and float

Chris Rebert pyideas at rebertia.com
Mon Oct 3 11:57:03 CEST 2011


On Mon, Oct 3, 2011 at 12:52 AM, David Townshend <aquavitae69 at gmail.com> wrote:
> My idea is fairly simple: add a "default" argument to int and float,
> allowing a return value if the conversion fails.  E.g:
>
>>>> float('cannot convert this', default=0.0)
> 0.0
>
> I think there are many use cases for this, every time float() or int()
> are called with data that cannot be guaranteed to be numeric, it has
> to be checked and some sort of default behaviour applied.  The above
> example is just much cleaner than:
>
> try:
>    return float(s)
> except ValueError:
>    return 0.0

Important consideration: Would the default value be typechecked or
not? (i.e. Does something like `float(s, {})` raise TypeError?)
It's not uncommon to use None as the result value when the input is
invalid, but not typechecking would then leave the door open to
strangeness like my example.
Or would None just be inelegantly special-cased, or...?

This could be one of those instances where Python is better off
leaving people to write their own short one-off functions to get the
/exact/ behavior desired in their individual circumstances.

Cheers,
Chris



More information about the Python-ideas mailing list