forked from gc3-uzh-ch/python-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart10.tex
341 lines (276 loc) · 8.3 KB
/
part10.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
\documentclass[english,serif,mathserif,xcolor=pdftex,dvipsnames,table]{beamer}
\usetheme[informal]{s3it}
\usepackage{s3it}
\title[OOP 3]{%
Object-oriented programming, III
}
\author[S3IT]{%
S3IT: Services and Support for Science IT, \\
University of Zurich
}
\date{June~23--24, 2014}
\begin{document}
% title frame
\maketitle
\begin{frame}
\frametitle{What we shall see in this part}
Iterators: the Python way of implementing generalized sequences,
e.g., ``infinite lists''.
\+
The \href{http://en.wikipedia.org/wiki/Template_method_pattern}{Template
method}: an object-oriented pattern for code reuse.
\end{frame}
\begin{frame}
\frametitle{Protocols}
A \emph{protocol}, in the Python jargon, is an informal
specification of what methods an object should implement in order to
be used in a certain context.
\+ For example, objects that implement the same methods as the
\texttt{file} object are called ``file-like'' and can be used in
stead of a real file.
\+
(This corresponds to the notion of \emph{interfaces} in other
programming languages, but interfaces are usually a formal language
construct.)
\end{frame}
\begin{frame}[fragile]
\frametitle{The Iterator Protocol}
An \emph{iterator} is an object that can be used in the
\texttt{in}-clause of a \texttt{for \ldots in \ldots} statement.
\+
An object can work as an iterator if and only if it implements a
\texttt{next()} method, that:
\begin{description}
\item[\emph{either}] returns the next value in the iteration,
\item[\emph{or}] use \lstinline|raise StopIteration| to signal the
end of the iteration.
\end{description}
\+
An object can be iterated over with \lstinline|for| if it implements a
\lstinline|__iter__()| method that returns an iterator.
\begin{references}
\url{http://www.python.org/dev/peps/pep-0234/}
\end{references}
\end{frame}
\begin{frame}[fragile]
\frametitle{Examples of Iterators, I}
The \texttt{file} object:
\begin{lstlisting}
>>> fd = open('welcome.py', 'r')
>>> dir(fd)
['__class__', ~\ldots,~ 'name',
'newlines', ~\HL{\tt 'next'}~, 'read',
~\ldots,~ 'writelines', 'xreadlines']
\end{lstlisting}
\+
The \texttt{.next()} method of \texttt{file} objects returns the
lines one by one:
\begin{lstlisting}
>>> fd.next()
'#! /usr/bin/env python\n'
>>> fd.next()
'\n'
>>> fd.next()
'print ("Welcome to Python!")\n'
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Examples of Iterators, II}
You can get an iterator from any sequence with the \texttt{iter()} built-in function:
\begin{lstlisting}
>>> S = "Python"
>>> it = iter(S)
\end{lstlisting}
\+
The \texttt{.next()} method of such iterators returns the
elements of the sequence one by one:
\begin{lstlisting}
>>> it.next()
'P'
>>> it.next()
'y'
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Detour: Regular Expressions}
Regular expressions (RE) are a way to describe text
patterns.
\+
Any character, except those listed below, matches itself.
\+
\begin{tabular}{>{\ttfamily}c>{\small}p{0.85\linewidth}}
. & Matches any character except a newline. \\
\textasciicircum & Matches the start of the string. \\
\$ & Matches the end of the string or just before the newline at the end of the string. \\
* & Matches 0 or more repetitions of the preceding RE. \\
+ & Matches 1 or more repetitions of the preceding RE. \\
? & Matches 0 or 1 of the preceding RE. \\
\end{tabular}
\begin{seealso}
\url{http://regexone.com/} (learn RE), \\
\url{http://regexpal.com/} (try RE live)
\end{seealso}
\end{frame}
\begin{frame}
\frametitle{Regular Expression objects}
The \texttt{re} module in the standard library provides
\emph{regular expression searching}, allowing you to match a string
against a pattern.
\+
\begin{describe}{re.search(pattern, string)}
If \texttt{pattern} is matched anywhere in \texttt{string}, return
a \emph{match object}. Otherwise, return \texttt{None}.
\end{describe}
\+
\begin{describe}{\emph{match}.group(0)}
The entire string matched by \texttt{pattern} in a search operation.
\end{describe}
\+
\begin{references}
\url{http://docs.python.org/library/re.html}
\end{references}
\end{frame}
\begin{frame}[fragile]
\frametitle{A user-defined iterator}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
import re
class Grep(object):
def __init__(self, filename, pattern):
self._file = open(filename, 'r')
self._pattern = pattern
def __iter__(self):
return self
def next(self):
line = self._file.next()
while not re.search(self._pattern, line):
line = self._file.next()
return line
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
Iterate over lines of a file matching a pattern.
\end{column}
\end{columns}
\+
{\scriptsize Source code available at:
\url{https://raw.github.com/gc3-uzh-ch/python-course/master/evens.py}}
\end{frame}
\begin{frame}[fragile]
\frametitle{Example using \texttt{Grep}, I}
\begin{lstlisting}[showstringspaces=false]
>>> from grep import Grep
>>> g = Grep('grep.py', 'def')
>>> g.next()
' def __init__(self, filename, pattern):\n'
>>> g.next()
' def __iter__(self):\n'
>>> g.next()
' def next(self):\n'
>>> g.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "grep.py", line 17, in next
line = self._file.next()
StopIteration
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{Example using \texttt{Grep}, II}
\begin{lstlisting}
>>> from grep import Grep
>>> g = Grep('grep.py', 'def')
>>> for line in g:
... print line.strip()
...
\end{lstlisting}
\vspace{-1.5em}
\begin{verbatim}
def __init__(self, filename, pattern):
def __iter__(self):
def next(self):
\end{verbatim}
\end{frame}
\begin{frame}[fragile]
\begin{exercise}
Define a \texttt{GrepOnlyMatching} class, similar to \texttt{Grep}
except that its \texttt{next()} method returns only the part of
the line that matched the \texttt{pattern} expression.
\end{exercise}
\+
\begin{exercise}
Define a \texttt{GrepExactly} class, similar to \texttt{Grep}
except that \texttt{pattern} is now a fixed string, and the
\texttt{next()} method returns lines that \emph{contain} it.
\end{exercise}
\end{frame}
\begin{frame}[fragile]
\frametitle{The ``Template method'' pattern}
\begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
class Grep(object):
def __init__(self, filename, pattern):
self._file = open(filename, 'r')
self._pattern = pattern
def match(self, line):
return re.search(self._pattern, line)
def result(self, match, line):
return line
def next(self):
line = self._file.next()
match = self.match(line)
while not match:
line = self._file.next()
match = self.match(line)
return self.result(match, line)
\end{lstlisting}
\end{frame}
\begin{frame}[fragile]
\frametitle{The ``Template method'' pattern, I}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class Grep(object):
# parts omitted
def next(self):
line = self._file.next()
match = ~\HL{self.match}~(line)
while not match:
line = self._file.next()
match = ~\HL{self.match}~(line)
return ~\HL{self.result}~(match, line)
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
These calls delegate the actual matching and
extraction of the result from the line to instance methods.
\end{column}
\end{columns}
\end{frame}
\begin{frame}[fragile]
\frametitle{The ``Template method'' pattern, II}
\begin{columns}[t]
\begin{column}{0.5\textwidth}
\begin{lstlisting}
class GrepOnlyMatching(Grep):
~\HL{\textbf{def} result}~(self, match, line):
return match.group(0)
class GrepExactly(Grep):
~\HL{\textbf{def} match}~(self, line):
return (self._pattern in line)
\end{lstlisting}
\end{column}
\begin{column}{0.5\textwidth}
\raggedleft
So we need only re-define those methods in derived
classes to implement a variant behavior.
\end{column}
\end{columns}
\end{frame}
\end{document}
%%% Local Variables:
%%% mode: latex
%%% TeX-master: t
%%% End: