[Python-Dev] cpython: Rename contextlib.ignored() to contextlib.ignore(). (original) (raw)

Victor Stinner victor.stinner at gmail.com
Wed Oct 16 13:42:34 CEST 2013


I might agree with idea of contextlib.ignore() (I'm still opposed to the idea), but I don't understand the purpose of adding a new syntax doing exactly the same than try/except:

with trap(OSError) as cm: os.unlink('missing.txt') if cm.exc: dosomething()

Nobody noticed that this can be written:

try: os.unlink('missing.txt') except OSError as err:

do something with err

?? What happened with the Zen Principle "There should be one-- and preferably only one --obvious way to do it." I don't understand why I would import contextlib and use a new context manager, whereas try/except is already a builtin feature of Python.

By the way, what are the performances of contextlib.ignore()? Exceptions can be slow in some cases. Adding something even slower would not be a good idea.

Victor

2013/10/15 Tim Delaney <timothy.c.delaney at gmail.com>:

On 16 October 2013 05:17, Alexander Belopolsky <alexander.belopolsky at gmail.com> wrote:

On Tue, Oct 15, 2013 at 12:45 PM, Ethan Furman <ethan at stoneleaf.us> wrote: > with trap(OSError) as cm: > os.unlink('missing.txt') > if cm.exc: > dosomething() .. and why is this better than try: os.unlink('missing.txt') except OSError as exc: dosomething() It would allow you to perform a series of operations then process the any exceptions all together e.g. with trap(OSError) as cm1: os.unlink('missing.txt') with trap(OSError) as cm2: os.unlink('othermissing.txt') with trap(OSError) as cm3: os.unlink('anothermissing.txt') for cm in (cm1, cm2, cm3): if cm.exc: dosomething(cm.exc) An equivalent implementation would be: exceptions = [] try: os.unlink('missing.txt') except OSError as exc: exceptions.append(exc) try: os.unlink('missing.txt') except OSError as exc: exceptions.append(exc) try: os.unlink('missing.txt') except OSError as exc: exceptions.append(exc) for exc in exceptions: if exc: dosomething(exc) Tim Delaney


Python-Dev mailing list Python-Dev at python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/victor.stinner%40gmail.com



More information about the Python-Dev mailing list