[Python-ideas] Default return values to int and float
David Townshend
aquavitae69 at gmail.com
Tue Oct 4 08:58:31 CEST 2011
>
> def try_convert(target_type, obj, default, ignored=(TypeError,))
> try:
> return target_type(obj)
> except ignored:
> return default
>
The problem with a general convert function is that to make it work, you
would need to account for several variations and the signature gets rather
clunky. Personally, I think that the try format:
try:
return float('some text')
except ValueError:
return 42
is more readable than
try_convert('some text', float, 42, (ValueError,))
because it is clear what it does. The second form is shorter, but not as
descriptive. However,
float('some text', default=42)
follows the existing syntax quite nicely, and is more readable than either
of the other options.
A generalised try_convert method would be useful, but I think I would rather
see a one-line version of the try statements, perhaps something like this:
x = try float('some text') else 42 if ValueError
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111004/7c058f5f/attachment.html>
More information about the Python-ideas
mailing list