[Python-de] Frage zur Implementierung von Generatoren (yield)

Mark Zöltsch zoeltsch at mooniewar.de
Die Jun 3 16:23:45 EDT 2003


>Kannst Du mal ein Beispiel angeben? Wenn ein Generator "sich selbst"
>wieder ruft, wird *ganz bestimmt* für den inneren Generator ein neues
>Frame-Objekt erzeugt.

z.B. der XML Walk Tree Generator von Ogbuji (klein und sogar 
sinnvoll :) )
http://www-106.ibm.com/developerworks/library/x-tipgenr.html

#Required in Python 2.2, and must be the first import
from __future__ import generators
from xml.dom import Node

def doc_order_iter(node):
    """
    Iterates over each node in document order,
    returning each in turn
    """
    #Document order returns the current node,
    #then each of its children in turn
    yield node
    for child in node.childNodes:
        #Create a generator for each child,
        #Over which to iterate
        for cn in doc_order_iter(child):
            yield cn
    return

#Parse a document then print the Python representation
#of each node object in document order

DOC = """\
<memo xmlns='http://spam.com'>
<date form="iso-8601">2002-08-14</date>
This is just to <strong>say</strong>:
I ate the eggs you left in the fridge
And were probably saving for breakfast.
Do you know?  They were <emph>quite</emph> rotten.
</memo>
"""

from xml.dom import minidom
doc = minidom.parseString(DOC)
for node in doc_order_iter(doc):
    print node