Envelope/Quill PythonGenerators

- Last edited October 29, 2002
Python has a new language feature called generators, which I read about on the site below:

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)

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
- Last edited October 29, 2002

https://casino-brain.com/