conatraints on "for" magic?

david_ullrich at my-deja.com david_ullrich at my-deja.com
Wed Jul 26 12:55:45 EDT 2000


   I don't recall seeing a precise statement about this
in the docs (which no doubt just proves I haven't looked)
but it's in various books for example Lutz (book at home,
title is either "Learning Python" or not): When you
say "for x in someInstance" the __getitem__ is called
repeatedly, with an index starting at 0 and increasing
by 1 each time, terminating when there is an IndexError:

class Squares:
	def __init__(self, count):
		self.count = count
	def __getitem__(self, index):
		if not (index < self.count):
			raise IndexError
		return index*index

for x in Squares(10):
	print x

DU

In article <8llqso$q75$1 at news.dtc.hp.com>,
  weeks at golden.dtc.hp.com ((Greg Weeks)) wrote:
> Initially I learned that
>
>     for x in seq:
> 	<do stuff>
>
> required seq to be a sequence.  But then I saw the code:
>
>     import fileinput
>     for line in fileinput.input():
> 	<do stuff>
>
> How did the implementer of the "fileinput" module convince the "for"
> construct that fileinput.input() was a sequence?
>
> (In "Python ESSENTIAL REFERENCE" I don't find any way of creating
class
> instances that are recognized by "for" as sequences.)
>
> Regards,
> Greg
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list