blob: 67fb4c669989d1036ff9376f6b068357bd04f7bf [file] [log] [blame]
Fred Drake03e10312002-03-26 19:17:43 +00001\documentclass{howto}
Fred Drake03e10312002-03-26 19:17:43 +00002
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +00003% $Id$
4
5\title{What's New in Python 2.3}
6\release{0.01}
7\author{A.M. Kuchling}
8\authoraddress{\email{akuchlin@mems-exchange.org}}
Fred Drake03e10312002-03-26 19:17:43 +00009
10\begin{document}
11\maketitle
12\tableofcontents
13
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000014%\section{Introduction \label{intro}}
15
16{\large This article is a draft, and is currently up to date for some
17random version of the CVS tree around March 26 2002. Please send any
18additions, comments or errata to the author.}
19
20This article explains the new features in Python 2.3. The tentative
21release date of Python 2.3 is currently scheduled for August 30 2002.
22
23This article doesn't attempt to provide a complete specification of
24the new features, but instead provides a convenient overview. For
25full details, you should refer to the documentation for Python 2.3,
26such as the
27\citetitle[http://www.python.org/doc/2.3/lib/lib.html]{Python Library
28Reference} and the
29\citetitle[http://www.python.org/doc/2.3/ref/ref.html]{Python
30Reference Manual}. If you want to understand the complete
31implementation and design rationale for a change, refer to the PEP for
32a particular new feature.
Fred Drake03e10312002-03-26 19:17:43 +000033
34
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +000035%======================================================================
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +000036\section{PEP 255: Simple Generators}
37
38In Python 2.2, generators were added as an optional feature, to be
39enabled by a \code{from __future__ import generators} directive. In
402.3 generators no longer need to be specially enabled, and are now
41always present; this means that \keyword{yield} is now always a
42keyword. The rest of this section is a copy of the description of
43generators from the ``What's New in Python 2.2'' document; if you read
44it when 2.2 came out, you can skip the rest of this section.
45
46Generators are a new feature that interacts with the iterators
47introduced in Python 2.2.
48
49You're doubtless familiar with how function calls work in Python or
50C. When you call a function, it gets a private namespace where its local
51variables are created. When the function reaches a \keyword{return}
52statement, the local variables are destroyed and the resulting value
53is returned to the caller. A later call to the same function will get
54a fresh new set of local variables. But, what if the local variables
55weren't thrown away on exiting a function? What if you could later
56resume the function where it left off? This is what generators
57provide; they can be thought of as resumable functions.
58
59Here's the simplest example of a generator function:
60
61\begin{verbatim}
62def generate_ints(N):
63 for i in range(N):
64 yield i
65\end{verbatim}
66
67A new keyword, \keyword{yield}, was introduced for generators. Any
68function containing a \keyword{yield} statement is a generator
69function; this is detected by Python's bytecode compiler which
70compiles the function specially as a result.
71
72When you call a generator function, it doesn't return a single value;
73instead it returns a generator object that supports the iterator
74protocol. On executing the \keyword{yield} statement, the generator
75outputs the value of \code{i}, similar to a \keyword{return}
76statement. The big difference between \keyword{yield} and a
77\keyword{return} statement is that on reaching a \keyword{yield} the
78generator's state of execution is suspended and local variables are
79preserved. On the next call to the generator's \code{.next()} method,
80the function will resume executing immediately after the
81\keyword{yield} statement. (For complicated reasons, the
82\keyword{yield} statement isn't allowed inside the \keyword{try} block
83of a \code{try...finally} statement; read \pep{255} for a full
84explanation of the interaction between \keyword{yield} and
85exceptions.)
86
87Here's a sample usage of the \function{generate_ints} generator:
88
89\begin{verbatim}
90>>> gen = generate_ints(3)
91>>> gen
92<generator object at 0x8117f90>
93>>> gen.next()
940
95>>> gen.next()
961
97>>> gen.next()
982
99>>> gen.next()
100Traceback (most recent call last):
101 File "<stdin>", line 1, in ?
102 File "<stdin>", line 2, in generate_ints
103StopIteration
104\end{verbatim}
105
106You could equally write \code{for i in generate_ints(5)}, or
107\code{a,b,c = generate_ints(3)}.
108
109Inside a generator function, the \keyword{return} statement can only
110be used without a value, and signals the end of the procession of
111values; afterwards the generator cannot return any further values.
112\keyword{return} with a value, such as \code{return 5}, is a syntax
113error inside a generator function. The end of the generator's results
114can also be indicated by raising \exception{StopIteration} manually,
115or by just letting the flow of execution fall off the bottom of the
116function.
117
118You could achieve the effect of generators manually by writing your
119own class and storing all the local variables of the generator as
120instance variables. For example, returning a list of integers could
121be done by setting \code{self.count} to 0, and having the
122\method{next()} method increment \code{self.count} and return it.
123However, for a moderately complicated generator, writing a
124corresponding class would be much messier.
125\file{Lib/test/test_generators.py} contains a number of more
126interesting examples. The simplest one implements an in-order
127traversal of a tree using generators recursively.
128
129\begin{verbatim}
130# A recursive generator that generates Tree leaves in in-order.
131def inorder(t):
132 if t:
133 for x in inorder(t.left):
134 yield x
135 yield t.label
136 for x in inorder(t.right):
137 yield x
138\end{verbatim}
139
140Two other examples in \file{Lib/test/test_generators.py} produce
141solutions for the N-Queens problem (placing $N$ queens on an $NxN$
142chess board so that no queen threatens another) and the Knight's Tour
143(a route that takes a knight to every square of an $NxN$ chessboard
144without visiting any square twice).
145
146The idea of generators comes from other programming languages,
147especially Icon (\url{http://www.cs.arizona.edu/icon/}), where the
148idea of generators is central. In Icon, every
149expression and function call behaves like a generator. One example
150from ``An Overview of the Icon Programming Language'' at
151\url{http://www.cs.arizona.edu/icon/docs/ipd266.htm} gives an idea of
152what this looks like:
153
154\begin{verbatim}
155sentence := "Store it in the neighboring harbor"
156if (i := find("or", sentence)) > 5 then write(i)
157\end{verbatim}
158
159In Icon the \function{find()} function returns the indexes at which the
160substring ``or'' is found: 3, 23, 33. In the \keyword{if} statement,
161\code{i} is first assigned a value of 3, but 3 is less than 5, so the
162comparison fails, and Icon retries it with the second value of 23. 23
163is greater than 5, so the comparison now succeeds, and the code prints
164the value 23 to the screen.
165
166Python doesn't go nearly as far as Icon in adopting generators as a
167central concept. Generators are considered a new part of the core
168Python language, but learning or using them isn't compulsory; if they
169don't solve any problems that you have, feel free to ignore them.
170One novel feature of Python's interface as compared to
171Icon's is that a generator's state is represented as a concrete object
172(the iterator) that can be passed around to other functions or stored
173in a data structure.
174
175\begin{seealso}
176
177\seepep{255}{Simple Generators}{Written by Neil Schemenauer, Tim
178Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer
179and Tim Peters, with other fixes from the Python Labs crew.}
180
181\end{seealso}
182
183
184%======================================================================
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000185\section{PEP 285: The \class{bool} Type}
186
187XXX write this section
188
189\begin{seealso}
190
191\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
192
193\end{seealso}
194
195
196%======================================================================
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000197\section{New and Improved Modules}
198
199arraymodule.c: - add Py_UNICODE arrays
200- support +=, *=
201
202Return enhanced tuples in grpmodule
203
204posixmodule: killpg,
205
206Expat is now included with the Python source
207
208Readline: Add get_history_item, get_current_history_length, and
209redisplay functions.
210
211
212%======================================================================
213\section{Interpreter Changes and Fixes}
214
215XXX bug? Change the version string from "2.2+" to "2.3a0". disutils peels off
216the first 3 characters of this string in several places, so for as long
217as they remain "2.2" it confuses the heck out of attempts to build 2.3
218stuff using distutils.
219
220file object can now be subtyped (did this not work before?)
221
222yield is now always available
223
224This adds the module name and a dot in front of the type name in every
225type object initializer, except for built-in types (and those that
226already had this). Note that it touches lots of Mac modules -- I have
227no way to test these but the changes look right. Apologies if they're
228not. This also touches the weakref docs, which contains a sample type
229object initializer. It also touches the mmap test output, because the
230mmap type's repr is included in that output. It touches object.h to
231put the correct description in a comment.
232
233File objects: Grow the string buffer at a mildly exponential rate for
234the getc version of get_line. This makes test_bufio finish in 1.7
235seconds instead of 57 seconds on my machine (with Py_DEBUG defined).
236
237%======================================================================
238\section{Other Changes and Fixes}
239
240
241% ======================================================================
242\section{C Interface Changes}
243
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000244Patch \#527027: Allow building python as shared library with
245--enable-shared
246
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000247pymalloc is now enabled by default (also mention debug-mode pymalloc)
248
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000249Memory API reworking -- which functions are deprecated?
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000250
251PyObject_DelItemString() added
252
253PyArg_NoArgs macro is now deprecated
254
Andrew M. Kuchling45afd542002-04-02 14:25:25 +0000255===
256Introduce two new flag bits that can be set in a PyMethodDef method
257descriptor, as used for the tp_methods slot of a type. These new flag
258bits are both optional, and mutually exclusive. Most methods will not
259use either. These flags are used to create special method types which
260exist in the same namespace as normal methods without having to use
261tedious construction code to insert the new special method objects in
262the type's tp_dict after PyType_Ready() has been called.
263
264If METH_CLASS is specified, the method will represent a class method
265like that returned by the classmethod() built-in.
266
267If METH_STATIC is specified, the method will represent a static method
268like that returned by the staticmethod() built-in.
269
270These flags may not be used in the PyMethodDef table for modules since
271these special method types are not meaningful in that case; a
272ValueError will be raised if these flags are found in that context.
273===
274
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000275Ports:
276
277OS/2 EMX port
278
279MacOS: Weaklink most toolbox modules, improving backward
280compatibility. Modules will no longer fail to load if a single routine
281is missing on the curent OS version, in stead calling the missing
282routine will raise an exception. Should finally fix 531398. 2.2.1
283candidate. Also blacklisted some constants with definitions that
284were not Python-compatible.
285
286Checked in Sean Reifschneider's RPM spec file and patches. Bugfix candidate.
Fred Drake03e10312002-03-26 19:17:43 +0000287
288
289%======================================================================
290\section{Acknowledgements \label{acks}}
291
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000292The author would like to thank the following people for offering
293suggestions, corrections and assistance with various drafts of this
294article: Fred~L. Drake, Jr.
Fred Drake03e10312002-03-26 19:17:43 +0000295
296\end{document}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000297
298
299