FrontPage
RecentChanges
FindPage
PageIndex
UnusedPages
UndefinedPages
XpApprentices

Set your name in
UserPreferences

Edit this page



Referenced by
Xtc20021029




JSPWiki v2.0.36


PythonGenerators

[old:PythonGenerators]

Python has a new language feature called generators, which I read about on the site below:

http://www-106.ibm.com/developerworks/library/l-pycon.html?t=gr,lnxw06=PyIntro?

Does anyone know the rationale behind doing this rather than a 'SmallTalk block' type approach (now that the scoping rules have been fixed in Python). I have included some code to show both approaches (needs Python 2.2) ? IvanM

from future import generators

class Node: pass

a=Node() a.left=Node() a.value='d' a.right=Node() a.right.left=None a.right.right=None a.right.value='e' a.left.value='b' a.left.left=Node() a.left.right=Node() a.left.left.left=None a.left.left.right=None a.left.left.value='a' a.left.right.left=None a.left.right.right=None a.left.right.value='c'

#generator way

def walk(tree): if tree==None: return for n in walk(tree.left): yield n yield tree.value for n in walk(tree.right): yield n

print 'using generator' for n in walk(a): print n

#'smalltalk block' way

def do(tree,block): if tree==None: return do(tree.left, block) block(tree.value) do(tree.right, block)

def prn(x): print x

print 'using smalltalk block style' do(a, prn)


http://www.python.org/peps/pep-0255.html has the rationale for generators. However in your example the biggest difference seems to be in memory used. Every level of recursion will require yet another stack frame to be maintained. Whereas the generator approach will only require one. It's o(1) versus o(n).--AdewaleOshineye Sorry, the above is wrong, they're both recursive.--ao
One more attempt. The generators PEP came after iterators (PEP 234) and most of the discussion was focussed around laziness, the Icon and Sather approaches and being able to write simple for..in loops to abstract away the producer-consumer relationship using the iterator protocol. Comp.lang.python was filled with lots of discussion of it. Oddly enough no-one mentioned smalltalk even once in the discussion.--ao³host³³date³October 29, 2002³agent³Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.2b) Gecko/20021016³PythonGenerators


Edit this page   More info...   Attach file...
This page last changed on 29-Oct-2002 16:55:06 GMT by unknown.