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

Nick Coghlan ncoghlan at gmail.com
Mon Oct 3 19:03:43 CEST 2011


On Mon, Oct 3, 2011 at 5:57 AM, Chris Rebert <pyideas at rebertia.com> wrote:
> 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.

+1

We get into similar discussions when it comes to higher order
itertools. Eventually, there are enough subtle variations that it
becomes a better option to let users write their own utility
functions.

In this case, there are at least 2 useful variants:

    def convert(target_type, obj, default)
        if obj:
            return target_type(obj)
        return default

    def try_convert(target_type, obj, default, ignored=(TypeError,))
        try:
            return target_type(obj)
        except ignored:
            return default

Exceptions potentially ignored include TypeError, AttributeError and
ValueError. However, you may also want to include logging so that you
can go through the logs later to find data that needs cleaning.

Except even in Dirkjan's example code, we see cases that don't fit
either model (they're comparing against a *particular* value and
otherwise just calling float()).

The question is whether there is a useful alternative that is as
general purpose as getattr/3 (which ignores AttributeError) and
dict.get/2 (which ignores KeyError). However, I think there are too
many variations in conversion function APIs and the way are used for
that to be of sufficiently general use - we'd be adding something new
that everyone has to learn, but far too much of the time they'd have
to do their own conversion anyway. I'd sooner see a getitem/3 builtin
that could be used to ignore any LookupError the way dict.get/3 allows
KeyError to be ignored.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list