Yield

Tim Chase python.list at tim.thechases.com
Thu Nov 16 11:53:17 EST 2006


>> I absoultely agree.  Thanks for pointing me out to some real-world
>> code.  However, the function you pointed me to is not a generator
>> (there is no yield statement... it just returns the entire list of
>> primes).
> 
> Oops,  should have looked at the code more closely. Another example
> would be os.walk() in the standard library. 

I've used a similar scheme for dealing with incoming data files. 
  Sometimes, I get them Emailed/FTP'ed so they're sitting in a 
folder, so I can do a multitude of them by just pointing 
os.walk() at them.  Other times, I get them on specially 
formatted CDs.  It's nice to have the clean main-loop logic of:

	for file_name in source:
		do_stuff(file_name)

and be able to dynamically set "source" to an generator that 
either wraps os.walk() for a given directory or repeatedly (1) 
reads the file on the CD to know where it should be dumped, (2) 
copies files off the CD to their associated dumping ground, (3) 
ejects the CD, (4) yields the name of the file to process in the 
dumping-ground directory, and (5) prompts the user if there are 
more CDs to be processed.

Without "yield" functionality, I'd either have to have two 
duplicate loops with similar internal logic (the do_stuff() sort 
of code), or I'd have to read in all the files off the CD and 
*then* process them all as a list afterwards.

Just one of the places I've recently been thankful for generators.

-tkc








More information about the Python-list mailing list