[Python-ideas] with ... except

Andrew Barnert abarnert at yahoo.com
Fri Mar 8 20:01:27 CET 2013


On Mar 8, 2013, at 7:16, Antoine Pitrou <solipsis at pitrou.net> wrote:

> Le Fri, 8 Mar 2013 14:48:34 +0000,
> Oscar Benjamin
> <oscar.j.benjamin at gmail.com> 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.

If that's not his point, I apologize--but it was definitely my point when I said the same thing last week in response to the similar try with suggestion.


More information about the Python-ideas mailing list