2014-12-24 18:28:23 +00:00
|
|
|
"""Utilities for with-statement contexts. See PEP 343.
|
2014-12-24 18:26:21 +00:00
|
|
|
|
2014-12-24 18:28:23 +00:00
|
|
|
Original source code: https://hg.python.org/cpython/file/3.4/Lib/contextlib.py
|
2014-12-24 18:26:21 +00:00
|
|
|
|
2014-12-24 18:28:23 +00:00
|
|
|
Not implemented:
|
|
|
|
- redirect_stdout;
|
|
|
|
- ExitStack.
|
2014-12-24 18:26:21 +00:00
|
|
|
|
2014-12-24 18:28:23 +00:00
|
|
|
"""
|
2014-12-24 18:26:21 +00:00
|
|
|
|
2015-10-20 21:20:02 +00:00
|
|
|
from ucontextlib import *
|
2014-12-24 18:26:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
class closing(object):
|
|
|
|
"""Context to automatically close something at the end of a block.
|
|
|
|
|
|
|
|
Code like this:
|
|
|
|
|
|
|
|
with closing(<module>.open(<arguments>)) as f:
|
|
|
|
<block>
|
|
|
|
|
|
|
|
is equivalent to this:
|
|
|
|
|
|
|
|
f = <module>.open(<arguments>)
|
|
|
|
try:
|
|
|
|
<block>
|
|
|
|
finally:
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
"""
|
|
|
|
def __init__(self, thing):
|
|
|
|
self.thing = thing
|
|
|
|
def __enter__(self):
|
|
|
|
return self.thing
|
|
|
|
def __exit__(self, *exc_info):
|
|
|
|
self.thing.close()
|
|
|
|
|
|
|
|
|
|
|
|
class suppress:
|
|
|
|
"""Context manager to suppress specified exceptions
|
|
|
|
|
|
|
|
After the exception is suppressed, execution proceeds with the next
|
|
|
|
statement following the with statement.
|
|
|
|
|
|
|
|
with suppress(FileNotFoundError):
|
|
|
|
os.remove(somefile)
|
|
|
|
# Execution still resumes here if the file was already removed
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, *exceptions):
|
|
|
|
self._exceptions = exceptions
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __exit__(self, exctype, excinst, exctb):
|
|
|
|
# Unlike isinstance and issubclass, CPython exception handling
|
|
|
|
# currently only looks at the concrete type hierarchy (ignoring
|
|
|
|
# the instance and subclass checking hooks). While Guido considers
|
|
|
|
# that a bug rather than a feature, it's a fairly hard one to fix
|
|
|
|
# due to various internal implementation details. suppress provides
|
|
|
|
# the simpler issubclass based semantics, rather than trying to
|
|
|
|
# exactly reproduce the limitations of the CPython interpreter.
|
|
|
|
#
|
|
|
|
# See http://bugs.python.org/issue12029 for more details
|
|
|
|
return exctype is not None and issubclass(exctype, self._exceptions)
|