Skip to content

Instantly share code, notes, and snippets.

@mpkocher
Created June 21, 2013 16:23
Show Gist options
  • Save mpkocher/5832403 to your computer and use it in GitHub Desktop.
Save mpkocher/5832403 to your computer and use it in GitHub Desktop.
Contextmanager usage to make error handling more pythonic. Back ported ignored from Py3K.
"""Example taken from Raymond Hettinger's Pycon 2013 talk"""
import sys
import os
from contextlib import contextmanager
_file_name = "Exampl3.fil3.tmp"
def terrible_example():
"""Terrible. Race condition"""
if os.path.exists(_file_name):
os.remove(_file_name)
def bad_example():
"""Solves Race condition. Ask for forgiveness, not permission model.
Not very pythonic.
"""
try:
os.remove(_file_name)
except OSError:
pass
@contextmanager
def ignored(*exceptions):
try:
yield
except exceptions:
pass
def good_example():
"""Pythonic approach a using contextmanager"""
with ignored(OSError):
os.remove(_file_name)
def main():
terrible_example()
bad_example()
good_example()
return 0
if __name__ == '__main__':
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment