PageRenderTime 63ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/whatsnew/2.0.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 1206 lines | 942 code | 264 blank | 0 comment | 0 complexity | 0e89b8646c1bd2e43554abd1dbd205ce MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. ****************************
  2. What's New in Python 2.0
  3. ****************************
  4. :Author: A.M. Kuchling and Moshe Zadka
  5. .. |release| replace:: 1.02
  6. .. $Id: whatsnew20.tex 50964 2006-07-30 03:03:43Z fred.drake $
  7. Introduction
  8. ============
  9. A new release of Python, version 2.0, was released on October 16, 2000. This
  10. article covers the exciting new features in 2.0, highlights some other useful
  11. changes, and points out a few incompatible changes that may require rewriting
  12. code.
  13. Python's development never completely stops between releases, and a steady flow
  14. of bug fixes and improvements are always being submitted. A host of minor fixes,
  15. a few optimizations, additional docstrings, and better error messages went into
  16. 2.0; to list them all would be impossible, but they're certainly significant.
  17. Consult the publicly-available CVS logs if you want to see the full list. This
  18. progress is due to the five developers working for PythonLabs are now getting
  19. paid to spend their days fixing bugs, and also due to the improved communication
  20. resulting from moving to SourceForge.
  21. .. ======================================================================
  22. What About Python 1.6?
  23. ======================
  24. Python 1.6 can be thought of as the Contractual Obligations Python release.
  25. After the core development team left CNRI in May 2000, CNRI requested that a 1.6
  26. release be created, containing all the work on Python that had been performed at
  27. CNRI. Python 1.6 therefore represents the state of the CVS tree as of May 2000,
  28. with the most significant new feature being Unicode support. Development
  29. continued after May, of course, so the 1.6 tree received a few fixes to ensure
  30. that it's forward-compatible with Python 2.0. 1.6 is therefore part of Python's
  31. evolution, and not a side branch.
  32. So, should you take much interest in Python 1.6? Probably not. The 1.6final
  33. and 2.0beta1 releases were made on the same day (September 5, 2000), the plan
  34. being to finalize Python 2.0 within a month or so. If you have applications to
  35. maintain, there seems little point in breaking things by moving to 1.6, fixing
  36. them, and then having another round of breakage within a month by moving to 2.0;
  37. you're better off just going straight to 2.0. Most of the really interesting
  38. features described in this document are only in 2.0, because a lot of work was
  39. done between May and September.
  40. .. ======================================================================
  41. New Development Process
  42. =======================
  43. The most important change in Python 2.0 may not be to the code at all, but to
  44. how Python is developed: in May 2000 the Python developers began using the tools
  45. made available by SourceForge for storing source code, tracking bug reports,
  46. and managing the queue of patch submissions. To report bugs or submit patches
  47. for Python 2.0, use the bug tracking and patch manager tools available from
  48. Python's project page, located at http://sourceforge.net/projects/python/.
  49. The most important of the services now hosted at SourceForge is the Python CVS
  50. tree, the version-controlled repository containing the source code for Python.
  51. Previously, there were roughly 7 or so people who had write access to the CVS
  52. tree, and all patches had to be inspected and checked in by one of the people on
  53. this short list. Obviously, this wasn't very scalable. By moving the CVS tree
  54. to SourceForge, it became possible to grant write access to more people; as of
  55. September 2000 there were 27 people able to check in changes, a fourfold
  56. increase. This makes possible large-scale changes that wouldn't be attempted if
  57. they'd have to be filtered through the small group of core developers. For
  58. example, one day Peter Schneider-Kamp took it into his head to drop K&R C
  59. compatibility and convert the C source for Python to ANSI C. After getting
  60. approval on the python-dev mailing list, he launched into a flurry of checkins
  61. that lasted about a week, other developers joined in to help, and the job was
  62. done. If there were only 5 people with write access, probably that task would
  63. have been viewed as "nice, but not worth the time and effort needed" and it
  64. would never have gotten done.
  65. The shift to using SourceForge's services has resulted in a remarkable increase
  66. in the speed of development. Patches now get submitted, commented on, revised
  67. by people other than the original submitter, and bounced back and forth between
  68. people until the patch is deemed worth checking in. Bugs are tracked in one
  69. central location and can be assigned to a specific person for fixing, and we can
  70. count the number of open bugs to measure progress. This didn't come without a
  71. cost: developers now have more e-mail to deal with, more mailing lists to
  72. follow, and special tools had to be written for the new environment. For
  73. example, SourceForge sends default patch and bug notification e-mail messages
  74. that are completely unhelpful, so Ka-Ping Yee wrote an HTML screen-scraper that
  75. sends more useful messages.
  76. The ease of adding code caused a few initial growing pains, such as code was
  77. checked in before it was ready or without getting clear agreement from the
  78. developer group. The approval process that has emerged is somewhat similar to
  79. that used by the Apache group. Developers can vote +1, +0, -0, or -1 on a patch;
  80. +1 and -1 denote acceptance or rejection, while +0 and -0 mean the developer is
  81. mostly indifferent to the change, though with a slight positive or negative
  82. slant. The most significant change from the Apache model is that the voting is
  83. essentially advisory, letting Guido van Rossum, who has Benevolent Dictator For
  84. Life status, know what the general opinion is. He can still ignore the result of
  85. a vote, and approve or reject a change even if the community disagrees with him.
  86. Producing an actual patch is the last step in adding a new feature, and is
  87. usually easy compared to the earlier task of coming up with a good design.
  88. Discussions of new features can often explode into lengthy mailing list threads,
  89. making the discussion hard to follow, and no one can read every posting to
  90. python-dev. Therefore, a relatively formal process has been set up to write
  91. Python Enhancement Proposals (PEPs), modelled on the Internet RFC process. PEPs
  92. are draft documents that describe a proposed new feature, and are continually
  93. revised until the community reaches a consensus, either accepting or rejecting
  94. the proposal. Quoting from the introduction to PEP 1, "PEP Purpose and
  95. Guidelines":
  96. .. epigraph::
  97. PEP stands for Python Enhancement Proposal. A PEP is a design document
  98. providing information to the Python community, or describing a new feature for
  99. Python. The PEP should provide a concise technical specification of the feature
  100. and a rationale for the feature.
  101. We intend PEPs to be the primary mechanisms for proposing new features, for
  102. collecting community input on an issue, and for documenting the design decisions
  103. that have gone into Python. The PEP author is responsible for building
  104. consensus within the community and documenting dissenting opinions.
  105. Read the rest of PEP 1 for the details of the PEP editorial process, style, and
  106. format. PEPs are kept in the Python CVS tree on SourceForge, though they're not
  107. part of the Python 2.0 distribution, and are also available in HTML form from
  108. http://www.python.org/peps/. As of September 2000, there are 25 PEPS, ranging
  109. from PEP 201, "Lockstep Iteration", to PEP 225, "Elementwise/Objectwise
  110. Operators".
  111. .. ======================================================================
  112. Unicode
  113. =======
  114. The largest new feature in Python 2.0 is a new fundamental data type: Unicode
  115. strings. Unicode uses 16-bit numbers to represent characters instead of the
  116. 8-bit number used by ASCII, meaning that 65,536 distinct characters can be
  117. supported.
  118. The final interface for Unicode support was arrived at through countless often-
  119. stormy discussions on the python-dev mailing list, and mostly implemented by
  120. Marc-AndrĂŠ Lemburg, based on a Unicode string type implementation by Fredrik
  121. Lundh. A detailed explanation of the interface was written up as :pep:`100`,
  122. "Python Unicode Integration". This article will simply cover the most
  123. significant points about the Unicode interfaces.
  124. In Python source code, Unicode strings are written as ``u"string"``. Arbitrary
  125. Unicode characters can be written using a new escape sequence, ``\uHHHH``, where
  126. *HHHH* is a 4-digit hexadecimal number from 0000 to FFFF. The existing
  127. ``\xHHHH`` escape sequence can also be used, and octal escapes can be used for
  128. characters up to U+01FF, which is represented by ``\777``.
  129. Unicode strings, just like regular strings, are an immutable sequence type.
  130. They can be indexed and sliced, but not modified in place. Unicode strings have
  131. an ``encode( [encoding] )`` method that returns an 8-bit string in the desired
  132. encoding. Encodings are named by strings, such as ``'ascii'``, ``'utf-8'``,
  133. ``'iso-8859-1'``, or whatever. A codec API is defined for implementing and
  134. registering new encodings that are then available throughout a Python program.
  135. If an encoding isn't specified, the default encoding is usually 7-bit ASCII,
  136. though it can be changed for your Python installation by calling the
  137. :func:`sys.setdefaultencoding(encoding)` function in a customised version of
  138. :file:`site.py`.
  139. Combining 8-bit and Unicode strings always coerces to Unicode, using the default
  140. ASCII encoding; the result of ``'a' + u'bc'`` is ``u'abc'``.
  141. New built-in functions have been added, and existing built-ins modified to
  142. support Unicode:
  143. * ``unichr(ch)`` returns a Unicode string 1 character long, containing the
  144. character *ch*.
  145. * ``ord(u)``, where *u* is a 1-character regular or Unicode string, returns the
  146. number of the character as an integer.
  147. * ``unicode(string [, encoding] [, errors] )`` creates a Unicode string
  148. from an 8-bit string. ``encoding`` is a string naming the encoding to use. The
  149. ``errors`` parameter specifies the treatment of characters that are invalid for
  150. the current encoding; passing ``'strict'`` as the value causes an exception to
  151. be raised on any encoding error, while ``'ignore'`` causes errors to be silently
  152. ignored and ``'replace'`` uses U+FFFD, the official replacement character, in
  153. case of any problems.
  154. * The :keyword:`exec` statement, and various built-ins such as ``eval()``,
  155. ``getattr()``, and ``setattr()`` will also accept Unicode strings as well as
  156. regular strings. (It's possible that the process of fixing this missed some
  157. built-ins; if you find a built-in function that accepts strings but doesn't
  158. accept Unicode strings at all, please report it as a bug.)
  159. A new module, :mod:`unicodedata`, provides an interface to Unicode character
  160. properties. For example, ``unicodedata.category(u'A')`` returns the 2-character
  161. string 'Lu', the 'L' denoting it's a letter, and 'u' meaning that it's
  162. uppercase. ``unicodedata.bidirectional(u'\u0660')`` returns 'AN', meaning that
  163. U+0660 is an Arabic number.
  164. The :mod:`codecs` module contains functions to look up existing encodings and
  165. register new ones. Unless you want to implement a new encoding, you'll most
  166. often use the :func:`codecs.lookup(encoding)` function, which returns a
  167. 4-element tuple: ``(encode_func, decode_func, stream_reader, stream_writer)``.
  168. * *encode_func* is a function that takes a Unicode string, and returns a 2-tuple
  169. ``(string, length)``. *string* is an 8-bit string containing a portion (perhaps
  170. all) of the Unicode string converted into the given encoding, and *length* tells
  171. you how much of the Unicode string was converted.
  172. * *decode_func* is the opposite of *encode_func*, taking an 8-bit string and
  173. returning a 2-tuple ``(ustring, length)``, consisting of the resulting Unicode
  174. string *ustring* and the integer *length* telling how much of the 8-bit string
  175. was consumed.
  176. * *stream_reader* is a class that supports decoding input from a stream.
  177. *stream_reader(file_obj)* returns an object that supports the :meth:`read`,
  178. :meth:`readline`, and :meth:`readlines` methods. These methods will all
  179. translate from the given encoding and return Unicode strings.
  180. * *stream_writer*, similarly, is a class that supports encoding output to a
  181. stream. *stream_writer(file_obj)* returns an object that supports the
  182. :meth:`write` and :meth:`writelines` methods. These methods expect Unicode
  183. strings, translating them to the given encoding on output.
  184. For example, the following code writes a Unicode string into a file, encoding
  185. it as UTF-8::
  186. import codecs
  187. unistr = u'\u0660\u2000ab ...'
  188. (UTF8_encode, UTF8_decode,
  189. UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')
  190. output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
  191. output.write( unistr )
  192. output.close()
  193. The following code would then read UTF-8 input from the file::
  194. input = UTF8_streamreader( open( '/tmp/output', 'rb') )
  195. print repr(input.read())
  196. input.close()
  197. Unicode-aware regular expressions are available through the :mod:`re` module,
  198. which has a new underlying implementation called SRE written by Fredrik Lundh of
  199. Secret Labs AB.
  200. A ``-U`` command line option was added which causes the Python compiler to
  201. interpret all string literals as Unicode string literals. This is intended to be
  202. used in testing and future-proofing your Python code, since some future version
  203. of Python may drop support for 8-bit strings and provide only Unicode strings.
  204. .. ======================================================================
  205. List Comprehensions
  206. ===================
  207. Lists are a workhorse data type in Python, and many programs manipulate a list
  208. at some point. Two common operations on lists are to loop over them, and either
  209. pick out the elements that meet a certain criterion, or apply some function to
  210. each element. For example, given a list of strings, you might want to pull out
  211. all the strings containing a given substring, or strip off trailing whitespace
  212. from each line.
  213. The existing :func:`map` and :func:`filter` functions can be used for this
  214. purpose, but they require a function as one of their arguments. This is fine if
  215. there's an existing built-in function that can be passed directly, but if there
  216. isn't, you have to create a little function to do the required work, and
  217. Python's scoping rules make the result ugly if the little function needs
  218. additional information. Take the first example in the previous paragraph,
  219. finding all the strings in the list containing a given substring. You could
  220. write the following to do it::
  221. # Given the list L, make a list of all strings
  222. # containing the substring S.
  223. sublist = filter( lambda s, substring=S:
  224. string.find(s, substring) != -1,
  225. L)
  226. Because of Python's scoping rules, a default argument is used so that the
  227. anonymous function created by the :keyword:`lambda` statement knows what
  228. substring is being searched for. List comprehensions make this cleaner::
  229. sublist = [ s for s in L if string.find(s, S) != -1 ]
  230. List comprehensions have the form::
  231. [ expression for expr in sequence1
  232. for expr2 in sequence2 ...
  233. for exprN in sequenceN
  234. if condition ]
  235. The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
  236. iterated over. The sequences do not have to be the same length, because they
  237. are *not* iterated over in parallel, but from left to right; this is explained
  238. more clearly in the following paragraphs. The elements of the generated list
  239. will be the successive values of *expression*. The final :keyword:`if` clause
  240. is optional; if present, *expression* is only evaluated and added to the result
  241. if *condition* is true.
  242. To make the semantics very clear, a list comprehension is equivalent to the
  243. following Python code::
  244. for expr1 in sequence1:
  245. for expr2 in sequence2:
  246. ...
  247. for exprN in sequenceN:
  248. if (condition):
  249. # Append the value of
  250. # the expression to the
  251. # resulting list.
  252. This means that when there are multiple :keyword:`for`...\ :keyword:`in`
  253. clauses, the resulting list will be equal to the product of the lengths of all
  254. the sequences. If you have two lists of length 3, the output list is 9 elements
  255. long::
  256. seq1 = 'abc'
  257. seq2 = (1,2,3)
  258. >>> [ (x,y) for x in seq1 for y in seq2]
  259. [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
  260. ('c', 2), ('c', 3)]
  261. To avoid introducing an ambiguity into Python's grammar, if *expression* is
  262. creating a tuple, it must be surrounded with parentheses. The first list
  263. comprehension below is a syntax error, while the second one is correct::
  264. # Syntax error
  265. [ x,y for x in seq1 for y in seq2]
  266. # Correct
  267. [ (x,y) for x in seq1 for y in seq2]
  268. The idea of list comprehensions originally comes from the functional programming
  269. language Haskell (http://www.haskell.org). Greg Ewing argued most effectively
  270. for adding them to Python and wrote the initial list comprehension patch, which
  271. was then discussed for a seemingly endless time on the python-dev mailing list
  272. and kept up-to-date by Skip Montanaro.
  273. .. ======================================================================
  274. Augmented Assignment
  275. ====================
  276. Augmented assignment operators, another long-requested feature, have been added
  277. to Python 2.0. Augmented assignment operators include ``+=``, ``-=``, ``*=``,
  278. and so forth. For example, the statement ``a += 2`` increments the value of the
  279. variable ``a`` by 2, equivalent to the slightly lengthier ``a = a + 2``.
  280. The full list of supported assignment operators is ``+=``, ``-=``, ``*=``,
  281. ``/=``, ``%=``, ``**=``, ``&=``, ``|=``, ``^=``, ``>>=``, and ``<<=``. Python
  282. classes can override the augmented assignment operators by defining methods
  283. named :meth:`__iadd__`, :meth:`__isub__`, etc. For example, the following
  284. :class:`Number` class stores a number and supports using += to create a new
  285. instance with an incremented value.
  286. .. The empty groups below prevent conversion to guillemets.
  287. ::
  288. class Number:
  289. def __init__(self, value):
  290. self.value = value
  291. def __iadd__(self, increment):
  292. return Number( self.value + increment)
  293. n = Number(5)
  294. n += 3
  295. print n.value
  296. The :meth:`__iadd__` special method is called with the value of the increment,
  297. and should return a new instance with an appropriately modified value; this
  298. return value is bound as the new value of the variable on the left-hand side.
  299. Augmented assignment operators were first introduced in the C programming
  300. language, and most C-derived languages, such as :program:`awk`, C++, Java, Perl,
  301. and PHP also support them. The augmented assignment patch was implemented by
  302. Thomas Wouters.
  303. .. ======================================================================
  304. String Methods
  305. ==============
  306. Until now string-manipulation functionality was in the :mod:`string` module,
  307. which was usually a front-end for the :mod:`strop` module written in C. The
  308. addition of Unicode posed a difficulty for the :mod:`strop` module, because the
  309. functions would all need to be rewritten in order to accept either 8-bit or
  310. Unicode strings. For functions such as :func:`string.replace`, which takes 3
  311. string arguments, that means eight possible permutations, and correspondingly
  312. complicated code.
  313. Instead, Python 2.0 pushes the problem onto the string type, making string
  314. manipulation functionality available through methods on both 8-bit strings and
  315. Unicode strings. ::
  316. >>> 'andrew'.capitalize()
  317. 'Andrew'
  318. >>> 'hostname'.replace('os', 'linux')
  319. 'hlinuxtname'
  320. >>> 'moshe'.find('sh')
  321. 2
  322. One thing that hasn't changed, a noteworthy April Fools' joke notwithstanding,
  323. is that Python strings are immutable. Thus, the string methods return new
  324. strings, and do not modify the string on which they operate.
  325. The old :mod:`string` module is still around for backwards compatibility, but it
  326. mostly acts as a front-end to the new string methods.
  327. Two methods which have no parallel in pre-2.0 versions, although they did exist
  328. in JPython for quite some time, are :meth:`startswith` and :meth:`endswith`.
  329. ``s.startswith(t)`` is equivalent to ``s[:len(t)] == t``, while
  330. ``s.endswith(t)`` is equivalent to ``s[-len(t):] == t``.
  331. One other method which deserves special mention is :meth:`join`. The
  332. :meth:`join` method of a string receives one parameter, a sequence of strings,
  333. and is equivalent to the :func:`string.join` function from the old :mod:`string`
  334. module, with the arguments reversed. In other words, ``s.join(seq)`` is
  335. equivalent to the old ``string.join(seq, s)``.
  336. .. ======================================================================
  337. Garbage Collection of Cycles
  338. ============================
  339. The C implementation of Python uses reference counting to implement garbage
  340. collection. Every Python object maintains a count of the number of references
  341. pointing to itself, and adjusts the count as references are created or
  342. destroyed. Once the reference count reaches zero, the object is no longer
  343. accessible, since you need to have a reference to an object to access it, and if
  344. the count is zero, no references exist any longer.
  345. Reference counting has some pleasant properties: it's easy to understand and
  346. implement, and the resulting implementation is portable, fairly fast, and reacts
  347. well with other libraries that implement their own memory handling schemes. The
  348. major problem with reference counting is that it sometimes doesn't realise that
  349. objects are no longer accessible, resulting in a memory leak. This happens when
  350. there are cycles of references.
  351. Consider the simplest possible cycle, a class instance which has a reference to
  352. itself::
  353. instance = SomeClass()
  354. instance.myself = instance
  355. After the above two lines of code have been executed, the reference count of
  356. ``instance`` is 2; one reference is from the variable named ``'instance'``, and
  357. the other is from the ``myself`` attribute of the instance.
  358. If the next line of code is ``del instance``, what happens? The reference count
  359. of ``instance`` is decreased by 1, so it has a reference count of 1; the
  360. reference in the ``myself`` attribute still exists. Yet the instance is no
  361. longer accessible through Python code, and it could be deleted. Several objects
  362. can participate in a cycle if they have references to each other, causing all of
  363. the objects to be leaked.
  364. Python 2.0 fixes this problem by periodically executing a cycle detection
  365. algorithm which looks for inaccessible cycles and deletes the objects involved.
  366. A new :mod:`gc` module provides functions to perform a garbage collection,
  367. obtain debugging statistics, and tuning the collector's parameters.
  368. Running the cycle detection algorithm takes some time, and therefore will result
  369. in some additional overhead. It is hoped that after we've gotten experience
  370. with the cycle collection from using 2.0, Python 2.1 will be able to minimize
  371. the overhead with careful tuning. It's not yet obvious how much performance is
  372. lost, because benchmarking this is tricky and depends crucially on how often the
  373. program creates and destroys objects. The detection of cycles can be disabled
  374. when Python is compiled, if you can't afford even a tiny speed penalty or
  375. suspect that the cycle collection is buggy, by specifying the
  376. :option:`--without-cycle-gc` switch when running the :program:`configure`
  377. script.
  378. Several people tackled this problem and contributed to a solution. An early
  379. implementation of the cycle detection approach was written by Toby Kelsey. The
  380. current algorithm was suggested by Eric Tiedemann during a visit to CNRI, and
  381. Guido van Rossum and Neil Schemenauer wrote two different implementations, which
  382. were later integrated by Neil. Lots of other people offered suggestions along
  383. the way; the March 2000 archives of the python-dev mailing list contain most of
  384. the relevant discussion, especially in the threads titled "Reference cycle
  385. collection for Python" and "Finalization again".
  386. .. ======================================================================
  387. Other Core Changes
  388. ==================
  389. Various minor changes have been made to Python's syntax and built-in functions.
  390. None of the changes are very far-reaching, but they're handy conveniences.
  391. Minor Language Changes
  392. ----------------------
  393. A new syntax makes it more convenient to call a given function with a tuple of
  394. arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier,
  395. you'd use the :func:`apply` built-in function: ``apply(f, args, kw)`` calls the
  396. function :func:`f` with the argument tuple *args* and the keyword arguments in
  397. the dictionary *kw*. :func:`apply` is the same in 2.0, but thanks to a patch
  398. from Greg Ewing, ``f(*args, **kw)`` as a shorter and clearer way to achieve the
  399. same effect. This syntax is symmetrical with the syntax for defining
  400. functions::
  401. def f(*args, **kw):
  402. # args is a tuple of positional args,
  403. # kw is a dictionary of keyword args
  404. ...
  405. The :keyword:`print` statement can now have its output directed to a file-like
  406. object by following the :keyword:`print` with ``>> file``, similar to the
  407. redirection operator in Unix shells. Previously you'd either have to use the
  408. :meth:`write` method of the file-like object, which lacks the convenience and
  409. simplicity of :keyword:`print`, or you could assign a new value to
  410. ``sys.stdout`` and then restore the old value. For sending output to standard
  411. error, it's much easier to write this::
  412. print >> sys.stderr, "Warning: action field not supplied"
  413. Modules can now be renamed on importing them, using the syntax ``import module
  414. as name`` or ``from module import name as othername``. The patch was submitted
  415. by Thomas Wouters.
  416. A new format style is available when using the ``%`` operator; '%r' will insert
  417. the :func:`repr` of its argument. This was also added from symmetry
  418. considerations, this time for symmetry with the existing '%s' format style,
  419. which inserts the :func:`str` of its argument. For example, ``'%r %s' % ('abc',
  420. 'abc')`` returns a string containing ``'abc' abc``.
  421. Previously there was no way to implement a class that overrode Python's built-in
  422. :keyword:`in` operator and implemented a custom version. ``obj in seq`` returns
  423. true if *obj* is present in the sequence *seq*; Python computes this by simply
  424. trying every index of the sequence until either *obj* is found or an
  425. :exc:`IndexError` is encountered. Moshe Zadka contributed a patch which adds a
  426. :meth:`__contains__` magic method for providing a custom implementation for
  427. :keyword:`in`. Additionally, new built-in objects written in C can define what
  428. :keyword:`in` means for them via a new slot in the sequence protocol.
  429. Earlier versions of Python used a recursive algorithm for deleting objects.
  430. Deeply nested data structures could cause the interpreter to fill up the C stack
  431. and crash; Christian Tismer rewrote the deletion logic to fix this problem. On
  432. a related note, comparing recursive objects recursed infinitely and crashed;
  433. Jeremy Hylton rewrote the code to no longer crash, producing a useful result
  434. instead. For example, after this code::
  435. a = []
  436. b = []
  437. a.append(a)
  438. b.append(b)
  439. The comparison ``a==b`` returns true, because the two recursive data structures
  440. are isomorphic. See the thread "trashcan and PR#7" in the April 2000 archives of
  441. the python-dev mailing list for the discussion leading up to this
  442. implementation, and some useful relevant links. Note that comparisons can now
  443. also raise exceptions. In earlier versions of Python, a comparison operation
  444. such as ``cmp(a,b)`` would always produce an answer, even if a user-defined
  445. :meth:`__cmp__` method encountered an error, since the resulting exception would
  446. simply be silently swallowed.
  447. .. Starting URL:
  448. .. http://www.python.org/pipermail/python-dev/2000-April/004834.html
  449. Work has been done on porting Python to 64-bit Windows on the Itanium processor,
  450. mostly by Trent Mick of ActiveState. (Confusingly, ``sys.platform`` is still
  451. ``'win32'`` on Win64 because it seems that for ease of porting, MS Visual C++
  452. treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the
  453. Python CE page at http://starship.python.net/crew/mhammond/ce/ for more
  454. information.
  455. Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0.
  456. Dynamic loading works, if you specify "configure --with-dyld --with-suffix=.x".
  457. Consult the README in the Python source distribution for more instructions.
  458. An attempt has been made to alleviate one of Python's warts, the often-confusing
  459. :exc:`NameError` exception when code refers to a local variable before the
  460. variable has been assigned a value. For example, the following code raises an
  461. exception on the :keyword:`print` statement in both 1.5.2 and 2.0; in 1.5.2 a
  462. :exc:`NameError` exception is raised, while 2.0 raises a new
  463. :exc:`UnboundLocalError` exception. :exc:`UnboundLocalError` is a subclass of
  464. :exc:`NameError`, so any existing code that expects :exc:`NameError` to be
  465. raised should still work. ::
  466. def f():
  467. print "i=",i
  468. i = i + 1
  469. f()
  470. Two new exceptions, :exc:`TabError` and :exc:`IndentationError`, have been
  471. introduced. They're both subclasses of :exc:`SyntaxError`, and are raised when
  472. Python code is found to be improperly indented.
  473. Changes to Built-in Functions
  474. -----------------------------
  475. A new built-in, :func:`zip(seq1, seq2, ...)`, has been added. :func:`zip`
  476. returns a list of tuples where each tuple contains the i-th element from each of
  477. the argument sequences. The difference between :func:`zip` and ``map(None,
  478. seq1, seq2)`` is that :func:`map` pads the sequences with ``None`` if the
  479. sequences aren't all of the same length, while :func:`zip` truncates the
  480. returned list to the length of the shortest argument sequence.
  481. The :func:`int` and :func:`long` functions now accept an optional "base"
  482. parameter when the first argument is a string. ``int('123', 10)`` returns 123,
  483. while ``int('123', 16)`` returns 291. ``int(123, 16)`` raises a
  484. :exc:`TypeError` exception with the message "can't convert non-string with
  485. explicit base".
  486. A new variable holding more detailed version information has been added to the
  487. :mod:`sys` module. ``sys.version_info`` is a tuple ``(major, minor, micro,
  488. level, serial)`` For example, in a hypothetical 2.0.1beta1, ``sys.version_info``
  489. would be ``(2, 0, 1, 'beta', 1)``. *level* is a string such as ``"alpha"``,
  490. ``"beta"``, or ``"final"`` for a final release.
  491. Dictionaries have an odd new method, :meth:`setdefault(key, default)`, which
  492. behaves similarly to the existing :meth:`get` method. However, if the key is
  493. missing, :meth:`setdefault` both returns the value of *default* as :meth:`get`
  494. would do, and also inserts it into the dictionary as the value for *key*. Thus,
  495. the following lines of code::
  496. if dict.has_key( key ): return dict[key]
  497. else:
  498. dict[key] = []
  499. return dict[key]
  500. can be reduced to a single ``return dict.setdefault(key, [])`` statement.
  501. The interpreter sets a maximum recursion depth in order to catch runaway
  502. recursion before filling the C stack and causing a core dump or GPF..
  503. Previously this limit was fixed when you compiled Python, but in 2.0 the maximum
  504. recursion depth can be read and modified using :func:`sys.getrecursionlimit` and
  505. :func:`sys.setrecursionlimit`. The default value is 1000, and a rough maximum
  506. value for a given platform can be found by running a new script,
  507. :file:`Misc/find_recursionlimit.py`.
  508. .. ======================================================================
  509. Porting to 2.0
  510. ==============
  511. New Python releases try hard to be compatible with previous releases, and the
  512. record has been pretty good. However, some changes are considered useful
  513. enough, usually because they fix initial design decisions that turned out to be
  514. actively mistaken, that breaking backward compatibility can't always be avoided.
  515. This section lists the changes in Python 2.0 that may cause old Python code to
  516. break.
  517. The change which will probably break the most code is tightening up the
  518. arguments accepted by some methods. Some methods would take multiple arguments
  519. and treat them as a tuple, particularly various list methods such as
  520. :meth:`.append` and :meth:`.insert`. In earlier versions of Python, if ``L`` is
  521. a list, ``L.append( 1,2 )`` appends the tuple ``(1,2)`` to the list. In Python
  522. 2.0 this causes a :exc:`TypeError` exception to be raised, with the message:
  523. 'append requires exactly 1 argument; 2 given'. The fix is to simply add an
  524. extra set of parentheses to pass both values as a tuple: ``L.append( (1,2) )``.
  525. The earlier versions of these methods were more forgiving because they used an
  526. old function in Python's C interface to parse their arguments; 2.0 modernizes
  527. them to use :func:`PyArg_ParseTuple`, the current argument parsing function,
  528. which provides more helpful error messages and treats multi-argument calls as
  529. errors. If you absolutely must use 2.0 but can't fix your code, you can edit
  530. :file:`Objects/listobject.c` and define the preprocessor symbol
  531. ``NO_STRICT_LIST_APPEND`` to preserve the old behaviour; this isn't recommended.
  532. Some of the functions in the :mod:`socket` module are still forgiving in this
  533. way. For example, :func:`socket.connect( ('hostname', 25) )` is the correct
  534. form, passing a tuple representing an IP address, but :func:`socket.connect(
  535. 'hostname', 25 )` also works. :func:`socket.connect_ex` and :func:`socket.bind`
  536. are similarly easy-going. 2.0alpha1 tightened these functions up, but because
  537. the documentation actually used the erroneous multiple argument form, many
  538. people wrote code which would break with the stricter checking. GvR backed out
  539. the changes in the face of public reaction, so for the :mod:`socket` module, the
  540. documentation was fixed and the multiple argument form is simply marked as
  541. deprecated; it *will* be tightened up again in a future Python version.
  542. The ``\x`` escape in string literals now takes exactly 2 hex digits. Previously
  543. it would consume all the hex digits following the 'x' and take the lowest 8 bits
  544. of the result, so ``\x123456`` was equivalent to ``\x56``.
  545. The :exc:`AttributeError` and :exc:`NameError` exceptions have a more friendly
  546. error message, whose text will be something like ``'Spam' instance has no
  547. attribute 'eggs'`` or ``name 'eggs' is not defined``. Previously the error
  548. message was just the missing attribute name ``eggs``, and code written to take
  549. advantage of this fact will break in 2.0.
  550. Some work has been done to make integers and long integers a bit more
  551. interchangeable. In 1.5.2, large-file support was added for Solaris, to allow
  552. reading files larger than 2 GiB; this made the :meth:`tell` method of file
  553. objects return a long integer instead of a regular integer. Some code would
  554. subtract two file offsets and attempt to use the result to multiply a sequence
  555. or slice a string, but this raised a :exc:`TypeError`. In 2.0, long integers
  556. can be used to multiply or slice a sequence, and it'll behave as you'd
  557. intuitively expect it to; ``3L * 'abc'`` produces 'abcabcabc', and
  558. ``(0,1,2,3)[2L:4L]`` produces (2,3). Long integers can also be used in various
  559. contexts where previously only integers were accepted, such as in the
  560. :meth:`seek` method of file objects, and in the formats supported by the ``%``
  561. operator (``%d``, ``%i``, ``%x``, etc.). For example, ``"%d" % 2L**64`` will
  562. produce the string ``18446744073709551616``.
  563. The subtlest long integer change of all is that the :func:`str` of a long
  564. integer no longer has a trailing 'L' character, though :func:`repr` still
  565. includes it. The 'L' annoyed many people who wanted to print long integers that
  566. looked just like regular integers, since they had to go out of their way to chop
  567. off the character. This is no longer a problem in 2.0, but code which does
  568. ``str(longval)[:-1]`` and assumes the 'L' is there, will now lose the final
  569. digit.
  570. Taking the :func:`repr` of a float now uses a different formatting precision
  571. than :func:`str`. :func:`repr` uses ``%.17g`` format string for C's
  572. :func:`sprintf`, while :func:`str` uses ``%.12g`` as before. The effect is that
  573. :func:`repr` may occasionally show more decimal places than :func:`str`, for
  574. certain numbers. For example, the number 8.1 can't be represented exactly in
  575. binary, so ``repr(8.1)`` is ``'8.0999999999999996'``, while str(8.1) is
  576. ``'8.1'``.
  577. The ``-X`` command-line option, which turned all standard exceptions into
  578. strings instead of classes, has been removed; the standard exceptions will now
  579. always be classes. The :mod:`exceptions` module containing the standard
  580. exceptions was translated from Python to a built-in C module, written by Barry
  581. Warsaw and Fredrik Lundh.
  582. .. Commented out for now -- I don't think anyone will care.
  583. The pattern and match objects provided by SRE are C types, not Python
  584. class instances as in 1.5. This means you can no longer inherit from
  585. \class{RegexObject} or \class{MatchObject}, but that shouldn't be much
  586. of a problem since no one should have been doing that in the first
  587. place.
  588. .. ======================================================================
  589. Extending/Embedding Changes
  590. ===========================
  591. Some of the changes are under the covers, and will only be apparent to people
  592. writing C extension modules or embedding a Python interpreter in a larger
  593. application. If you aren't dealing with Python's C API, you can safely skip
  594. this section.
  595. The version number of the Python C API was incremented, so C extensions compiled
  596. for 1.5.2 must be recompiled in order to work with 2.0. On Windows, it's not
  597. possible for Python 2.0 to import a third party extension built for Python 1.5.x
  598. due to how Windows DLLs work, so Python will raise an exception and the import
  599. will fail.
  600. Users of Jim Fulton's ExtensionClass module will be pleased to find out that
  601. hooks have been added so that ExtensionClasses are now supported by
  602. :func:`isinstance` and :func:`issubclass`. This means you no longer have to
  603. remember to write code such as ``if type(obj) == myExtensionClass``, but can use
  604. the more natural ``if isinstance(obj, myExtensionClass)``.
  605. The :file:`Python/importdl.c` file, which was a mass of #ifdefs to support
  606. dynamic loading on many different platforms, was cleaned up and reorganised by
  607. Greg Stein. :file:`importdl.c` is now quite small, and platform-specific code
  608. has been moved into a bunch of :file:`Python/dynload_\*.c` files. Another
  609. cleanup: there were also a number of :file:`my\*.h` files in the Include/
  610. directory that held various portability hacks; they've been merged into a single
  611. file, :file:`Include/pyport.h`.
  612. Vladimir Marangozov's long-awaited malloc restructuring was completed, to make
  613. it easy to have the Python interpreter use a custom allocator instead of C's
  614. standard :func:`malloc`. For documentation, read the comments in
  615. :file:`Include/pymem.h` and :file:`Include/objimpl.h`. For the lengthy
  616. discussions during which the interface was hammered out, see the Web archives of
  617. the 'patches' and 'python-dev' lists at python.org.
  618. Recent versions of the GUSI development environment for MacOS support POSIX
  619. threads. Therefore, Python's POSIX threading support now works on the
  620. Macintosh. Threading support using the user-space GNU ``pth`` library was also
  621. contributed.
  622. Threading support on Windows was enhanced, too. Windows supports thread locks
  623. that use kernel objects only in case of contention; in the common case when
  624. there's no contention, they use simpler functions which are an order of
  625. magnitude faster. A threaded version of Python 1.5.2 on NT is twice as slow as
  626. an unthreaded version; with the 2.0 changes, the difference is only 10%. These
  627. improvements were contributed by Yakov Markovitch.
  628. Python 2.0's source now uses only ANSI C prototypes, so compiling Python now
  629. requires an ANSI C compiler, and can no longer be done using a compiler that
  630. only supports K&R C.
  631. Previously the Python virtual machine used 16-bit numbers in its bytecode,
  632. limiting the size of source files. In particular, this affected the maximum
  633. size of literal lists and dictionaries in Python source; occasionally people who
  634. are generating Python code would run into this limit. A patch by Charles G.
  635. Waldman raises the limit from ``2^16`` to ``2^{32}``.
  636. Three new convenience functions intended for adding constants to a module's
  637. dictionary at module initialization time were added: :func:`PyModule_AddObject`,
  638. :func:`PyModule_AddIntConstant`, and :func:`PyModule_AddStringConstant`. Each
  639. of these functions takes a module object, a null-terminated C string containing
  640. the name to be added, and a third argument for the value to be assigned to the
  641. name. This third argument is, respectively, a Python object, a C long, or a C
  642. string.
  643. A wrapper API was added for Unix-style signal handlers. :func:`PyOS_getsig` gets
  644. a signal handler and :func:`PyOS_setsig` will set a new handler.
  645. .. ======================================================================
  646. Distutils: Making Modules Easy to Install
  647. =========================================
  648. Before Python 2.0, installing modules was a tedious affair -- there was no way
  649. to figure out automatically where Python is installed, or what compiler options
  650. to use for extension modules. Software authors had to go through an arduous
  651. ritual of editing Makefiles and configuration files, which only really work on
  652. Unix and leave Windows and MacOS unsupported. Python users faced wildly
  653. differing installation instructions which varied between different extension
  654. packages, which made administering a Python installation something of a chore.
  655. The SIG for distribution utilities, shepherded by Greg Ward, has created the
  656. Distutils, a system to make package installation much easier. They form the
  657. :mod:`distutils` package, a new part of Python's standard library. In the best
  658. case, installing a Python module from source will require the same steps: first
  659. you simply mean unpack the tarball or zip archive, and the run "``python
  660. setup.py install``". The platform will be automatically detected, the compiler
  661. will be recognized, C extension modules will be compiled, and the distribution
  662. installed into the proper directory. Optional command-line arguments provide
  663. more control over the installation process, the distutils package offers many
  664. places to override defaults -- separating the build from the install, building
  665. or installing in non-default directories, and more.
  666. In order to use the Distutils, you need to write a :file:`setup.py` script. For
  667. the simple case, when the software contains only .py files, a minimal
  668. :file:`setup.py` can be just a few lines long::
  669. from distutils.core import setup
  670. setup (name = "foo", version = "1.0",
  671. py_modules = ["module1", "module2"])
  672. The :file:`setup.py` file isn't much more complicated if the software consists
  673. of a few packages::
  674. from distutils.core import setup
  675. setup (name = "foo", version = "1.0",
  676. packages = ["package", "package.subpackage"])
  677. A C extension can be the most complicated case; here's an example taken from
  678. the PyXML package::
  679. from distutils.core import setup, Extension
  680. expat_extension = Extension('xml.parsers.pyexpat',
  681. define_macros = [('XML_NS', None)],
  682. include_dirs = [ 'extensions/expat/xmltok',
  683. 'extensions/expat/xmlparse' ],
  684. sources = [ 'extensions/pyexpat.c',
  685. 'extensions/expat/xmltok/xmltok.c',
  686. 'extensions/expat/xmltok/xmlrole.c', ]
  687. )
  688. setup (name = "PyXML", version = "0.5.4",
  689. ext_modules =[ expat_extension ] )
  690. The Distutils can also take care of creating source and binary distributions.
  691. The "sdist" command, run by "``python setup.py sdist``', builds a source
  692. distribution such as :file:`foo-1.0.tar.gz`. Adding new commands isn't
  693. difficult, "bdist_rpm" and "bdist_wininst" commands have already been
  694. contributed to create an RPM distribution and a Windows installer for the
  695. software, respectively. Commands to create other distribution formats such as
  696. Debian packages and Solaris :file:`.pkg` files are in various stages of
  697. development.
  698. All this is documented in a new manual, *Distributing Python Modules*, that
  699. joins the basic set of Python documentation.
  700. .. ======================================================================
  701. XML Modules
  702. ===========
  703. Python 1.5.2 included a simple XML parser in the form of the :mod:`xmllib`
  704. module, contributed by Sjoerd Mullender. Since 1.5.2's release, two different
  705. interfaces for processing XML have become common: SAX2 (version 2 of the Simple
  706. API for XML) provides an event-driven interface with some similarities to
  707. :mod:`xmllib`, and the DOM (Document Object Model) provides a tree-based
  708. interface, transforming an XML document into a tree of nodes that can be
  709. traversed and modified. Python 2.0 includes a SAX2 interface and a stripped-
  710. down DOM interface as part of the :mod:`xml` package. Here we will give a brief
  711. overview of these new interfaces; consult the Python documentation or the source
  712. code for complete details. The Python XML SIG is also working on improved
  713. documentation.
  714. SAX2 Support
  715. ------------
  716. SAX defines an event-driven interface for parsing XML. To use SAX, you must
  717. write a SAX handler class. Handler classes inherit from various classes
  718. provided by SAX, and override various methods that will then be called by the
  719. XML parser. For example, the :meth:`startElement` and :meth:`endElement`
  720. methods are called for every starting and end tag encountered by the parser, the
  721. :meth:`characters` method is called for every chunk of character data, and so
  722. forth.
  723. The advantage of the event-driven approach is that the whole document doesn't
  724. have to be resident in memory at any one time, which matters if you are
  725. processing really huge documents. However, writing the SAX handler class can
  726. get very complicated if you're trying to modify the document structure in some
  727. elaborate way.
  728. For example, this little example program defines a handler that prints a message
  729. for every starting and ending tag, and then parses the file :file:`hamlet.xml`
  730. using it::
  731. from xml import sax
  732. class SimpleHandler(sax.ContentHandler):
  733. def startElement(self, name, attrs):
  734. print 'Start of element:', name, attrs.keys()
  735. def endElement(self, name):
  736. print 'End of element:', name
  737. # Create a parser object
  738. parser = sax.make_parser()
  739. # Tell it what handler to use
  740. handler = SimpleHandler()
  741. parser.setContentHandler( handler )
  742. # Parse a file!
  743. parser.parse( 'hamlet.xml' )
  744. For more information, consult the Python documentation, or the XML HOWTO at
  745. http://pyxml.sourceforge.net/topics/howto/xml-howto.html.
  746. DOM Support
  747. -----------
  748. The Document Object Model is a tree-based representation for an XML document. A
  749. top-level :class:`Document` instance is the root of the tree, and has a single
  750. child which is the top-level :class:`Element` instance. This :class:`Element`
  751. has children nodes representing character data and any sub-elements, which may
  752. have further children of their own, and so forth. Using the DOM you can
  753. traverse the resulting tree any way you like, access element and attribute
  754. values, insert and delete nodes, and convert the tree back into XML.
  755. The DOM is useful for modifying XML documents, because you can create a DOM
  756. tree, modify it by adding new nodes or rearranging subtrees, and then produce a
  757. new XML document as output. You can also construct a DOM tree manually and
  758. convert it to XML, which can be a more flexible way of producing XML output than
  759. simply writing ``<tag1>``...\ ``</tag1>`` to a file.
  760. The DOM implementation included with Python lives in the :mod:`xml.dom.minidom`
  761. module. It's a lightweight implementation of the Level 1 DOM with support for
  762. XML namespaces. The :func:`parse` and :func:`parseString` convenience
  763. functions are provided for generating a DOM tree::
  764. from xml.dom import minidom
  765. doc = minidom.parse('hamlet.xml')
  766. ``doc`` is a :class:`Document` instance. :class:`Document`, like all the other
  767. DOM classes such as :class:`Element` and :class:`Text`, is a subclass of the
  768. :class:`Node` base class. All the nodes in a DOM tree therefore support certain
  769. common methods, such as :meth:`toxml` which returns a string containing the XML
  770. representation of the node and its children. Each class also has special
  771. methods of its own; for example, :class:`Element` and :class:`Document`
  772. instances have a method to find all child elements with a given tag name.
  773. Continuing from the previous 2-line example::
  774. perslist = doc.getElementsByTagName( 'PERSONA' )
  775. print perslist[0].toxml()
  776. print perslist[1].toxml()
  777. For the *Hamlet* XML file, the above few lines output::
  778. <PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
  779. <PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>
  780. The root element of the document is available as ``doc.documentElement``, and
  781. its children can be easily modified by deleting, adding, or removing nodes::
  782. root = doc.documentElement
  783. # Remove the first child
  784. root.removeChild( root.childNodes[0] )
  785. # Move the new first child to the end
  786. root.appendChild( root.childNodes[0] )
  787. # Insert the new first child (originally,
  788. # the third child) before the 20th child.
  789. root.insertBefore( root.childNodes[0], root.childNodes[20] )
  790. Again, I will refer you to the Python documentation for a complete listing of
  791. the different :class:`Node` classes and their various methods.
  792. Relationship to PyXML
  793. ---------------------
  794. The XML Special Interest Group has been working on XML-related Python code for a
  795. while. Its code distribution, called PyXML, is available from the SIG's Web
  796. pages at http://www.python.org/sigs/xml-sig/. The PyXML distribution also used
  797. the package name ``xml``. If you've written programs that used PyXML, you're
  798. probably wondering about its compatibility with the 2.0 :mod:`xml` package.
  799. The answer is that Python 2.0's :mod:`xml` package isn't compatible with PyXML,
  800. but can be made compatible by installing a recent version PyXML. Many
  801. applications can get by with the XML support that is included with Python 2.0,
  802. but more complicated applications will require that the full PyXML package will
  803. be installed. When installed, PyXML versions 0.6.0 or greater will replace the
  804. :mod:`xml` package shipped with Python, and will be a strict superset of the
  805. standard package, adding a bunch of additional features. Some of the additional
  806. features in PyXML include:
  807. * 4DOM, a full DOM implementation from FourThought, Inc.
  808. * The xmlproc validating parser, written by Lars Marius Garshol.
  809. * The :mod:`sgmlop` parser accelerator module, written by Fredrik Lundh.
  810. .. ======================================================================
  811. Module changes
  812. ==============
  813. Lots of improvements and bugfixes were made to Python's extensive standard
  814. library; some of the affected modules include :mod:`readline`,
  815. :mod:`ConfigParser`, :mod:`cgi`, :mod:`calendar`, :mod:`posix`, :mod:`readline`,
  816. :mod:`xmllib`, :mod:`aifc`, :mod:`chunk, wave`, :mod:`random`, :mod:`shelve`,
  817. and :mod:`nntplib`. Consult the CVS logs for the exact patch-by-patch details.
  818. Brian Gallew contributed OpenSSL support for the :mod:`socket` module. OpenSSL
  819. is an implementation of the Secure Socket Layer, which encrypts the data being
  820. sent over a socket. When compiling Python, you can edit :file:`Modules/Setup`
  821. to include SSL support, which adds an additional function to the :mod:`socket`
  822. module: :func:`socket.ssl(socket, keyfile, certfile)`, which takes a socket
  823. object and returns an SSL socket. The :mod:`httplib` and :mod:`urllib` modules
  824. were also changed to support "https://" URLs, though no one has implemented FTP
  825. or SMTP over SSL.
  826. The :mod:`httplib` module has been rewritten by Greg Stein to support HTTP/1.1.
  827. Backward compatibility with the 1.5 version of :mod:`httplib` is provided,
  828. though using HTTP/1.1 features such as pipelining will require rewriting code to
  829. use a different set of interfaces.
  830. The :mod:`Tkinter` module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and
  831. support for the older 7.x versions has been dropped. The Tkinter module now
  832. supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh
  833. contributed an optimization which makes operations like ``create_line`` and
  834. ``create_polygon`` much faster, especially when using lots of coordinates.
  835. The :mod:`curses` module has been greatly extended, starting from Oliver
  836. Andrich's enhanced version, to provide many additional functions from ncurses
  837. and SYSV curses, such as colour, alternative character set support, pads, and
  838. mouse support. This means the module is no longer compatible with operating
  839. systems that only have BSD curses, but there don't seem to be any currently
  840. maintained OSes that fall into this category.
  841. As mentioned in the earlier discussion of 2.0's Unicode support, the underlying
  842. implementation of the regular expressions provided by the :mod:`re` module has
  843. been changed. SRE, a new regular expression engine written by Fredrik Lundh and
  844. partially funded by Hewlett Packard, supports matching against both 8-bit
  845. strings and Unicode strings.
  846. .. ======================================================================
  847. New modules
  848. ===========
  849. A number of new modules were added. We'll simply list them with brief
  850. descriptions; consult the 2.0 documentation for the details of a particular
  851. module.
  852. * :mod:`atexit`: For registering functions to be called before the Python
  853. interpreter exits. Code that currently sets ``sys.exitfunc`` directly should be
  854. changed to use the :mod:`atexit` module instead, importing :mod:`atexit` and
  855. calling :func:`atexit.register` with the function to be called on exit.
  856. (Contributed by Skip Montanaro.)
  857. * :mod:`codecs`, :mod:`encodings`, :mod:`unicodedata`: Added as part of the new
  858. Unicode support.
  859. * :mod:`filecmp`: Supersedes the old :mod:`cmp`, :mod:`cmpcache` and
  860. :mod:`dircmp` modules, which have now become deprecated. (Contributed by Gordon
  861. MacMillan and Moshe Zadka.)
  862. * :mod:`gettext`: This module provides internationalization (I18N) and
  863. localization (L10N) support for Python programs by providing an interface to the
  864. GNU gettext message catalog library. (Integrated by Barry Warsaw, from separate
  865. contributions by Martin von LĂświs, Peter Funk, and James Henstridge.)
  866. * :mod:`linuxaudiodev`: Support for the :file:`/dev/audio` device on Linux, a
  867. twin to the existing :mod:`sunaudiodev` module. (Contributed by Peter Bosch,
  868. with fixes by Jeremy Hylton.)
  869. * :mod:`mmap`: An interface to memory-mapped files on both Windows and Unix. A
  870. file's contents can be mapped directly into memory, at which point it behaves
  871. like a mutable string, so its contents can be read and modified. They can even
  872. be passed to functions that expect ordinary strings, such as the :mod:`re`
  873. module. (Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)
  874. * :mod:`pyexpat`: An interface to the Expat XML parser. (Contributed by Paul
  875. Prescod.)
  876. * :mod:`robotparser`: Parse a :file:`robots.txt` file, which is used for writing
  877. Web spiders that politely avoid certain areas of a Web site. The parser accepts
  878. the contents of a :file:`robots.txt` file, builds a set of rules from it, and
  879. can then answer questions about the fetchability of a given URL. (Contributed
  880. by Skip Montanaro.)
  881. * :mod:`tabnanny`: A module/script to check Python source code for ambiguous
  882. indentation. (Contributed by Tim Peters.)
  883. * :mod:`UserString`: A base class useful for deriving objects that behave like
  884. strings.
  885. * :mod:`webbrowser`: A module that provides a platform independent way to launch
  886. a web browser on a specific URL. For each platform, various browsers are tried
  887. in a specific order. The user can alter which browser is launched by setting the
  888. *BROWSER* environment variable. (Originally inspired by Eric S. Raymond's patch
  889. to :mod:`urllib` which added similar functionality, but the final module comes
  890. from code originally implemented by Fred Drake as
  891. :file:`Tools/idle/BrowserControl.py`, and adapted for the standard library by
  892. Fred.)
  893. * :mod:`_winreg`: An interface to the Windows registry. :mod:`_winreg` is an
  894. adaptation of functions that have been part of PythonWin since 1995, but has now
  895. been added to the core distribution, and enhanced to support Unicode.
  896. :mod:`_winreg` was written by Bill Tutt and Mark Hammond.
  897. * :mod:`zipfile`: A module for reading and writing ZIP-format archives. These
  898. are archives produced by :program:`PKZIP` on DOS/Windows or :program:`zip` on
  899. Unix, not to be confused with :program:`gzip`\ -format files (which are
  900. supported by the :mod:`gzip` module) (Contributed by James C. Ahlstrom.)
  901. * :mod:`imputil`: A module that provides a simpler way for writing customised
  902. import hooks, in comparison to the existing :mod:`ihooks` module. (Implemented
  903. by Greg Stein, with much discussion on python-dev along the way.)
  904. .. ======================================================================
  905. IDLE Improvements
  906. =================
  907. IDLE is the official Python cross-platform IDE, written using Tkinter. Python
  908. 2.0 includes IDLE 0.6, which adds a number of new features and improvements. A
  909. partial list:
  910. * UI improvements and optimizations, especially in the area of syntax
  911. highlighting and auto-indentation.
  912. * The class browser now shows more information, such as the top level functions
  913. in a module.
  914. * Tab width is now a user settable option. When opening an existing Python file,
  915. IDLE automatically detects the indentation conventions, and adapts.
  916. * There is now support for calling browsers on various platforms, used to open
  917. the Python documentation in a browser.
  918. * IDLE now has a command line, which is largely similar to the vanilla Python
  919. interpreter.
  920. * Call tips were added in many places.
  921. * IDLE can now be installed as a package.
  922. * In the editor window, there is now a line/column bar at the bottom.
  923. * Three new keystroke commands: Check module (Alt-F5), Import module (F5) and
  924. Run script (Ctrl-F5).
  925. .. ======================================================================
  926. Deleted and Deprecated Modules
  927. ==============================
  928. A few modules have been dropped because they're obsolete, or because there are
  929. now better ways to do the same thing. The :mod:`stdwin` module is gone; it was
  930. for a platform-independent windowing toolkit that's no longer developed.
  931. A number of modules have been moved to the :file:`lib-old` subdirectory:
  932. :mod:`cmp`, :mod:`cmpcache`, :mod:`dircmp`, :mod:`dump`, :mod:`find`,
  933. :mod:`grep`, :mod:`packmail`, :mod:`poly`, :mod:`util`, :mod:`whatsound`,
  934. :mod:`zmod`. If you have code which relies on a module that's been moved to
  935. :file:`lib-old`, you can simply add that directory to ``sys.path`` to get them
  936. back, but you're encouraged to update any code that uses these modules.
  937. Acknowledgements
  938. ================
  939. The authors would like to thank the following people for offering suggestions on
  940. various drafts of this article: David Bolen, Mark Hammond, Gregg Hauser, Jeremy
  941. Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip Montanaro, Vladimir
  942. Marangozov, Tobias Polzin, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.