blob: 0b16acd99cab77e0f302c49e245e743527ef3eb9 [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. Kuchlingf3676512002-04-15 02:27:55 +0000185\section{PEP 278: Universal Newline Support}
186
187XXX write this section
188
189%Highlights: import and friends will understand any of \r, \n and \r\n
190%as end of line. Python file input will do the same if you use mode 'U'.
191%Everything can be disabled by configuring with --without-universal-newlines.
192
193
194\begin{seealso}
195
196\seepep{278}{Universal Newline Support}{Written
197and implemented by Jack Jansen.}
198
199\end{seealso}
200
201%======================================================================
Andrew M. Kuchling3a52ff62002-04-03 22:44:47 +0000202\section{PEP 285: The \class{bool} Type}
203
204XXX write this section
205
206\begin{seealso}
207
208\seepep{285}{Adding a bool type}{Written and implemented by GvR.}
209
210\end{seealso}
211
212
213%======================================================================
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000214\section{New and Improved Modules}
215
216arraymodule.c: - add Py_UNICODE arrays
217- support +=, *=
218
219Return enhanced tuples in grpmodule
220
Neal Norwitzb384c722002-04-15 12:46:11 +0000221posixmodule: killpg, mknod
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000222
223Expat is now included with the Python source
224
225Readline: Add get_history_item, get_current_history_length, and
226redisplay functions.
227
Andrew M. Kuchlingf3676512002-04-15 02:27:55 +0000228Add optional arg to string methods strip(), lstrip(), rstrip().
229The optional arg specifies characters to delete.
230
Neal Norwitzb384c722002-04-15 12:46:11 +0000231Add dict method pop().
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000232
233%======================================================================
234\section{Interpreter Changes and Fixes}
235
236XXX bug? Change the version string from "2.2+" to "2.3a0". disutils peels off
237the first 3 characters of this string in several places, so for as long
238as they remain "2.2" it confuses the heck out of attempts to build 2.3
239stuff using distutils.
240
241file object can now be subtyped (did this not work before?)
242
243yield is now always available
244
245This adds the module name and a dot in front of the type name in every
246type object initializer, except for built-in types (and those that
247already had this). Note that it touches lots of Mac modules -- I have
248no way to test these but the changes look right. Apologies if they're
249not. This also touches the weakref docs, which contains a sample type
250object initializer. It also touches the mmap test output, because the
251mmap type's repr is included in that output. It touches object.h to
252put the correct description in a comment.
253
254File objects: Grow the string buffer at a mildly exponential rate for
255the getc version of get_line. This makes test_bufio finish in 1.7
256seconds instead of 57 seconds on my machine (with Py_DEBUG defined).
257
258%======================================================================
259\section{Other Changes and Fixes}
260
261
262% ======================================================================
263\section{C Interface Changes}
264
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000265Patch \#527027: Allow building python as shared library with
266--enable-shared
267
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000268pymalloc is now enabled by default (also mention debug-mode pymalloc)
269
Andrew M. Kuchlingf4dd65d2002-04-01 19:28:09 +0000270Memory API reworking -- which functions are deprecated?
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000271
272PyObject_DelItemString() added
273
274PyArg_NoArgs macro is now deprecated
275
Andrew M. Kuchling45afd542002-04-02 14:25:25 +0000276===
277Introduce two new flag bits that can be set in a PyMethodDef method
278descriptor, as used for the tp_methods slot of a type. These new flag
279bits are both optional, and mutually exclusive. Most methods will not
280use either. These flags are used to create special method types which
281exist in the same namespace as normal methods without having to use
282tedious construction code to insert the new special method objects in
283the type's tp_dict after PyType_Ready() has been called.
284
285If METH_CLASS is specified, the method will represent a class method
286like that returned by the classmethod() built-in.
287
288If METH_STATIC is specified, the method will represent a static method
289like that returned by the staticmethod() built-in.
290
291These flags may not be used in the PyMethodDef table for modules since
292these special method types are not meaningful in that case; a
293ValueError will be raised if these flags are found in that context.
294===
295
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000296Ports:
297
298OS/2 EMX port
299
300MacOS: Weaklink most toolbox modules, improving backward
301compatibility. Modules will no longer fail to load if a single routine
302is missing on the curent OS version, in stead calling the missing
303routine will raise an exception. Should finally fix 531398. 2.2.1
304candidate. Also blacklisted some constants with definitions that
305were not Python-compatible.
306
307Checked in Sean Reifschneider's RPM spec file and patches. Bugfix candidate.
Fred Drake03e10312002-03-26 19:17:43 +0000308
309
310%======================================================================
311\section{Acknowledgements \label{acks}}
312
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000313The author would like to thank the following people for offering
314suggestions, corrections and assistance with various drafts of this
315article: Fred~L. Drake, Jr.
Fred Drake03e10312002-03-26 19:17:43 +0000316
317\end{document}
Andrew M. Kuchling03594bb2002-03-27 02:29:48 +0000318
319
320