[Tutor] Generator questions.
rumpy at mrbitter.org
rumpy at mrbitter.org
Wed Dec 6 20:59:54 CET 2006
Hi Folks,
I'm working through Magnus Lie Hetland's excellent book "Beginning
Python" and I have a few basic (I think) questions. Specifically,
regarding his first project in Chapter 20(Instant Markup).
The outline of the project is to take a plain text file and "mark it
up" into HTML or XML. Step one is simply getting the tool to recognize
basic elements of a text document - blocks of text seperated by empty
lines.
To this end the following file is created as a module(?) to be imported
into the
subsequent primary execution (main?) script.
def lines(file):
for line in file: yield line
yield '\n'
del blocks(file):
block = []
for line in lines(file):
if line.strip():
block.append(line)
elif block:
yield ''.join(block).strip()
block = []
Now, for the most part I understand what's going on here. The part that
puzzles me a bit is:
elif block:
yield ''.join(block).strip()
block = []
1.) Does the yield mean the block list is returned from the function
AND then wiped out by 'block = []'?
2.) Is block list scrubbed clean by 'block = []' because the function
is going to iterate over the next block and it needs to be empty?
3.) The statement after the 'yield' threw me. I haven't seen that to
this point in the book. I figured 'yield' is always last in a function
because it needs to iterate over itself again. Am I understanding
generators correctly?
4.) Is it correct to say that a generator is a function that returns
multiple values and iterates over itself?
Thanks in advance for any feedback/help.
Rumpy.
More information about the Tutor
mailing list