[Python-ideas] One-line "try with" statement

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 5 16:56:13 CET 2013

On 3 March 2013 21:36, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Stefan Behnel wrote:
>> The above example therefore strikes me as
>> useless. If you need a try-except around a with block, then your context
>> manager is doing something wrong.
> A with statement is equivalent to try-finally, not try-except,
> so if you want to catch the exception you still need to put
> a try-except somewhere.

With statements can be used for any kind of exception handling you
like, not just try/finally. For example:

import contextlib

def ignore(errorcls):
    except errorcls:

with ignore(ValueError):
    a = int('a')


More information about the Python-ideas mailing list