Skip to content

Instantly share code, notes, and snippets.

@flashingpumpkin
Created July 18, 2014 11:25
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 flashingpumpkin/77b2ca4f22ea3eeb1b82 to your computer and use it in GitHub Desktop.
Save flashingpumpkin/77b2ca4f22ea3eeb1b82 to your computer and use it in GitHub Desktop.
class Try(object):
"""
Encapsulate an operation potentially throwing an error. A try
instance is `True` if no error was thrown, it's `False` if an
error occured.
"""
def __init__(self, fn):
self.fn = fn
self()
@property
def get(self):
if self.is_success():
return self.result
raise self.error
def is_success(self):
return bool(self)
def is_failure(self):
return not bool(self)
def __call__(self):
try:
self.result = self.fn()
except Exception as e:
self.error = e
def __nonzero__(self):
if hasattr(self, 'result'):
return True
else:
return False
def raising(self, fn = lambda err: err):
"""
Return this try or raise `fn` applied to this try's exception.
::
soup = Try(lambda: Soup(self.get('file').read(), 'xml')).raising(
lambda err: forms.ValidationError("Please upload a valid XML file")).get
"""
if self.is_failure(): raise fn(self.error)
else: return self
def failing(self, fn = lambda err: err):
"""
Return this try or a new try with `fn` applied to this try's
exception.
::
Try(lambda: self.process(soup.find('Synopsis').text))).failing(
lambda err: self.log(err))
"""
if self.is_failure(): Try(lambda: fn(self.error))
else: return self
def get_or_else(self, fn):
"""
Return the result of this try or in case of failure the result of
`fn`
::
user = Try(lambda: soup.find('User')['id'])).get_or_else(
lambda: None)
"""
if self.is_success(): return self.result
else: return fn()
def or_else(self, fn):
"""
Return this try or in case of failure a new try wrapped around `fn`
::
Try(lambda: self.set('category', soup.find('Category').text)).or_else(
lambda: self.set('category', self.DEFAULT_CATEGORY))
"""
if self.is_failure(): Try(fn)
else: return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment