use the same logic for callbacks regardless of is_done status

This commit is contained in:
Zack Dever
2016-04-25 14:22:51 -07:00
parent aefafd270a
commit 0300edb353

View File

@@ -5,6 +5,8 @@ log = logging.getLogger(__name__)
class Future(object): class Future(object):
error_on_callbacks = False # and errbacks
def __init__(self): def __init__(self):
self.is_done = False self.is_done = False
self.value = None self.value = None
@@ -28,11 +30,7 @@ class Future(object):
assert not self.is_done, 'Future is already complete' assert not self.is_done, 'Future is already complete'
self.value = value self.value = value
self.is_done = True self.is_done = True
for f in self._callbacks: self._call_backs('callback', self._callbacks, self.value)
try:
f(value)
except Exception:
log.exception('Error processing callback')
return self return self
def failure(self, e): def failure(self, e):
@@ -41,18 +39,14 @@ class Future(object):
assert isinstance(self.exception, BaseException), ( assert isinstance(self.exception, BaseException), (
'future failed without an exception') 'future failed without an exception')
self.is_done = True self.is_done = True
for f in self._errbacks: self._call_backs('errback', self._errbacks, self.exception)
try:
f(self.exception)
except Exception:
log.exception('Error processing errback')
return self return self
def add_callback(self, f, *args, **kwargs): def add_callback(self, f, *args, **kwargs):
if args or kwargs: if args or kwargs:
f = functools.partial(f, *args, **kwargs) f = functools.partial(f, *args, **kwargs)
if self.is_done and not self.exception: if self.is_done and not self.exception:
f(self.value) self._call_backs('callback', [f], self.value)
else: else:
self._callbacks.append(f) self._callbacks.append(f)
return self return self
@@ -61,7 +55,7 @@ class Future(object):
if args or kwargs: if args or kwargs:
f = functools.partial(f, *args, **kwargs) f = functools.partial(f, *args, **kwargs)
if self.is_done and self.exception: if self.is_done and self.exception:
f(self.exception) self._call_backs('callback', [f], self.exception)
else: else:
self._errbacks.append(f) self._errbacks.append(f)
return self return self
@@ -75,3 +69,12 @@ class Future(object):
self.add_callback(future.success) self.add_callback(future.success)
self.add_errback(future.failure) self.add_errback(future.failure)
return self return self
def _call_backs(self, back_type, backs, value):
for f in backs:
try:
f(value)
except Exception as e:
log.exception('Error processing %s', back_type)
if self.error_on_callbacks:
raise e