[Python-ideas] Default return values to int and float
Jan Kaliszewski
zuo at chopin.edu.pl
Thu Oct 6 17:47:22 CEST 2011
Guido van Rossum dixit (2011-10-04, 19:21):
> Other ideas: returning some more structured object than an integer
> (like re.match does) feels like overkill, and returning an (index,
> success) tuple is begging for lots of mysterious occurrences of [0] or
> [1].
A lightweight builtin type whose instances would have `index` attribute
might do the job well (together with None as not-found).
A naive pure-Python implementation:
class Found(object):
__slots__ = 'index',
def __init__(self, index):
self.index = index
Example usage:
found = s.find('foo')
if found: # or more explicit: `if found is not None:`
print('foo found at %d' % found.index)
else:
# found is None
print('foo not found')
Of course that would be probably a new method, not str.find(), say:
str.search(). Then it could be possible to make it a bit more
universal, accepting substring tuples (as startswith/endswith
already do):
Example usage:
one_of = 'foo', 'bar', 'baz'
found = s.search(one_of)
if found:
print('%s found at %d' % (found.substring, found.index))
else:
print('None of %s found' % one_of)
The 4th line could be respelled as:
index, substring = found
print('%s found at %d' % (substring, index))
A naive implementation of s.search() result type:
class Found(object):
__slots__ = 'index', 'substring'
def __init__(self, index, substring):
self.index = index
self.substring = substring
def __iter__(self):
yield self.index
yield self.substring
Cheers,
*j
More information about the Python-ideas
mailing list