Created
June 21, 2013 16:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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