Feb
5
#!/usr/bin/python """ yield.py Demonstrates a recursive generator method. This allows very large nested Container structures to be created, and when rendering to a string, we don't need to create the whole thing in memory (handy if, like me, you want to create 160,000 line XML files. """ class Container(object): def __init__(self, name, contents=[]): self.tag=name self.contents=contents def lines(self): """ Iterate over the text representing the Container and its contents. """ # This is a generator function; really it returns an iterable object. The # only reason you know this is that it contains the yield statement. On # one hand, a nasty gotcha for the rookie pythoneer, on the other hand, a # lovely concise way of doing something you will want to do often. yield "<%s>"%(self.tag.upper()) if isinstance(self.contents, str): yield self.contents else: for x in self.contents: if isinstance(x,Container): for l in x.lines(): yield l else: yield x yield "</%s>"%self.tag # Declare a structure of nested Container objects c=Container('HTML', [ Container('HEAD', [ Container('TITLE',[ "The quick and the Dead" ]) ]), Container('BODY', [ "The quick, that's me, and the dead, that's you.", Container('Blockquote', "Ar wuz never wun te be hackin' about this here county") ]), ]) # Now write the structure's text representation out. for l in c.lines(): print "Line: %s"%l
leave a reply
You must be logged in to post a comment.