On Tue, Oct 4, 2011 at 9:37 AM, Masklinn <masklinn@masklinn.net> wrote:

On 2011-10-04, at 08:58 , David Townshend wrote:

>>
>>   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
That's basically what the function you've rejected does (you got the arguments order wrong):

   x = try_convert(float, 'some text', default=42, ignored=ValueError)

Just rename an argument or two and you have the exact same thing.

Same functionality, but try_convert is a function with lots of arguments whereas my alternative is an expression.  But to be honest, I don't really like either.  In cases that require the level of control that try_convert provides, the try statement is cleaner.  The point I'm really trying to make is that my initial proposal was for a specific but common use case (float and int), not a general-purpose conversion tool.