Skip to content

Commit fa6cce1

Browse files
committed
Minor fixups and added sections for iterators and generators.
1 parent 6d3e018 commit fa6cce1

File tree

1 file changed

+117
-3
lines changed

1 file changed

+117
-3
lines changed

Doc/tut/tut.tex

Lines changed: 117 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3731,7 +3731,7 @@ \subsection{Class Objects \label{classObjects}}
37313731
Class attributes can also be assigned to, so you can change the value
37323732
of \code{MyClass.i} by assignment. \member{__doc__} is also a valid
37333733
attribute, returning the docstring belonging to the class: \code{"A
3734-
simple example class"}).
3734+
simple example class"}.
37353735
37363736
Class \emph{instantiation} uses function notation. Just pretend that
37373737
the class object is a parameterless function that returns a new
@@ -4128,7 +4128,8 @@ \section{Odds and Ends \label{odds}}
41284128
object of which the method is an instance, and \code{m.im_func} is the
41294129
function object corresponding to the method.
41304130
4131-
\subsection{Exceptions Are Classes Too\label{exceptionClasses}}
4131+
4132+
\section{Exceptions Are Classes Too\label{exceptionClasses}}
41324133
41334134
User-defined exceptions are identified by classes as well. Using this
41344135
mechanism it is possible to create extensible hierarchies of exceptions.
@@ -4184,6 +4185,119 @@ \subsection{Exceptions Are Classes Too\label{exceptionClasses}}
41844185
\function{str()}.
41854186
41864187
4188+
\section{Iterators\label{iterators}}
4189+
4190+
By now, you've probably noticed that most container objects can looped over
4191+
using a \code{for} statement:
4192+
4193+
\begin{verbatim}
4194+
for element in [1, 2, 3]:
4195+
print element
4196+
for element in (1, 2, 3):
4197+
print element
4198+
for key in {'one':1, 'two':2}:
4199+
print key
4200+
for char in "123":
4201+
print char
4202+
for line in open("myfile.txt"):
4203+
print line
4204+
\end{verbatim}
4205+
4206+
This style of access is clear, concise, and convenient. The use of iterators
4207+
pervades and unifies Python. Behind the scenes, the \code{for} statement calls
4208+
\function{iter()} on the container object. The function returns an iterator
4209+
object that defines the method \method{next()} which accesses elements in the
4210+
container one at a time. When there are no more elements, \method{next()}
4211+
raises a \exception{StopIteration} exception which tells the \code{for} loop
4212+
to terminate. This example shows how it all works:
4213+
4214+
\begin{verbatim}
4215+
>>> s = 'abc'
4216+
>>> it = iter(s)
4217+
>>> it
4218+
<iterator object at 0x00A1DB50>
4219+
>>> it.next()
4220+
'a'
4221+
>>> it.next()
4222+
'b'
4223+
>>> it.next()
4224+
'c'
4225+
>>> it.next()
4226+
4227+
Traceback (most recent call last):
4228+
File "<pyshell#6>", line 1, in -toplevel-
4229+
it.next()
4230+
StopIteration
4231+
\end{verbatim}
4232+
4233+
Having seen the mechanics behind the iterator protocol, it is easy to add
4234+
iterator behavior to your classes. Define a \method{__iter__()} method
4235+
which returns an object with a \method{next()} method. If the class defines
4236+
\method{next()}, then \method{__iter__()} can just return \code{self}:
4237+
4238+
\begin{verbatim}
4239+
>>> class Reverse:
4240+
"Iterator for looping over a sequence backwards"
4241+
def __init__(self, data):
4242+
self.data = data
4243+
self.index = len(data)
4244+
def __iter__(self):
4245+
return self
4246+
def next(self):
4247+
if self.index == 0:
4248+
raise StopIteration
4249+
self.index = self.index - 1
4250+
return self.data[self.index]
4251+
4252+
>>> for char in Reverse('spam'):
4253+
print char
4254+
4255+
m
4256+
a
4257+
p
4258+
s
4259+
\end{verbatim}
4260+
4261+
4262+
\section{Generators\label{generators}}
4263+
4264+
Generators are a simple and powerful tool for creating iterators. They are
4265+
written like regular functions but use the \keyword{yield} statement whenever
4266+
they want to return data. Each time the \method{next()} is called, the
4267+
generator resumes where it left-off (it remembers all the data values and
4268+
which statement was last executed). An example shows that generators can
4269+
be trivially easy to create:
4270+
4271+
\begin{verbatim}
4272+
>>> def reverse(data):
4273+
for index in range(len(data)-1, -1, -1):
4274+
yield data[index]
4275+
4276+
>>> for char in reverse('golf'):
4277+
print char
4278+
4279+
f
4280+
l
4281+
o
4282+
g
4283+
\end{verbatim}
4284+
4285+
Anything that can be done with generators can also be done with class based
4286+
iterators as described in the previous section. What makes generators so
4287+
compact is that the \method{__iter__()} and \method{next()} methods are
4288+
created automatically.
4289+
4290+
Another other key feature is that the local variables and execution state
4291+
are automatically saved between calls. This made the function easier to write
4292+
and much more clear than an approach using class variables like
4293+
\code{self.index} and \code{self.data}.
4294+
4295+
In addition to automatic method creation and saving program state, when
4296+
generators terminate, they automatically raise \exception{StopIteration}.
4297+
In combination, these features make it easy to create iterators with no
4298+
more effort than writing a regular function.
4299+
4300+
41874301
\chapter{What Now? \label{whatNow}}
41884302
41894303
Reading this tutorial has probably reinforced your interest in using
@@ -4360,7 +4474,7 @@ \section{Key Bindings \label{keyBindings}}
43604474
# bound to the Esc key by default (you can change it - see readline docs).
43614475
#
43624476
# Store the file in ~/.pystartup, and set an environment variable to point
4363-
# to it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
4477+
# to it: "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
43644478
#
43654479
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
43664480
# full path to your home directory.

0 commit comments

Comments
 (0)