[Python-ideas] with ... except

Stefan Behnel stefan_ml at behnel.de
Sat Mar 9 11:53:45 CET 2013


Antoine Pitrou, 09.03.2013 11:45:
> On Fri, 8 Mar 2013 11:01:27 -0800
> Andrew Barnert wrote:
>> On Mar 8, 2013, at 7:16, Antoine Pitrou wrote:
>>> Le Fri, 8 Mar 2013 14:48:34 +0000,
>>> Oscar Benjamin a écrit :
>>>>> or:
>>>>>
>>>>>  try:
>>>>>      with transaction.commit_on_success():
>>>>>          ...
>>>>>  except ObjectDoesNotExist:
>>>>>      # do something else, perhaps clean up some internal cache
>>>>
>>>> Another possibility is a context manager that handles both things,
>>>> e.g.:
>>>>
>>>> @contextmanager
>>>> def commit_or_clean(errorcls):
>>>>    try:
>>>>        with transaction.commit_on_success():
>>>>            yield
>>>>    except errorcls:
>>>>        clean()
>>>
>>> That's true, but only if the two things are strongly related, not in
>>> the general case.
>>
>> I think his point is that if you need any specific case often enough in your app, they will be related, and you can write a single context manager that wraps up your specific case so you can use it. In other words, messy with and try statements can be refactored into functions as needed, very easily.
> 
> Of course, you are right in some way. But it's a bit of a shame to have
> to resort to a helper function because the syntax isn't powerful
> enough :-)

OTOH, why add syntax for something that is easily done with a helper function?

Stefan





More information about the Python-ideas mailing list