Skip to content

Instantly share code, notes, and snippets.

@micktwomey
Created August 9, 2012 11:22
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 micktwomey/3303374 to your computer and use it in GitHub Desktop.
Save micktwomey/3303374 to your computer and use it in GitHub Desktop.
Better to ask for forgiveness...
import contextlib
import functools
@contextlib.contextmanager
def forgiveness(exceptions):
"""Seek forgiveness
"""
try:
yield
except exceptions:
pass
class PermissionDenied(Exception):
pass
@contextlib.contextmanager
def askfor():
"""Used to ask for permission
"""
try:
yield
except PermissionDenied:
pass
@contextlib.contextmanager
def permission(callable):
"""Give permission to proceed
"""
if callable():
yield
else:
raise PermissionDenied()
if __name__ == '__main__':
import os
with forgiveness(FileExistsError):
print("Trying to create /tmp/foo")
os.mkdir("/tmp/foo")
print("Look no exception, forgiveness was given!")
with askfor(), permission(lambda: not os.path.isdir("/tmp/bar")):
print("Permission given to create /tmp/bar")
os.mkdir("/tmp/bar")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment