Created
August 9, 2012 11:22
-
-
Save micktwomey/3303374 to your computer and use it in GitHub Desktop.
Better to ask for forgiveness...
This file contains hidden or 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
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