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

Ethan Furman ethan at stoneleaf.us
Wed Oct 5 07:38:59 CEST 2011


Guido van Rossum wrote:
> On Tue, Oct 4, 2011 at 4:13 PM, Steven D'Aprano wrote:
>> However, returning None as re.match does is better than returning -1 as
>> str.find does, as -1 can be mistaken for a valid result but None can't be.
> 
> What works for re.match doesn't work for str.find. With re.match, the
> result when cast to bool is true when there's a match and false when
> there isn't. That's elegant.

[snip]

> But with str.find, 0 is a legitimate result, so if we were to return
> None there'd be *two* outcomes mapping to false: no match, or a match
> at the start of the string, which is no good.

[snip]

> Other ideas: returning some more structured object than an integer
> (like re.match does) feels like overkill

[snip]

> I'm out of ideas here. But of all these, str.find is probably still
> the worst -- I've flagged bugs caused by it too many times to count.

What's correct code worth?  My contributions to other Open Source 
projects is so minor as to not register, but the first bug report/patch 
I ever submitted was a str.find issue.

A structured object that behaved like an int /except/ for its boolean 
checks might do the trick here.  Something like:

class FindResult(int):
     def __bool__(self):
         return self != -1

Code that checks for -1 (like it should) will keep working, and code 
that doesn't will start working.

~Ethan~




More information about the Python-ideas mailing list