peter9477

Comparison of callback and generator approaches

Nov 15th, 2013
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. Comparison of callback and generator approaches:
  2.  
  3. Callback approach:
  4.  
  5.     def onSomeEvent(self, data):
  6.         setup stuff
  7.         call-some-API(data, self.success_callback, self.error_callback)
  8.  
  9.  
  10.     def success_callback(self, data):
  11.         do stuff with data (as result)
  12.         tart.send('response', data)
  13.  
  14.         do another API call with more callbacks...
  15.  
  16.  
  17.     def error_callback(self, data):
  18.         handle the error case
  19.         tart.send('blarg')
  20.  
  21.     x10 for pain level
  22.  
  23.  
  24. Generator approach:
  25.  
  26.     def onSomeEvent(self, data):
  27.         setup stuff
  28.         try:
  29.             result = yield ApiCallObject(data)
  30.  
  31.         except ApiCallError:
  32.             handle the error case
  33.             tart.send('blarg')
  34.             return
  35.  
  36.         do stuff with result
  37.         tart.send('response', result)
  38.  
  39.         do another API call, in-line without callbacks...
  40.  
  41.         even nice things like: yield TimeDelay(seconds=1.5)
  42.         or fancier stuff like:
  43.  
  44.         try:
  45.             yield Timeout(seconds=1.0)
  46.             yield ApiCall()
  47.         except TimeoutError:
  48.             oops, the operation didn't complete in time
  49.        except ApiCallError:
  50.            oops, the operation failed
  51.        else:
  52.            yay! everything worked and the timeout is cancelled automatically
Advertisement
Add Comment
Please, Sign In to add comment