Why don't generators execute until first yield?

Duncan Booth duncan.booth at invalid.invalid
Wed May 7 08:14:32 EDT 2008


Martin Sand Christensen <msc at es.aau.dk> wrote:

>>>>>> "Duncan" == Duncan Booth <duncan.booth at invalid.invalid> writes:
> [...]
> Duncan> Now try:
> Duncan> 
> Duncan>    for command in getCommandsFromUser():
> Duncan>        print "the result of that command was",
> execute(command) Duncan> 
> Duncan> where getCommandsFromUser is a greedy generator that reads
> from stdin, Duncan> and see why generators don't work that way.
> 
> I don't see a problem unless the generator isn't defined where it's
> going to be used. In other similar input bound use cases, such as the
> generator iterating over a query result set in my original post, I see
> even less of a problem. Maybe I'm simply daft and you need to spell it
> out for me. :-)

It does this:

>>> @greedy
def getCommandsFromUser():
	while True:
		yield raw_input('Command?')

		
>>> for cmd in getCommandsFromUser():
	print "that was command", cmd

	
Command?hello
Command?goodbye
that was command hello
Command?wtf
that was command goodbye
Command?

Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    for cmd in getCommandsFromUser():
  File "<pyshell#42>", line 11, in delayed
    for value in it:
  File "<pyshell#53>", line 4, in getCommandsFromUser
    yield raw_input('Command?')
KeyboardInterrupt



More information about the Python-list mailing list