
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.