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

Massimo Di Pierro massimo.dipierro at gmail.com
Mon Oct 3 16:10:48 CEST 2011


+1

On Oct 3, 2011, at 8:55 AM, Michael Foord wrote:

> 
> 
> On 3 October 2011 08:52, David Townshend <aquavitae69 at gmail.com> wrote:
> My idea is fairly simple: add a "default" argument to int and float,
> allowing a return value if the conversion fails.  E.g:
> 
> >>> float('cannot convert this', default=0.0)
> 0.0
> 
> 
> 
> Something similar to this is pretty common in other languages. For example .NET has System.Double.TryParse
> 
> http://msdn.microsoft.com/en-us/library/994c0zb1.aspx
> 
> The pattern there is equivalent to returning an extra result as well as the converted value - a boolean indicating whether or not the conversion succeeded (with the "converted value" being 0.0 where conversion fails). A Python version might look like:
> 
> success, value = float.parse('thing')
> if success:
>     ...
> 
> Part of the rational for this approach in .NET is that exception handling is very expensive, so calling TryParse is much more efficient than catching the exception if parsing fails.
> 
> All the best,
> 
> Michael Foord
>  
> I think there are many use cases for this, every time float() or int()
> are called with data that cannot be guaranteed to be numeric, it has
> to be checked and some sort of default behaviour applied.  The above
> example is just much cleaner than:
> 
> try:
>    return float(s)
> except ValueError:
>    return 0.0
> 
> 
> Any takers?
> 
> David
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
> 
> 
> 
> -- 
> http://www.voidspace.org.uk/
> 
> May you do good and not evil
> May you find forgiveness for yourself and forgive others
> 
> May you share freely, never taking more than you give.
> -- the sqlite blessing http://www.sqlite.org/different.html
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20111003/14627ac0/attachment.html>


More information about the Python-ideas mailing list