[Python-ideas] Default return values to int and float
Carl Matthew Johnson
cmjohnson.mailinglist at gmail.com
Tue Oct 4 06:00:01 CEST 2011
On Oct 3, 2011, at 7:03 AM, Nick Coghlan wrote:
>
> def try_convert(target_type, obj, default, ignored=(TypeError,))
> try:
> return target_type(obj)
> except ignored:
> return default
This reminds me of the string.index vs. string.find discussion we had a while back. In basically any situation where an exception can be raised, it's sometimes nice to return a None-like value and sometimes nice to have an out-of-band exception. I have a certain amount of admiration for the pattern in Go of returning (value, error) from most functions that might have an error, but for Python as it is today, there's no One Obvious Way to Do It yet, and there's probably none forthcoming. A slightly more generalized form of try_convert might be useful (see below), but then again, we can't just pack every possible 5 line function into the standard library…
> def catch(exception, f, *args, kwargs={}, default=None)
> try:
> return f(*args, **kwargs)
> except exception:
> return default
>>> catch(ValueError, "abc".index, "z", default="Not Found")
'Not Found'
>>> catch(ValueError, float, "zero", default=0.0)
0.0
More information about the Python-ideas
mailing list