conatraints on "for" magic?

Olaf Delgado delgado at olaf.de
Wed Jul 26 05:28:59 EDT 2000


In article <8llqso$q75$1 at news.dtc.hp.com>,
	weeks at golden.dtc.hp.com ((Greg Weeks)) writes:

> How did the implementer of the "fileinput" module convince the "for"
> construct that fileinput.input() was a sequence?

AFAIR, when you write

    for x in seq:
         <do stuff>

Python does something like

    i = 0
    while (1):
        try:
            x = seq[i]
        except IndexError:
            break;
        <do stuff>
        i = i + 1

where, if seq is a class instance, seq[i] just calls
seq.__getitem__(i). So, for classes, all you have to do is to
implement an appropriate __getitem__ method. For builtin types, such
as implemented in an extension module, there is a similar 'magic
method' the implementor may provide.

Regards,

-- 
  ////
  Olaf  Delgado Friedrichs, Bielefeld, Germany
  `='   --- http://www.mathematik.uni-bielefeld.de/~delgado ---



More information about the Python-list mailing list