Skip to content

Instantly share code, notes, and snippets.

@theho
Created May 20, 2015 00:07
Show Gist options
  • Save theho/79f1c1f94f0dba5aaaa2 to your computer and use it in GitHub Desktop.
Save theho/79f1c1f94f0dba5aaaa2 to your computer and use it in GitHub Desktop.
Methon chaining inspired by $q / Q in Javascript
# Inspired by $q/Q in javascript to chain methods
class Q:
def __init__(self, d):
self.d = d
self.error = None
def then(self, fn):
if not self.error:
try:
self.d = fn(self.d)
except Exception as e:
self.error = e
return self
def catch(self, fn):
if self.error:
fn(self.error)
return self
def done(self):
return self.d
if __name__=='__main__':
input = 123
def add(d):
d+=999
return d
def insert(d):
d+=102
raise Exception('hello')
return d
def abc(e):
print ('error', e)
print(Q(input).then(add).then(insert).catch(abc).then(add).done())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment