[Twisted-Python] raw deferreds vs deferredGenerator vs inlineCallbacks

Jean-Paul Calderone exarkun at divmod.com
Wed Aug 13 13:57:34 EDT 2008

On Wed, 13 Aug 2008 19:47:53 +0200, Marcin Kasperski <marcin.kasperski at softax.com.pl> wrote:
>I wrote a short example comparing the 3. Prepared it mostly for
>myself, but maybe it will be of some use for somebody:
>PS Crucial function:
>  raw deferreds     - 29 non-empty lines of code,
>  deferredGenerator - 26 lines,
>  inlineCallbacks   - 17 lines

Nice comparison.  A more idiomatic rendering of the "raw deferred"
example might look like this, though:

  def lookup(country, search_term):
      query = "http://www.google.%s/search?q=%s" % (country,search_term)
      d = getPage(query)
      def cbFirstPage(content, country):
          m = re.search('<div id="?res.*?href="(?P<url>http://[^"]+)"',
                        content, re.DOTALL)
          if not m:
              return None
          url = m.group('url')
          d = getPage(url)
          def cbSecondPage(content, country, url):
              m = re.search("<title>(.*?)</title>", content)
              if m:
                  title = m.group(1)
                  return dict(url = url, title = title)
                  return dict(url=url, title="<not-specified>")
          d.addCallback(cbSecondPage, country, url)
          return d
      d.addCallback(cbGotPage, country)
      def ebGeneric(err, country):
          print ".%s FAILED: %s" % (country, str(e))
      d.addErrback(ebGeneric, country)
      return d

Converting any failure into a print and a None result is a bit strange,
but it's the same thing your other two examples did so I preserved that


More information about the Twisted-Python mailing list