On 3 October 2011 08:52, David Townshend firstname.lastname@example.org 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)
Something similar to this is pretty common in other languages. For example .NET has System.Double.TryParse
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,
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
David _______________________________________________ Python-ideas mailing list Pythonemail@example.com http://mail.python.org/mailman/listinfo/python-ideas