or float("cannot convert this") or 0.0 if ValueError i.e. map x = [expression] or [value] if [exception] into try: x = [expression] except [exception] x = [value] On Oct 3, 2011, at 8:55 AM, Michael Foord wrote:
On 3 October 2011 08:52, David Townshend <aquavitae69@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@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@python.org http://mail.python.org/mailman/listinfo/python-ideas