Skip to content

Instantly share code, notes, and snippets.

@bryan-lott
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryan-lott/61575e5118c4e9964c96 to your computer and use it in GitHub Desktop.
Save bryan-lott/61575e5118c4e9964c96 to your computer and use it in GitHub Desktop.
Context Manager - Ignore Exceptions and Others
"""Not sure where this came from, but I suspect
it was from a python talk about making beautiful
code."""
from contextlib import contextmanager
@contextmanager
def ignored(*exceptions):
"""Ignore a provided list of exceptions."""
try:
yield
except exceptions:
pass
# for other context handler functions, yield can
# return a value, ie:
tempfilenames = ['test1.txt', 'test2.txt', 'error1.txt']
@contextmanager
def create_test_folder():
"""Creates a test directory structure."""
testfolder = tempfile.mkdtemp(suffix='test')
test_text = 'temporary test file'
for fname in tempfilenames:
with open(path.join(testfolder, fname), 'w') as f:
f.write(test_text)
try:
yield testfolder
finally:
for fname in tempfilenames:
os.remove(path.join(testfolder, fname))
os.rmdir(testfolder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment