From: sdm7g at virginia.edu (Steven D. Majewski)
Date: Fri, 23 Apr 1999 23:40:33 GMT
Subject: Style/efficiency question using 'in'
In-Reply-To: <3720C3F3.CFF6D739@callware.com>
References: <3720C3F3.CFF6D739@callware.com>
Message-ID: <Pine.A32.3.90.990423192440.23052H-100000@elvis.med.Virginia.EDU>
Content-Length: 1738
X-UID: 517                                                  

On Fri, 23 Apr 1999, Ivan Van Laningham wrote several variations 
on 'for x in y' : 


And just to confuse the new user even further, lets add pseudo
sequences onto the pile.

The actual protocol that 'for' uses is to get the next item in
the sequence until an IndexError is raised.   Earlier versions
of Python compared the index to len() each time thru. I think
I can claim some credit in inspiring Guido to change that behaviour
by writing some Really Ugly classes which lied about their length
in order to implement indefinite or lazy sequences. Now, it's a 
snap: all you have to do is implement __getitem__ to make something
appear as a sequence to 'for' and 'in'. 

For example, rather than reading in a entire file and splitting it
into tokens or chunks all at once, you can make a lazy sequence which
reads another chunk of the file if needed and parses the next token
each time __getitem__ is called with a larger index. You main loop
would be something like 'for tok in Tokens( filename ): ' 

A simpler example: 

>>> class Squares:
... 	def __init__( self, n ):
... 		self.n = n
... 	def __getitem__( self, i ):
... 		if i < self.n : return i*i 
... 		else: raise IndexError
... 
>>> sq = Squares(10)
>>> for x in sq: print x
... 
0
1
4
9
16
25
36
49
64
81
>>> if 4 in sq : print 'YES' 
... 
YES
>>> 

---|  Steven D. Majewski   (804-982-0831)  <sdm7g at Virginia.EDU>  |---
---|  Department of Molecular Physiology and Biological Physics  |---
---|  University of Virginia             Health Sciences Center  |---
---|  P.O. Box 10011            Charlottesville, VA  22906-0011  |---

    Caldera Open Linux: "Powerful and easy to use!" -- Microsoft(*)
     (*) <http://www.pathfinder.com/fortune/1999/03/01/mic.html>
 





