PageRenderTime 43ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/Doc/whatsnew/2.3.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2078 lines | 1595 code | 483 blank | 0 comment | 0 complexity | 8db9b7b78675d404b6b3341c06d9e9af MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. ****************************
  2. What's New in Python 2.3
  3. ****************************
  4. :Author: A.M. Kuchling
  5. .. |release| replace:: 1.01
  6. .. $Id: whatsnew23.tex 54631 2007-03-31 11:58:36Z georg.brandl $
  7. This article explains the new features in Python 2.3. Python 2.3 was released
  8. on July 29, 2003.
  9. The main themes for Python 2.3 are polishing some of the features added in 2.2,
  10. adding various small but useful enhancements to the core language, and expanding
  11. the standard library. The new object model introduced in the previous version
  12. has benefited from 18 months of bugfixes and from optimization efforts that have
  13. improved the performance of new-style classes. A few new built-in functions
  14. have been added such as :func:`sum` and :func:`enumerate`. The :keyword:`in`
  15. operator can now be used for substring searches (e.g. ``"ab" in "abc"`` returns
  16. :const:`True`).
  17. Some of the many new library features include Boolean, set, heap, and date/time
  18. data types, the ability to import modules from ZIP-format archives, metadata
  19. support for the long-awaited Python catalog, an updated version of IDLE, and
  20. modules for logging messages, wrapping text, parsing CSV files, processing
  21. command-line options, using BerkeleyDB databases... the list of new and
  22. enhanced modules is lengthy.
  23. This article doesn't attempt to provide a complete specification of the new
  24. features, but instead provides a convenient overview. For full details, you
  25. should refer to the documentation for Python 2.3, such as the Python Library
  26. Reference and the Python Reference Manual. If you want to understand the
  27. complete implementation and design rationale, refer to the PEP for a particular
  28. new feature.
  29. .. ======================================================================
  30. PEP 218: A Standard Set Datatype
  31. ================================
  32. The new :mod:`sets` module contains an implementation of a set datatype. The
  33. :class:`Set` class is for mutable sets, sets that can have members added and
  34. removed. The :class:`ImmutableSet` class is for sets that can't be modified,
  35. and instances of :class:`ImmutableSet` can therefore be used as dictionary keys.
  36. Sets are built on top of dictionaries, so the elements within a set must be
  37. hashable.
  38. Here's a simple example::
  39. >>> import sets
  40. >>> S = sets.Set([1,2,3])
  41. >>> S
  42. Set([1, 2, 3])
  43. >>> 1 in S
  44. True
  45. >>> 0 in S
  46. False
  47. >>> S.add(5)
  48. >>> S.remove(3)
  49. >>> S
  50. Set([1, 2, 5])
  51. >>>
  52. The union and intersection of sets can be computed with the :meth:`union` and
  53. :meth:`intersection` methods; an alternative notation uses the bitwise operators
  54. ``&`` and ``|``. Mutable sets also have in-place versions of these methods,
  55. :meth:`union_update` and :meth:`intersection_update`. ::
  56. >>> S1 = sets.Set([1,2,3])
  57. >>> S2 = sets.Set([4,5,6])
  58. >>> S1.union(S2)
  59. Set([1, 2, 3, 4, 5, 6])
  60. >>> S1 | S2 # Alternative notation
  61. Set([1, 2, 3, 4, 5, 6])
  62. >>> S1.intersection(S2)
  63. Set([])
  64. >>> S1 & S2 # Alternative notation
  65. Set([])
  66. >>> S1.union_update(S2)
  67. >>> S1
  68. Set([1, 2, 3, 4, 5, 6])
  69. >>>
  70. It's also possible to take the symmetric difference of two sets. This is the
  71. set of all elements in the union that aren't in the intersection. Another way
  72. of putting it is that the symmetric difference contains all elements that are in
  73. exactly one set. Again, there's an alternative notation (``^``), and an in-
  74. place version with the ungainly name :meth:`symmetric_difference_update`. ::
  75. >>> S1 = sets.Set([1,2,3,4])
  76. >>> S2 = sets.Set([3,4,5,6])
  77. >>> S1.symmetric_difference(S2)
  78. Set([1, 2, 5, 6])
  79. >>> S1 ^ S2
  80. Set([1, 2, 5, 6])
  81. >>>
  82. There are also :meth:`issubset` and :meth:`issuperset` methods for checking
  83. whether one set is a subset or superset of another::
  84. >>> S1 = sets.Set([1,2,3])
  85. >>> S2 = sets.Set([2,3])
  86. >>> S2.issubset(S1)
  87. True
  88. >>> S1.issubset(S2)
  89. False
  90. >>> S1.issuperset(S2)
  91. True
  92. >>>
  93. .. seealso::
  94. :pep:`218` - Adding a Built-In Set Object Type
  95. PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and
  96. GvR.
  97. .. ======================================================================
  98. .. _section-generators:
  99. PEP 255: Simple Generators
  100. ==========================
  101. In Python 2.2, generators were added as an optional feature, to be enabled by a
  102. ``from __future__ import generators`` directive. In 2.3 generators no longer
  103. need to be specially enabled, and are now always present; this means that
  104. :keyword:`yield` is now always a keyword. The rest of this section is a copy of
  105. the description of generators from the "What's New in Python 2.2" document; if
  106. you read it back when Python 2.2 came out, you can skip the rest of this
  107. section.
  108. You're doubtless familiar with how function calls work in Python or C. When you
  109. call a function, it gets a private namespace where its local variables are
  110. created. When the function reaches a :keyword:`return` statement, the local
  111. variables are destroyed and the resulting value is returned to the caller. A
  112. later call to the same function will get a fresh new set of local variables.
  113. But, what if the local variables weren't thrown away on exiting a function?
  114. What if you could later resume the function where it left off? This is what
  115. generators provide; they can be thought of as resumable functions.
  116. Here's the simplest example of a generator function::
  117. def generate_ints(N):
  118. for i in range(N):
  119. yield i
  120. A new keyword, :keyword:`yield`, was introduced for generators. Any function
  121. containing a :keyword:`yield` statement is a generator function; this is
  122. detected by Python's bytecode compiler which compiles the function specially as
  123. a result.
  124. When you call a generator function, it doesn't return a single value; instead it
  125. returns a generator object that supports the iterator protocol. On executing
  126. the :keyword:`yield` statement, the generator outputs the value of ``i``,
  127. similar to a :keyword:`return` statement. The big difference between
  128. :keyword:`yield` and a :keyword:`return` statement is that on reaching a
  129. :keyword:`yield` the generator's state of execution is suspended and local
  130. variables are preserved. On the next call to the generator's ``.next()``
  131. method, the function will resume executing immediately after the
  132. :keyword:`yield` statement. (For complicated reasons, the :keyword:`yield`
  133. statement isn't allowed inside the :keyword:`try` block of a :keyword:`try`...\
  134. :keyword:`finally` statement; read :pep:`255` for a full explanation of the
  135. interaction between :keyword:`yield` and exceptions.)
  136. Here's a sample usage of the :func:`generate_ints` generator::
  137. >>> gen = generate_ints(3)
  138. >>> gen
  139. <generator object at 0x8117f90>
  140. >>> gen.next()
  141. 0
  142. >>> gen.next()
  143. 1
  144. >>> gen.next()
  145. 2
  146. >>> gen.next()
  147. Traceback (most recent call last):
  148. File "stdin", line 1, in ?
  149. File "stdin", line 2, in generate_ints
  150. StopIteration
  151. You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
  152. generate_ints(3)``.
  153. Inside a generator function, the :keyword:`return` statement can only be used
  154. without a value, and signals the end of the procession of values; afterwards the
  155. generator cannot return any further values. :keyword:`return` with a value, such
  156. as ``return 5``, is a syntax error inside a generator function. The end of the
  157. generator's results can also be indicated by raising :exc:`StopIteration`
  158. manually, or by just letting the flow of execution fall off the bottom of the
  159. function.
  160. You could achieve the effect of generators manually by writing your own class
  161. and storing all the local variables of the generator as instance variables. For
  162. example, returning a list of integers could be done by setting ``self.count`` to
  163. 0, and having the :meth:`next` method increment ``self.count`` and return it.
  164. However, for a moderately complicated generator, writing a corresponding class
  165. would be much messier. :file:`Lib/test/test_generators.py` contains a number of
  166. more interesting examples. The simplest one implements an in-order traversal of
  167. a tree using generators recursively. ::
  168. # A recursive generator that generates Tree leaves in in-order.
  169. def inorder(t):
  170. if t:
  171. for x in inorder(t.left):
  172. yield x
  173. yield t.label
  174. for x in inorder(t.right):
  175. yield x
  176. Two other examples in :file:`Lib/test/test_generators.py` produce solutions for
  177. the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
  178. queen threatens another) and the Knight's Tour (a route that takes a knight to
  179. every square of an $NxN$ chessboard without visiting any square twice).
  180. The idea of generators comes from other programming languages, especially Icon
  181. (http://www.cs.arizona.edu/icon/), where the idea of generators is central. In
  182. Icon, every expression and function call behaves like a generator. One example
  183. from "An Overview of the Icon Programming Language" at
  184. http://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
  185. like::
  186. sentence := "Store it in the neighboring harbor"
  187. if (i := find("or", sentence)) > 5 then write(i)
  188. In Icon the :func:`find` function returns the indexes at which the substring
  189. "or" is found: 3, 23, 33. In the :keyword:`if` statement, ``i`` is first
  190. assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
  191. retries it with the second value of 23. 23 is greater than 5, so the comparison
  192. now succeeds, and the code prints the value 23 to the screen.
  193. Python doesn't go nearly as far as Icon in adopting generators as a central
  194. concept. Generators are considered part of the core Python language, but
  195. learning or using them isn't compulsory; if they don't solve any problems that
  196. you have, feel free to ignore them. One novel feature of Python's interface as
  197. compared to Icon's is that a generator's state is represented as a concrete
  198. object (the iterator) that can be passed around to other functions or stored in
  199. a data structure.
  200. .. seealso::
  201. :pep:`255` - Simple Generators
  202. Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly
  203. by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
  204. .. ======================================================================
  205. .. _section-encodings:
  206. PEP 263: Source Code Encodings
  207. ==============================
  208. Python source files can now be declared as being in different character set
  209. encodings. Encodings are declared by including a specially formatted comment in
  210. the first or second line of the source file. For example, a UTF-8 file can be
  211. declared with::
  212. #!/usr/bin/env python
  213. # -*- coding: UTF-8 -*-
  214. Without such an encoding declaration, the default encoding used is 7-bit ASCII.
  215. Executing or importing modules that contain string literals with 8-bit
  216. characters and have no encoding declaration will result in a
  217. :exc:`DeprecationWarning` being signalled by Python 2.3; in 2.4 this will be a
  218. syntax error.
  219. The encoding declaration only affects Unicode string literals, which will be
  220. converted to Unicode using the specified encoding. Note that Python identifiers
  221. are still restricted to ASCII characters, so you can't have variable names that
  222. use characters outside of the usual alphanumerics.
  223. .. seealso::
  224. :pep:`263` - Defining Python Source Code Encodings
  225. Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao
  226. and Martin von Löwis.
  227. .. ======================================================================
  228. PEP 273: Importing Modules from ZIP Archives
  229. ============================================
  230. The new :mod:`zipimport` module adds support for importing modules from a ZIP-
  231. format archive. You don't need to import the module explicitly; it will be
  232. automatically imported if a ZIP archive's filename is added to ``sys.path``.
  233. For example::
  234. amk@nyman:~/src/python$ unzip -l /tmp/example.zip
  235. Archive: /tmp/example.zip
  236. Length Date Time Name
  237. -------- ---- ---- ----
  238. 8467 11-26-02 22:30 jwzthreading.py
  239. -------- -------
  240. 8467 1 file
  241. amk@nyman:~/src/python$ ./python
  242. Python 2.3 (#1, Aug 1 2003, 19:54:32)
  243. >>> import sys
  244. >>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
  245. >>> import jwzthreading
  246. >>> jwzthreading.__file__
  247. '/tmp/example.zip/jwzthreading.py'
  248. >>>
  249. An entry in ``sys.path`` can now be the filename of a ZIP archive. The ZIP
  250. archive can contain any kind of files, but only files named :file:`\*.py`,
  251. :file:`\*.pyc`, or :file:`\*.pyo` can be imported. If an archive only contains
  252. :file:`\*.py` files, Python will not attempt to modify the archive by adding the
  253. corresponding :file:`\*.pyc` file, meaning that if a ZIP archive doesn't contain
  254. :file:`\*.pyc` files, importing may be rather slow.
  255. A path within the archive can also be specified to only import from a
  256. subdirectory; for example, the path :file:`/tmp/example.zip/lib/` would only
  257. import from the :file:`lib/` subdirectory within the archive.
  258. .. seealso::
  259. :pep:`273` - Import Modules from Zip Archives
  260. Written by James C. Ahlstrom, who also provided an implementation. Python 2.3
  261. follows the specification in :pep:`273`, but uses an implementation written by
  262. Just van Rossum that uses the import hooks described in :pep:`302`. See section
  263. :ref:`section-pep302` for a description of the new import hooks.
  264. .. ======================================================================
  265. PEP 277: Unicode file name support for Windows NT
  266. =================================================
  267. On Windows NT, 2000, and XP, the system stores file names as Unicode strings.
  268. Traditionally, Python has represented file names as byte strings, which is
  269. inadequate because it renders some file names inaccessible.
  270. Python now allows using arbitrary Unicode strings (within the limitations of the
  271. file system) for all functions that expect file names, most notably the
  272. :func:`open` built-in function. If a Unicode string is passed to
  273. :func:`os.listdir`, Python now returns a list of Unicode strings. A new
  274. function, :func:`os.getcwdu`, returns the current directory as a Unicode string.
  275. Byte strings still work as file names, and on Windows Python will transparently
  276. convert them to Unicode using the ``mbcs`` encoding.
  277. Other systems also allow Unicode strings as file names but convert them to byte
  278. strings before passing them to the system, which can cause a :exc:`UnicodeError`
  279. to be raised. Applications can test whether arbitrary Unicode strings are
  280. supported as file names by checking :attr:`os.path.supports_unicode_filenames`,
  281. a Boolean value.
  282. Under MacOS, :func:`os.listdir` may now return Unicode filenames.
  283. .. seealso::
  284. :pep:`277` - Unicode file name support for Windows NT
  285. Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark
  286. Hammond.
  287. .. ======================================================================
  288. PEP 278: Universal Newline Support
  289. ==================================
  290. The three major operating systems used today are Microsoft Windows, Apple's
  291. Macintosh OS, and the various Unix derivatives. A minor irritation of cross-
  292. platform work is that these three platforms all use different characters to
  293. mark the ends of lines in text files. Unix uses the linefeed (ASCII character
  294. 10), MacOS uses the carriage return (ASCII character 13), and Windows uses a
  295. two-character sequence of a carriage return plus a newline.
  296. Python's file objects can now support end of line conventions other than the one
  297. followed by the platform on which Python is running. Opening a file with the
  298. mode ``'U'`` or ``'rU'`` will open a file for reading in universal newline mode.
  299. All three line ending conventions will be translated to a ``'\n'`` in the
  300. strings returned by the various file methods such as :meth:`read` and
  301. :meth:`readline`.
  302. Universal newline support is also used when importing modules and when executing
  303. a file with the :func:`execfile` function. This means that Python modules can
  304. be shared between all three operating systems without needing to convert the
  305. line-endings.
  306. This feature can be disabled when compiling Python by specifying the
  307. :option:`--without-universal-newlines` switch when running Python's
  308. :program:`configure` script.
  309. .. seealso::
  310. :pep:`278` - Universal Newline Support
  311. Written and implemented by Jack Jansen.
  312. .. ======================================================================
  313. .. _section-enumerate:
  314. PEP 279: enumerate()
  315. ====================
  316. A new built-in function, :func:`enumerate`, will make certain loops a bit
  317. clearer. ``enumerate(thing)``, where *thing* is either an iterator or a
  318. sequence, returns a iterator that will return ``(0, thing[0])``, ``(1,
  319. thing[1])``, ``(2, thing[2])``, and so forth.
  320. A common idiom to change every element of a list looks like this::
  321. for i in range(len(L)):
  322. item = L[i]
  323. # ... compute some result based on item ...
  324. L[i] = result
  325. This can be rewritten using :func:`enumerate` as::
  326. for i, item in enumerate(L):
  327. # ... compute some result based on item ...
  328. L[i] = result
  329. .. seealso::
  330. :pep:`279` - The enumerate() built-in function
  331. Written and implemented by Raymond D. Hettinger.
  332. .. ======================================================================
  333. PEP 282: The logging Package
  334. ============================
  335. A standard package for writing logs, :mod:`logging`, has been added to Python
  336. 2.3. It provides a powerful and flexible mechanism for generating logging
  337. output which can then be filtered and processed in various ways. A
  338. configuration file written in a standard format can be used to control the
  339. logging behavior of a program. Python includes handlers that will write log
  340. records to standard error or to a file or socket, send them to the system log,
  341. or even e-mail them to a particular address; of course, it's also possible to
  342. write your own handler classes.
  343. The :class:`Logger` class is the primary class. Most application code will deal
  344. with one or more :class:`Logger` objects, each one used by a particular
  345. subsystem of the application. Each :class:`Logger` is identified by a name, and
  346. names are organized into a hierarchy using ``.`` as the component separator.
  347. For example, you might have :class:`Logger` instances named ``server``,
  348. ``server.auth`` and ``server.network``. The latter two instances are below
  349. ``server`` in the hierarchy. This means that if you turn up the verbosity for
  350. ``server`` or direct ``server`` messages to a different handler, the changes
  351. will also apply to records logged to ``server.auth`` and ``server.network``.
  352. There's also a root :class:`Logger` that's the parent of all other loggers.
  353. For simple uses, the :mod:`logging` package contains some convenience functions
  354. that always use the root log::
  355. import logging
  356. logging.debug('Debugging information')
  357. logging.info('Informational message')
  358. logging.warning('Warning:config file %s not found', 'server.conf')
  359. logging.error('Error occurred')
  360. logging.critical('Critical error -- shutting down')
  361. This produces the following output::
  362. WARNING:root:Warning:config file server.conf not found
  363. ERROR:root:Error occurred
  364. CRITICAL:root:Critical error -- shutting down
  365. In the default configuration, informational and debugging messages are
  366. suppressed and the output is sent to standard error. You can enable the display
  367. of informational and debugging messages by calling the :meth:`setLevel` method
  368. on the root logger.
  369. Notice the :func:`warning` call's use of string formatting operators; all of the
  370. functions for logging messages take the arguments ``(msg, arg1, arg2, ...)`` and
  371. log the string resulting from ``msg % (arg1, arg2, ...)``.
  372. There's also an :func:`exception` function that records the most recent
  373. traceback. Any of the other functions will also record the traceback if you
  374. specify a true value for the keyword argument *exc_info*. ::
  375. def f():
  376. try: 1/0
  377. except: logging.exception('Problem recorded')
  378. f()
  379. This produces the following output::
  380. ERROR:root:Problem recorded
  381. Traceback (most recent call last):
  382. File "t.py", line 6, in f
  383. 1/0
  384. ZeroDivisionError: integer division or modulo by zero
  385. Slightly more advanced programs will use a logger other than the root logger.
  386. The :func:`getLogger(name)` function is used to get a particular log, creating
  387. it if it doesn't exist yet. :func:`getLogger(None)` returns the root logger. ::
  388. log = logging.getLogger('server')
  389. ...
  390. log.info('Listening on port %i', port)
  391. ...
  392. log.critical('Disk full')
  393. ...
  394. Log records are usually propagated up the hierarchy, so a message logged to
  395. ``server.auth`` is also seen by ``server`` and ``root``, but a :class:`Logger`
  396. can prevent this by setting its :attr:`propagate` attribute to :const:`False`.
  397. There are more classes provided by the :mod:`logging` package that can be
  398. customized. When a :class:`Logger` instance is told to log a message, it
  399. creates a :class:`LogRecord` instance that is sent to any number of different
  400. :class:`Handler` instances. Loggers and handlers can also have an attached list
  401. of filters, and each filter can cause the :class:`LogRecord` to be ignored or
  402. can modify the record before passing it along. When they're finally output,
  403. :class:`LogRecord` instances are converted to text by a :class:`Formatter`
  404. class. All of these classes can be replaced by your own specially-written
  405. classes.
  406. With all of these features the :mod:`logging` package should provide enough
  407. flexibility for even the most complicated applications. This is only an
  408. incomplete overview of its features, so please see the package's reference
  409. documentation for all of the details. Reading :pep:`282` will also be helpful.
  410. .. seealso::
  411. :pep:`282` - A Logging System
  412. Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.
  413. .. ======================================================================
  414. .. _section-bool:
  415. PEP 285: A Boolean Type
  416. =======================
  417. A Boolean type was added to Python 2.3. Two new constants were added to the
  418. :mod:`__builtin__` module, :const:`True` and :const:`False`. (:const:`True` and
  419. :const:`False` constants were added to the built-ins in Python 2.2.1, but the
  420. 2.2.1 versions are simply set to integer values of 1 and 0 and aren't a
  421. different type.)
  422. The type object for this new type is named :class:`bool`; the constructor for it
  423. takes any Python value and converts it to :const:`True` or :const:`False`. ::
  424. >>> bool(1)
  425. True
  426. >>> bool(0)
  427. False
  428. >>> bool([])
  429. False
  430. >>> bool( (1,) )
  431. True
  432. Most of the standard library modules and built-in functions have been changed to
  433. return Booleans. ::
  434. >>> obj = []
  435. >>> hasattr(obj, 'append')
  436. True
  437. >>> isinstance(obj, list)
  438. True
  439. >>> isinstance(obj, tuple)
  440. False
  441. Python's Booleans were added with the primary goal of making code clearer. For
  442. example, if you're reading a function and encounter the statement ``return 1``,
  443. you might wonder whether the ``1`` represents a Boolean truth value, an index,
  444. or a coefficient that multiplies some other quantity. If the statement is
  445. ``return True``, however, the meaning of the return value is quite clear.
  446. Python's Booleans were *not* added for the sake of strict type-checking. A very
  447. strict language such as Pascal would also prevent you performing arithmetic with
  448. Booleans, and would require that the expression in an :keyword:`if` statement
  449. always evaluate to a Boolean result. Python is not this strict and never will
  450. be, as :pep:`285` explicitly says. This means you can still use any expression
  451. in an :keyword:`if` statement, even ones that evaluate to a list or tuple or
  452. some random object. The Boolean type is a subclass of the :class:`int` class so
  453. that arithmetic using a Boolean still works. ::
  454. >>> True + 1
  455. 2
  456. >>> False + 1
  457. 1
  458. >>> False * 75
  459. 0
  460. >>> True * 75
  461. 75
  462. To sum up :const:`True` and :const:`False` in a sentence: they're alternative
  463. ways to spell the integer values 1 and 0, with the single difference that
  464. :func:`str` and :func:`repr` return the strings ``'True'`` and ``'False'``
  465. instead of ``'1'`` and ``'0'``.
  466. .. seealso::
  467. :pep:`285` - Adding a bool type
  468. Written and implemented by GvR.
  469. .. ======================================================================
  470. PEP 293: Codec Error Handling Callbacks
  471. =======================================
  472. When encoding a Unicode string into a byte string, unencodable characters may be
  473. encountered. So far, Python has allowed specifying the error processing as
  474. either "strict" (raising :exc:`UnicodeError`), "ignore" (skipping the
  475. character), or "replace" (using a question mark in the output string), with
  476. "strict" being the default behavior. It may be desirable to specify alternative
  477. processing of such errors, such as inserting an XML character reference or HTML
  478. entity reference into the converted string.
  479. Python now has a flexible framework to add different processing strategies. New
  480. error handlers can be added with :func:`codecs.register_error`, and codecs then
  481. can access the error handler with :func:`codecs.lookup_error`. An equivalent C
  482. API has been added for codecs written in C. The error handler gets the necessary
  483. state information such as the string being converted, the position in the string
  484. where the error was detected, and the target encoding. The handler can then
  485. either raise an exception or return a replacement string.
  486. Two additional error handlers have been implemented using this framework:
  487. "backslashreplace" uses Python backslash quoting to represent unencodable
  488. characters and "xmlcharrefreplace" emits XML character references.
  489. .. seealso::
  490. :pep:`293` - Codec Error Handling Callbacks
  491. Written and implemented by Walter Dörwald.
  492. .. ======================================================================
  493. .. _section-pep301:
  494. PEP 301: Package Index and Metadata for Distutils
  495. =================================================
  496. Support for the long-requested Python catalog makes its first appearance in 2.3.
  497. The heart of the catalog is the new Distutils :command:`register` command.
  498. Running ``python setup.py register`` will collect the metadata describing a
  499. package, such as its name, version, maintainer, description, &c., and send it to
  500. a central catalog server. The resulting catalog is available from
  501. http://www.python.org/pypi.
  502. To make the catalog a bit more useful, a new optional *classifiers* keyword
  503. argument has been added to the Distutils :func:`setup` function. A list of
  504. `Trove <http://catb.org/~esr/trove/>`_-style strings can be supplied to help
  505. classify the software.
  506. Here's an example :file:`setup.py` with classifiers, written to be compatible
  507. with older versions of the Distutils::
  508. from distutils import core
  509. kw = {'name': "Quixote",
  510. 'version': "0.5.1",
  511. 'description': "A highly Pythonic Web application framework",
  512. # ...
  513. }
  514. if (hasattr(core, 'setup_keywords') and
  515. 'classifiers' in core.setup_keywords):
  516. kw['classifiers'] = \
  517. ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
  518. 'Environment :: No Input/Output (Daemon)',
  519. 'Intended Audience :: Developers'],
  520. core.setup(**kw)
  521. The full list of classifiers can be obtained by running ``python setup.py
  522. register --list-classifiers``.
  523. .. seealso::
  524. :pep:`301` - Package Index and Metadata for Distutils
  525. Written and implemented by Richard Jones.
  526. .. ======================================================================
  527. .. _section-pep302:
  528. PEP 302: New Import Hooks
  529. =========================
  530. While it's been possible to write custom import hooks ever since the
  531. :mod:`ihooks` module was introduced in Python 1.3, no one has ever been really
  532. happy with it because writing new import hooks is difficult and messy. There
  533. have been various proposed alternatives such as the :mod:`imputil` and :mod:`iu`
  534. modules, but none of them has ever gained much acceptance, and none of them were
  535. easily usable from C code.
  536. :pep:`302` borrows ideas from its predecessors, especially from Gordon
  537. McMillan's :mod:`iu` module. Three new items are added to the :mod:`sys`
  538. module:
  539. * ``sys.path_hooks`` is a list of callable objects; most often they'll be
  540. classes. Each callable takes a string containing a path and either returns an
  541. importer object that will handle imports from this path or raises an
  542. :exc:`ImportError` exception if it can't handle this path.
  543. * ``sys.path_importer_cache`` caches importer objects for each path, so
  544. ``sys.path_hooks`` will only need to be traversed once for each path.
  545. * ``sys.meta_path`` is a list of importer objects that will be traversed before
  546. ``sys.path`` is checked. This list is initially empty, but user code can add
  547. objects to it. Additional built-in and frozen modules can be imported by an
  548. object added to this list.
  549. Importer objects must have a single method, :meth:`find_module(fullname,
  550. path=None)`. *fullname* will be a module or package name, e.g. ``string`` or
  551. ``distutils.core``. :meth:`find_module` must return a loader object that has a
  552. single method, :meth:`load_module(fullname)`, that creates and returns the
  553. corresponding module object.
  554. Pseudo-code for Python's new import logic, therefore, looks something like this
  555. (simplified a bit; see :pep:`302` for the full details)::
  556. for mp in sys.meta_path:
  557. loader = mp(fullname)
  558. if loader is not None:
  559. <module> = loader.load_module(fullname)
  560. for path in sys.path:
  561. for hook in sys.path_hooks:
  562. try:
  563. importer = hook(path)
  564. except ImportError:
  565. # ImportError, so try the other path hooks
  566. pass
  567. else:
  568. loader = importer.find_module(fullname)
  569. <module> = loader.load_module(fullname)
  570. # Not found!
  571. raise ImportError
  572. .. seealso::
  573. :pep:`302` - New Import Hooks
  574. Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.
  575. .. ======================================================================
  576. .. _section-pep305:
  577. PEP 305: Comma-separated Files
  578. ==============================
  579. Comma-separated files are a format frequently used for exporting data from
  580. databases and spreadsheets. Python 2.3 adds a parser for comma-separated files.
  581. Comma-separated format is deceptively simple at first glance::
  582. Costs,150,200,3.95
  583. Read a line and call ``line.split(',')``: what could be simpler? But toss in
  584. string data that can contain commas, and things get more complicated::
  585. "Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
  586. A big ugly regular expression can parse this, but using the new :mod:`csv`
  587. package is much simpler::
  588. import csv
  589. input = open('datafile', 'rb')
  590. reader = csv.reader(input)
  591. for line in reader:
  592. print line
  593. The :func:`reader` function takes a number of different options. The field
  594. separator isn't limited to the comma and can be changed to any character, and so
  595. can the quoting and line-ending characters.
  596. Different dialects of comma-separated files can be defined and registered;
  597. currently there are two dialects, both used by Microsoft Excel. A separate
  598. :class:`csv.writer` class will generate comma-separated files from a succession
  599. of tuples or lists, quoting strings that contain the delimiter.
  600. .. seealso::
  601. :pep:`305` - CSV File API
  602. Written and implemented by Kevin Altis, Dave Cole, Andrew McNamara, Skip
  603. Montanaro, Cliff Wells.
  604. .. ======================================================================
  605. .. _section-pep307:
  606. PEP 307: Pickle Enhancements
  607. ============================
  608. The :mod:`pickle` and :mod:`cPickle` modules received some attention during the
  609. 2.3 development cycle. In 2.2, new-style classes could be pickled without
  610. difficulty, but they weren't pickled very compactly; :pep:`307` quotes a trivial
  611. example where a new-style class results in a pickled string three times longer
  612. than that for a classic class.
  613. The solution was to invent a new pickle protocol. The :func:`pickle.dumps`
  614. function has supported a text-or-binary flag for a long time. In 2.3, this
  615. flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle
  616. format, 1 is the old binary format, and now 2 is a new 2.3-specific format. A
  617. new constant, :const:`pickle.HIGHEST_PROTOCOL`, can be used to select the
  618. fanciest protocol available.
  619. Unpickling is no longer considered a safe operation. 2.2's :mod:`pickle`
  620. provided hooks for trying to prevent unsafe classes from being unpickled
  621. (specifically, a :attr:`__safe_for_unpickling__` attribute), but none of this
  622. code was ever audited and therefore it's all been ripped out in 2.3. You should
  623. not unpickle untrusted data in any version of Python.
  624. To reduce the pickling overhead for new-style classes, a new interface for
  625. customizing pickling was added using three special methods:
  626. :meth:`__getstate__`, :meth:`__setstate__`, and :meth:`__getnewargs__`. Consult
  627. :pep:`307` for the full semantics of these methods.
  628. As a way to compress pickles yet further, it's now possible to use integer codes
  629. instead of long strings to identify pickled classes. The Python Software
  630. Foundation will maintain a list of standardized codes; there's also a range of
  631. codes for private use. Currently no codes have been specified.
  632. .. seealso::
  633. :pep:`307` - Extensions to the pickle protocol
  634. Written and implemented by Guido van Rossum and Tim Peters.
  635. .. ======================================================================
  636. .. _section-slices:
  637. Extended Slices
  638. ===============
  639. Ever since Python 1.4, the slicing syntax has supported an optional third "step"
  640. or "stride" argument. For example, these are all legal Python syntax:
  641. ``L[1:10:2]``, ``L[:-1:1]``, ``L[::-1]``. This was added to Python at the
  642. request of the developers of Numerical Python, which uses the third argument
  643. extensively. However, Python's built-in list, tuple, and string sequence types
  644. have never supported this feature, raising a :exc:`TypeError` if you tried it.
  645. Michael Hudson contributed a patch to fix this shortcoming.
  646. For example, you can now easily extract the elements of a list that have even
  647. indexes::
  648. >>> L = range(10)
  649. >>> L[::2]
  650. [0, 2, 4, 6, 8]
  651. Negative values also work to make a copy of the same list in reverse order::
  652. >>> L[::-1]
  653. [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  654. This also works for tuples, arrays, and strings::
  655. >>> s='abcd'
  656. >>> s[::2]
  657. 'ac'
  658. >>> s[::-1]
  659. 'dcba'
  660. If you have a mutable sequence such as a list or an array you can assign to or
  661. delete an extended slice, but there are some differences between assignment to
  662. extended and regular slices. Assignment to a regular slice can be used to
  663. change the length of the sequence::
  664. >>> a = range(3)
  665. >>> a
  666. [0, 1, 2]
  667. >>> a[1:3] = [4, 5, 6]
  668. >>> a
  669. [0, 4, 5, 6]
  670. Extended slices aren't this flexible. When assigning to an extended slice, the
  671. list on the right hand side of the statement must contain the same number of
  672. items as the slice it is replacing::
  673. >>> a = range(4)
  674. >>> a
  675. [0, 1, 2, 3]
  676. >>> a[::2]
  677. [0, 2]
  678. >>> a[::2] = [0, -1]
  679. >>> a
  680. [0, 1, -1, 3]
  681. >>> a[::2] = [0,1,2]
  682. Traceback (most recent call last):
  683. File "<stdin>", line 1, in ?
  684. ValueError: attempt to assign sequence of size 3 to extended slice of size 2
  685. Deletion is more straightforward::
  686. >>> a = range(4)
  687. >>> a
  688. [0, 1, 2, 3]
  689. >>> a[::2]
  690. [0, 2]
  691. >>> del a[::2]
  692. >>> a
  693. [1, 3]
  694. One can also now pass slice objects to the :meth:`__getitem__` methods of the
  695. built-in sequences::
  696. >>> range(10).__getitem__(slice(0, 5, 2))
  697. [0, 2, 4]
  698. Or use slice objects directly in subscripts::
  699. >>> range(10)[slice(0, 5, 2)]
  700. [0, 2, 4]
  701. To simplify implementing sequences that support extended slicing, slice objects
  702. now have a method :meth:`indices(length)` which, given the length of a sequence,
  703. returns a ``(start, stop, step)`` tuple that can be passed directly to
  704. :func:`range`. :meth:`indices` handles omitted and out-of-bounds indices in a
  705. manner consistent with regular slices (and this innocuous phrase hides a welter
  706. of confusing details!). The method is intended to be used like this::
  707. class FakeSeq:
  708. ...
  709. def calc_item(self, i):
  710. ...
  711. def __getitem__(self, item):
  712. if isinstance(item, slice):
  713. indices = item.indices(len(self))
  714. return FakeSeq([self.calc_item(i) for i in range(*indices)])
  715. else:
  716. return self.calc_item(i)
  717. From this example you can also see that the built-in :class:`slice` object is
  718. now the type object for the slice type, and is no longer a function. This is
  719. consistent with Python 2.2, where :class:`int`, :class:`str`, etc., underwent
  720. the same change.
  721. .. ======================================================================
  722. Other Language Changes
  723. ======================
  724. Here are all of the changes that Python 2.3 makes to the core Python language.
  725. * The :keyword:`yield` statement is now always a keyword, as described in
  726. section :ref:`section-generators` of this document.
  727. * A new built-in function :func:`enumerate` was added, as described in section
  728. :ref:`section-enumerate` of this document.
  729. * Two new constants, :const:`True` and :const:`False` were added along with the
  730. built-in :class:`bool` type, as described in section :ref:`section-bool` of this
  731. document.
  732. * The :func:`int` type constructor will now return a long integer instead of
  733. raising an :exc:`OverflowError` when a string or floating-point number is too
  734. large to fit into an integer. This can lead to the paradoxical result that
  735. ``isinstance(int(expression), int)`` is false, but that seems unlikely to cause
  736. problems in practice.
  737. * Built-in types now support the extended slicing syntax, as described in
  738. section :ref:`section-slices` of this document.
  739. * A new built-in function, :func:`sum(iterable, start=0)`, adds up the numeric
  740. items in the iterable object and returns their sum. :func:`sum` only accepts
  741. numbers, meaning that you can't use it to concatenate a bunch of strings.
  742. (Contributed by Alex Martelli.)
  743. * ``list.insert(pos, value)`` used to insert *value* at the front of the list
  744. when *pos* was negative. The behaviour has now been changed to be consistent
  745. with slice indexing, so when *pos* is -1 the value will be inserted before the
  746. last element, and so forth.
  747. * ``list.index(value)``, which searches for *value* within the list and returns
  748. its index, now takes optional *start* and *stop* arguments to limit the search
  749. to only part of the list.
  750. * Dictionaries have a new method, :meth:`pop(key[, *default*])`, that returns
  751. the value corresponding to *key* and removes that key/value pair from the
  752. dictionary. If the requested key isn't present in the dictionary, *default* is
  753. returned if it's specified and :exc:`KeyError` raised if it isn't. ::
  754. >>> d = {1:2}
  755. >>> d
  756. {1: 2}
  757. >>> d.pop(4)
  758. Traceback (most recent call last):
  759. File "stdin", line 1, in ?
  760. KeyError: 4
  761. >>> d.pop(1)
  762. 2
  763. >>> d.pop(1)
  764. Traceback (most recent call last):
  765. File "stdin", line 1, in ?
  766. KeyError: 'pop(): dictionary is empty'
  767. >>> d
  768. {}
  769. >>>
  770. There's also a new class method, :meth:`dict.fromkeys(iterable, value)`, that
  771. creates a dictionary with keys taken from the supplied iterator *iterable* and
  772. all values set to *value*, defaulting to ``None``.
  773. (Patches contributed by Raymond Hettinger.)
  774. Also, the :func:`dict` constructor now accepts keyword arguments to simplify
  775. creating small dictionaries::
  776. >>> dict(red=1, blue=2, green=3, black=4)
  777. {'blue': 2, 'black': 4, 'green': 3, 'red': 1}
  778. (Contributed by Just van Rossum.)
  779. * The :keyword:`assert` statement no longer checks the ``__debug__`` flag, so
  780. you can no longer disable assertions by assigning to ``__debug__``. Running
  781. Python with the :option:`-O` switch will still generate code that doesn't
  782. execute any assertions.
  783. * Most type objects are now callable, so you can use them to create new objects
  784. such as functions, classes, and modules. (This means that the :mod:`new` module
  785. can be deprecated in a future Python version, because you can now use the type
  786. objects available in the :mod:`types` module.) For example, you can create a new
  787. module object with the following code:
  788. ::
  789. >>> import types
  790. >>> m = types.ModuleType('abc','docstring')
  791. >>> m
  792. <module 'abc' (built-in)>
  793. >>> m.__doc__
  794. 'docstring'
  795. * A new warning, :exc:`PendingDeprecationWarning` was added to indicate features
  796. which are in the process of being deprecated. The warning will *not* be printed
  797. by default. To check for use of features that will be deprecated in the future,
  798. supply :option:`-Walways::PendingDeprecationWarning::` on the command line or
  799. use :func:`warnings.filterwarnings`.
  800. * The process of deprecating string-based exceptions, as in ``raise "Error
  801. occurred"``, has begun. Raising a string will now trigger
  802. :exc:`PendingDeprecationWarning`.
  803. * Using ``None`` as a variable name will now result in a :exc:`SyntaxWarning`
  804. warning. In a future version of Python, ``None`` may finally become a keyword.
  805. * The :meth:`xreadlines` method of file objects, introduced in Python 2.1, is no
  806. longer necessary because files now behave as their own iterator.
  807. :meth:`xreadlines` was originally introduced as a faster way to loop over all
  808. the lines in a file, but now you can simply write ``for line in file_obj``.
  809. File objects also have a new read-only :attr:`encoding` attribute that gives the
  810. encoding used by the file; Unicode strings written to the file will be
  811. automatically converted to bytes using the given encoding.
  812. * The method resolution order used by new-style classes has changed, though
  813. you'll only notice the difference if you have a really complicated inheritance
  814. hierarchy. Classic classes are unaffected by this change. Python 2.2
  815. originally used a topological sort of a class's ancestors, but 2.3 now uses the
  816. C3 algorithm as described in the paper `"A Monotonic Superclass Linearization
  817. for Dylan" <http://www.webcom.com/haahr/dylan/linearization-oopsla96.html>`_. To
  818. understand the motivation for this change, read Michele Simionato's article
  819. `"Python 2.3 Method Resolution Order" <http://www.python.org/2.3/mro.html>`_, or
  820. read the thread on python-dev starting with the message at
  821. http://mail.python.org/pipermail/python-dev/2002-October/029035.html. Samuele
  822. Pedroni first pointed out the problem and also implemented the fix by coding the
  823. C3 algorithm.
  824. * Python runs multithreaded programs by switching between threads after
  825. executing N bytecodes. The default value for N has been increased from 10 to
  826. 100 bytecodes, speeding up single-threaded applications by reducing the
  827. switching overhead. Some multithreaded applications may suffer slower response
  828. time, but that's easily fixed by setting the limit back to a lower number using
  829. :func:`sys.setcheckinterval(N)`. The limit can be retrieved with the new
  830. :func:`sys.getcheckinterval` function.
  831. * One minor but far-reaching change is that the names of extension types defined
  832. by the modules included with Python now contain the module and a ``'.'`` in
  833. front of the type name. For example, in Python 2.2, if you created a socket and
  834. printed its :attr:`__class__`, you'd get this output::
  835. >>> s = socket.socket()
  836. >>> s.__class__
  837. <type 'socket'>
  838. In 2.3, you get this::
  839. >>> s.__class__
  840. <type '_socket.socket'>
  841. * One of the noted incompatibilities between old- and new-style classes has been
  842. removed: you can now assign to the :attr:`__name__` and :attr:`__bases__`
  843. attributes of new-style classes. There are some restrictions on what can be
  844. assigned to :attr:`__bases__` along the lines of those relating to assigning to
  845. an instance's :attr:`__class__` attribute.
  846. .. ======================================================================
  847. String Changes
  848. --------------
  849. * The :keyword:`in` operator now works differently for strings. Previously, when
  850. evaluating ``X in Y`` where *X* and *Y* are strings, *X* could only be a single
  851. character. That's now changed; *X* can be a string of any length, and ``X in Y``
  852. will return :const:`True` if *X* is a substring of *Y*. If *X* is the empty
  853. string, the result is always :const:`True`. ::
  854. >>> 'ab' in 'abcd'
  855. True
  856. >>> 'ad' in 'abcd'
  857. False
  858. >>> '' in 'abcd'
  859. True
  860. Note that this doesn't tell you where the substring starts; if you need that
  861. information, use the :meth:`find` string method.
  862. * The :meth:`strip`, :meth:`lstrip`, and :meth:`rstrip` string methods now have
  863. an optional argument for specifying the characters to strip. The default is
  864. still to remove all whitespace characters::
  865. >>> ' abc '.strip()
  866. 'abc'
  867. >>> '><><abc<><><>'.strip('<>')
  868. 'abc'
  869. >>> '><><abc<><><>\n'.strip('<>')
  870. 'abc<><><>\n'
  871. >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
  872. u'\u4001abc'
  873. >>>
  874. (Suggested by Simon Brunning and implemented by Walter Dörwald.)
  875. * The :meth:`startswith` and :meth:`endswith` string methods now accept negative
  876. numbers for the *start* and *end* parameters.
  877. * Another new string method is :meth:`zfill`, originally a function in the
  878. :mod:`string` module. :meth:`zfill` pads a numeric string with zeros on the
  879. left until it's the specified width. Note that the ``%`` operator is still more
  880. flexible and powerful than :meth:`zfill`. ::
  881. >>> '45'.zfill(4)
  882. '0045'
  883. >>> '12345'.zfill(4)
  884. '12345'
  885. >>> 'goofy'.zfill(6)
  886. '0goofy'
  887. (Contributed by Walter Dörwald.)
  888. * A new type object, :class:`basestring`, has been added. Both 8-bit strings and
  889. Unicode strings inherit from this type, so ``isinstance(obj, basestring)`` will
  890. return :const:`True` for either kind of string. It's a completely abstract
  891. type, so you can't create :class:`basestring` instances.
  892. * Interned strings are no longer immortal and will now be garbage-collected in
  893. the usual way when the only reference to them is from the internal dictionary of
  894. interned strings. (Implemented by Oren Tirosh.)
  895. .. ======================================================================
  896. Optimizations
  897. -------------
  898. * The creation of new-style class instances has been made much faster; they're
  899. now faster than classic classes!
  900. * The :meth:`sort` method of list objects has been extensively rewritten by Tim
  901. Peters, and the implementation is significantly faster.
  902. * Multiplication of large long integers is now much faster thanks to an
  903. implementation of Karatsuba multiplication, an algorithm that scales better than
  904. the O(n\*n) required for the grade-school multiplication algorithm. (Original
  905. patch by Christopher A. Craig, and significantly reworked by Tim Peters.)
  906. * The ``SET_LINENO`` opcode is now gone. This may provide a small speed
  907. increase, depending on your compiler's idiosyncrasies. See section
  908. :ref:`section-other` for a longer explanation. (Removed by Michael Hudson.)
  909. * :func:`xrange` objects now have their own iterator, making ``for i in
  910. xrange(n)`` slightly faster than ``for i in range(n)``. (Patch by Raymond
  911. Hettinger.)
  912. * A number of small rearrangements have been made in various hotspots to improve
  913. performance, such as inlining a function or removing some code. (Implemented
  914. mostly by GvR, but lots of people have contributed single changes.)
  915. The net result of the 2.3 optimizations is that Python 2.3 runs the pystone
  916. benchmark around 25% faster than Python 2.2.
  917. .. ======================================================================
  918. New, Improved, and Deprecated Modules
  919. =====================================
  920. As usual, Python's standard library received a number of enhancements and bug
  921. fixes. Here's a partial list of the most notable changes, sorted alphabetically
  922. by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
  923. complete list of changes, or look through the CVS logs for all the details.
  924. * The :mod:`array` module now supports arrays of Unicode characters using the
  925. ``'u'`` format character. Arrays also now support using the ``+=`` assignment
  926. operator to add another array's contents, and the ``*=`` assignment operator to
  927. repeat an array. (Contributed by Jason Orendorff.)
  928. * The :mod:`bsddb` module has been replaced by version 4.1.6 of the `PyBSDDB
  929. <http://pybsddb.sourceforge.net>`_ package, providing a more complete interface
  930. to the transactional features of the BerkeleyDB library.
  931. The old version of the module has been renamed to :mod:`bsddb185` and is no
  932. longer built automatically; you'll have to edit :file:`Modules/Setup` to enable
  933. it. Note that the new :mod:`bsddb` package is intended to be compatible with
  934. the old module, so be sure to file bugs if you discover any incompatibilities.
  935. When upgrading to Python 2.3, if the new interpreter is compiled with a new
  936. version of the underlying BerkeleyDB library, you will almost certainly have to
  937. convert your database files to the new version. You can do this fairly easily
  938. with the new scripts :file:`db2pickle.py` and :file:`pickle2db.py` which you
  939. will find in the distribution's :file:`Tools/scripts` directory. If you've
  940. already been using the PyBSDDB package and importing it as :mod:`bsddb3`, you
  941. will have to change your ``import`` statements to import it as :mod:`bsddb`.
  942. * The new :mod:`bz2` module is an interface to the bz2 data compression library.
  943. bz2-compressed data is usually smaller than corresponding :mod:`zlib`\
  944. -compressed data. (Contributed by Gustavo Niemeyer.)
  945. * A set of standard date/time types has been added in the new :mod:`datetime`
  946. module. See the following section for more details.
  947. * The Distutils :class:`Extension` class now supports an extra constructor
  948. argument named *depends* for listing additional source files that an extension
  949. depends on. This lets Distutils recompile the module if any of the dependency
  950. files are modified. For example, if :file:`sampmodule.c` includes the header
  951. file :file:`sample.h`, you would create the :class:`Extension` object like
  952. this::
  953. ext = Extension("samp",
  954. sources=["sampmodule.c"],
  955. depends=["sample.h"])
  956. Modifying :file:`sample.h` would then cause the module to be recompiled.
  957. (Contributed by Jeremy Hylton.)
  958. * Other minor changes to Distutils: it now checks for the :envvar:`CC`,
  959. :envvar:`CFLAGS`, :envvar:`CPP`, :envvar:`LDFLAGS`, and :envvar:`CPPFLAGS`
  960. environment variables, using them to override the settings in Python's
  961. configuration (contributed by Robert Weber).
  962. * Previously the :mod:`doctest` module would only search the docstrings of
  963. public methods and functions for test cases, but it now also examines private
  964. ones as well. The :func:`DocTestSuite(` function creates a
  965. :class:`unittest.TestSuite` object from a set of :mod:`doctest` tests.
  966. * The new :func:`gc.get_referents(object)` function returns a list of all the
  967. objects referenced by *object*.
  968. * The :mod:`getopt` module gained a new function, :func:`gnu_getopt`, that
  969. supports the same arguments as the existing :func:`getopt` function but uses
  970. GNU-style scanning mode. The existing :func:`getopt` stops processing options as
  971. soon as a non-option argument is encountered, but in GNU-style mode processing
  972. continues, meaning that options and arguments can be mixed. For example::
  973. >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
  974. ([('-f', 'filename')], ['output', '-v'])
  975. >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
  976. ([('-f', 'filename'), ('-v', '')], ['output'])
  977. (Contributed by Peter Ă…strand.)
  978. * The :mod:`grp`, :mod:`pwd`, and :mod:`resource` modules now return enhanced
  979. tuples::
  980. >>> import grp
  981. >>> g = grp.getgrnam('amk')
  982. >>> g.gr_name, g.gr_gid
  983. ('amk', 500)
  984. * The :mod:`gzip` module can now handle files exceeding 2 GiB.
  985. * The new :mod:`heapq` module contains an implementation of a heap queue
  986. algorithm. A heap is an array-like data structure that keeps items in a
  987. partially sorted order such that, for every index *k*, ``heap[k] <=
  988. heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]``. This makes it quick to remove the
  989. smallest item, and inserting a new item while maintaining the heap property is
  990. O(lg n). (See http://www.nist.gov/dads/HTML/priorityque.html for more
  991. information about the priority queue data structure.)
  992. The :mod:`heapq` module provides :func:`heappush` and :func:`heappop` functions
  993. for adding and removing items while maintaining the heap property on top of some
  994. other mutable Python sequence type. Here's an example that uses a Python list::
  995. >>> import heapq
  996. >>> heap = []
  997. >>> for item in [3, 7, 5, 11, 1]:
  998. ... heapq.heappush(heap, item)
  999. ...
  1000. >>> heap
  1001. [1, 3, 5, 11, 7]
  1002. >>> heapq.heappop(heap)
  1003. 1
  1004. >>> heapq.heappop(heap)
  1005. 3
  1006. >>> heap
  1007. [5, 7, 11]
  1008. (Contributed by Kevin O'Connor.)
  1009. * The IDLE integrated development environment has been updated using the code
  1010. from the IDLEfork project (http://idlefork.sf.net). The most notable feature is
  1011. that the code being developed is now executed in a subprocess, meaning that
  1012. there's no longer any need for manual ``reload()`` operations. IDLE's core code
  1013. has been incorporated into the standard library as the :mod:`idlelib` package.
  1014. * The :mod:`imaplib` module now supports IMAP over SSL. (Contributed by Piers
  1015. Lauder and Tino Lange.)
  1016. * The :mod:`itertools` contains a number of useful functions for use with
  1017. iterators, inspired by various functions provided by the ML and Haskell
  1018. languages. For example, ``itertools.ifilter(predicate, iterator)`` returns all
  1019. elements in the iterator for which the function :func:`predicate` returns
  1020. :const:`True`, and ``itertools.repeat(obj, N)`` returns ``obj`` *N* times.
  1021. There are a number of other functions in the module; see the package's reference
  1022. documentation for details.
  1023. (Contributed by Raymond Hettinger.)
  1024. * Two new functions in the :mod:`math` module, :func:`degrees(rads)` and
  1025. :func:`radians(degs)`, convert between radians and degrees. Other functions in
  1026. the :mod:`math` module such as :func:`math.sin` and :func:`math.cos` have always
  1027. required input values measured in radians. Also, an optional *base* argument
  1028. was added to :func:`math.log` to make it easier to compute logarithms for bases
  1029. other than ``e`` and ``10``. (Contributed by Raymond Hettinger.)
  1030. * Several new POSIX functions (:func:`getpgid`, :func:`killpg`, :func:`lchown`,
  1031. :func:`loadavg`, :func:`major`, :func:`makedev`, :func:`minor`, and
  1032. :func:`mknod`) were added to the :mod:`posix` module that underlies the
  1033. :mod:`os` module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
  1034. Otkidach.)
  1035. * In the :mod:`os` module, the :func:`\*stat` family of functions can now report
  1036. fractions of a second in a timestamp. Such time stamps are represented as
  1037. floats, similar to the value returned by :func:`time.time`.
  1038. During testing, it was found that some applications will break if time stamps
  1039. are floats. For compatibility, when using the tuple interface of the
  1040. :class:`stat_result` time stamps will be represented as integers. When using
  1041. named fields (a feature first introduced in Python 2.2), time stamps are still
  1042. represented as integers, unless :func:`os.stat_float_times` is invoked to enable
  1043. float return values::
  1044. >>> os.stat("/tmp").st_mtime
  1045. 1034791200
  1046. >>> os.stat_float_times(True)
  1047. >>> os.stat("/tmp").st_mtime
  1048. 1034791200.6335014
  1049. In Python 2.4, the default will change to always returning floats.
  1050. Application developers should enable this feature only if all their libraries
  1051. work properly when confronted with floating point time stamps, or if they use
  1052. the tuple API. If used, the feature should be activated on an application level
  1053. instead of trying to enable it on a per-use basis.
  1054. * The :mod:`optparse` module contains a new parser for command-line arguments
  1055. that can convert option values to a particular Python type and will
  1056. automatically generate a usage message. See the following section for more
  1057. details.
  1058. * The old and never-documented :mod:`linuxaudiodev` module has been deprecated,
  1059. and a new version named :mod:`ossaudiodev` has been added. The module was
  1060. renamed because the OSS sound drivers can be used on platforms other than Linux,
  1061. and the interface has also been tidied and brought up to date in various ways.
  1062. (Contributed by Greg Ward and Nicholas FitzRoy-Dale.)
  1063. * The new :mod:`platform` module contains a number of functions that try to
  1064. determine various properties of the platform you're running on. There are
  1065. functions for getting the architecture, CPU type, the Windows OS version, and
  1066. even the Linux distribution version. (Contributed by Marc-André Lemburg.)
  1067. * The parser objects provided by the :mod:`pyexpat` module can now optionally
  1068. buffer character data, resulting in fewer calls to your character data handler
  1069. and therefore faster performance. Setting the parser object's
  1070. :attr:`buffer_text` attribute to :const:`True` will enable buffering.
  1071. * The :func:`sample(population, k)` function was added to the :mod:`random`
  1072. module. *population* is a sequence or :class:`xrange` object containing the
  1073. elements of a population, and :func:`sample` chooses *k* elements from the
  1074. population without replacing chosen elements. *k* can be any value up to
  1075. ``len(population)``. For example::
  1076. >>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
  1077. >>> random.sample(days, 3) # Choose 3 elements
  1078. ['St', 'Sn', 'Th']
  1079. >>> random.sample(days, 7) # Choose 7 elements
  1080. ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
  1081. >>> random.sample(days, 7) # Choose 7 again
  1082. ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
  1083. >>> random.sample(days, 8) # Can't choose eight
  1084. Traceback (most recent call last):
  1085. File "<stdin>", line 1, in ?
  1086. File "random.py", line 414, in sample
  1087. raise ValueError, "sample larger than population"
  1088. ValueError: sample larger than population
  1089. >>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
  1090. [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
  1091. The :mod:`random` module now uses a new algorithm, the Mersenne Twister,
  1092. implemented in C. It's faster and more extensively studied than the previous
  1093. algorithm.
  1094. (All changes contributed by Raymond Hettinger.)
  1095. * The :mod:`readline` module also gained a number of new functions:
  1096. :func:`get_history_item`, :func:`get_current_history_length`, and
  1097. :func:`redisplay`.
  1098. * The :mod:`rexec` and :mod:`Bastion` modules have been declared dead, and
  1099. attempts to import them will fail with a :exc:`RuntimeError`. New-style classes
  1100. provide new ways to break out of the restricted execution environment provided
  1101. by :mod:`rexec`, and no one has interest in fixing them or time to do so. If
  1102. you have applications using :mod:`rexec`, rewrite them to use something else.
  1103. (Sticking with Python 2.2 or 2.1 will not make your applications any safer
  1104. because there are known bugs in the :mod:`rexec` module in those versions. To
  1105. repeat: if you're using :mod:`rexec`, stop using it immediately.)
  1106. * The :mod:`rotor` module has been deprecated because the algorithm it uses for
  1107. encryption is not believed to be secure. If you need encryption, use one of the
  1108. several AES Python modules that are available separately.
  1109. * The :mod:`shutil` module gained a :func:`move(src, dest)` function that
  1110. recursively moves a file or directory to a new location.
  1111. * Support for more advanced POSIX signal handling was added to the :mod:`signal`
  1112. but then removed again as it proved impossible to make it work reliably across
  1113. platforms.
  1114. * The :mod:`socket` module now supports timeouts. You can call the
  1115. :meth:`settimeout(t)` method on a socket object to set a timeout of *t* seconds.
  1116. Subsequent socket operations that take longer than *t* seconds to complete will
  1117. abort and raise a :exc:`socket.timeout` exception.
  1118. The original timeout implementation was by Tim O'Malley. Michael Gilfix
  1119. integrated it into the Python :mod:`socket` module and shepherded it through a
  1120. lengthy review. After the code was checked in, Guido van Rossum rewrote parts
  1121. of it. (This is a good example of a collaborative development process in
  1122. action.)
  1123. * On Windows, the :mod:`socket` module now ships with Secure Sockets Layer
  1124. (SSL) support.
  1125. * The value of the C :const:`PYTHON_API_VERSION` macro is now exposed at the
  1126. Python level as ``sys.api_version``. The current exception can be cleared by
  1127. calling the new :func:`sys.exc_clear` function.
  1128. * The new :mod:`tarfile` module allows reading from and writing to
  1129. :program:`tar`\ -format archive files. (Contributed by Lars Gustäbel.)
  1130. * The new :mod:`textwrap` module contains functions for wrapping strings
  1131. containing paragraphs of text. The :func:`wrap(text, width)` function takes a
  1132. string and returns a list containing the text split into lines of no more than
  1133. the chosen width. The :func:`fill(text, width)` function returns a single
  1134. string, reformatted to fit into lines no longer than the chosen width. (As you
  1135. can guess, :func:`fill` is built on top of :func:`wrap`. For example::
  1136. >>> import textwrap
  1137. >>> paragraph = "Not a whit, we defy augury: ... more text ..."
  1138. >>> textwrap.wrap(paragraph, 60)
  1139. ["Not a whit, we defy augury: there's a special providence in",
  1140. "the fall of a sparrow. If it be now, 'tis not to come; if it",
  1141. ...]
  1142. >>> print textwrap.fill(paragraph, 35)
  1143. Not a whit, we defy augury: there's
  1144. a special providence in the fall of
  1145. a sparrow. If it be now, 'tis not
  1146. to come; if it be not to come, it
  1147. will be now; if it be not now, yet
  1148. it will come: the readiness is all.
  1149. >>>
  1150. The module also contains a :class:`TextWrapper` class that actually implements
  1151. the text wrapping strategy. Both the :class:`TextWrapper` class and the
  1152. :func:`wrap` and :func:`fill` functions support a number of additional keyword
  1153. arguments for fine-tuning the formatting; consult the module's documentation
  1154. for details. (Contributed by Greg Ward.)
  1155. * The :mod:`thread` and :mod:`threading` modules now have companion modules,
  1156. :mod:`dummy_thread` and :mod:`dummy_threading`, that provide a do-nothing
  1157. implementation of the :mod:`thread` module's interface for platforms where
  1158. threads are not supported. The intention is to simplify thread-aware modules
  1159. (ones that *don't* rely on threads to run) by putting the following code at the
  1160. top::
  1161. try:
  1162. import threading as _threading
  1163. except ImportError:
  1164. import dummy_threading as _threading
  1165. In this example, :mod:`_threading` is used as the module name to make it clear
  1166. that the module being used is not necessarily the actual :mod:`threading`
  1167. module. Code can call functions and use classes in :mod:`_threading` whether or
  1168. not threads are supported, avoiding an :keyword:`if` statement and making the
  1169. code slightly clearer. This module will not magically make multithreaded code
  1170. run without threads; code that waits for another thread to return or to do
  1171. something will simply hang forever.
  1172. * The :mod:`time` module's :func:`strptime` function has long been an annoyance
  1173. because it uses the platform C library's :func:`strptime` implementation, and
  1174. different platforms sometimes have odd bugs. Brett Cannon contributed a
  1175. portable implementation that's written in pure Python and should behave
  1176. identically on all platforms.
  1177. * The new :mod:`timeit` module helps measure how long snippets of Python code
  1178. take to execute. The :file:`timeit.py` file can be run directly from the
  1179. command line, or the module's :class:`Timer` class can be imported and used
  1180. directly. Here's a short example that figures out whether it's faster to
  1181. convert an 8-bit string to Unicode by appending an empty Unicode string to it or
  1182. by using the :func:`unicode` function::
  1183. import timeit
  1184. timer1 = timeit.Timer('unicode("abc")')
  1185. timer2 = timeit.Timer('"abc" + u""')
  1186. # Run three trials
  1187. print timer1.repeat(repeat=3, number=100000)
  1188. print timer2.repeat(repeat=3, number=100000)
  1189. # On my laptop this outputs:
  1190. # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
  1191. # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
  1192. * The :mod:`Tix` module has received various bug fixes and updates for the
  1193. current version of the Tix package.
  1194. * The :mod:`Tkinter` module now works with a thread-enabled version of Tcl.
  1195. Tcl's threading model requires that widgets only be accessed from the thread in
  1196. which they're created; accesses from another thread can cause Tcl to panic. For
  1197. certain Tcl interfaces, :mod:`Tkinter` will now automatically avoid this when a
  1198. widget is accessed from a different thread by marshalling a command, passing it
  1199. to the correct thread, and waiting for the results. Other interfaces can't be
  1200. handled automatically but :mod:`Tkinter` will now raise an exception on such an
  1201. access so that you can at least find out about the problem. See
  1202. http://mail.python.org/pipermail/python-dev/2002-December/031107.html for a more
  1203. detailed explanation of this change. (Implemented by Martin von Löwis.)
  1204. * Calling Tcl methods through :mod:`_tkinter` no longer returns only strings.
  1205. Instead, if Tcl returns other objects those objects are converted to their
  1206. Python equivalent, if one exists, or wrapped with a :class:`_tkinter.Tcl_Obj`
  1207. object if no Python equivalent exists. This behavior can be controlled through
  1208. the :meth:`wantobjects` method of :class:`tkapp` objects.
  1209. When using :mod:`_tkinter` through the :mod:`Tkinter` module (as most Tkinter
  1210. applications will), this feature is always activated. It should not cause
  1211. compatibility problems, since Tkinter would always convert string results to
  1212. Python types where possible.
  1213. If any incompatibilities are found, the old behavior can be restored by setting
  1214. the :attr:`wantobjects` variable in the :mod:`Tkinter` module to false before
  1215. creating the first :class:`tkapp` object. ::
  1216. import Tkinter
  1217. Tkinter.wantobjects = 0
  1218. Any breakage caused by this change should be reported as a bug.
  1219. * The :mod:`UserDict` module has a new :class:`DictMixin` class which defines
  1220. all dictionary methods for classes that already have a minimum mapping
  1221. interface. This greatly simplifies writing classes that need to be
  1222. substitutable for dictionaries, such as the classes in the :mod:`shelve`
  1223. module.
  1224. Adding the mix-in as a superclass provides the full dictionary interface
  1225. whenever the class defines :meth:`__getitem__`, :meth:`__setitem__`,
  1226. :meth:`__delitem__`, and :meth:`keys`. For example::
  1227. >>> import UserDict
  1228. >>> class SeqDict(UserDict.DictMixin):
  1229. ... """Dictionary lookalike implemented with lists."""
  1230. ... def __init__(self):
  1231. ... self.keylist = []
  1232. ... self.valuelist = []
  1233. ... def __getitem__(self, key):
  1234. ... try:
  1235. ... i = self.keylist.index(key)
  1236. ... except ValueError:
  1237. ... raise KeyError
  1238. ... return self.valuelist[i]
  1239. ... def __setitem__(self, key, value):
  1240. ... try:
  1241. ... i = self.keylist.index(key)
  1242. ... self.valuelist[i] = value
  1243. ... except ValueError:
  1244. ... self.keylist.append(key)
  1245. ... self.valuelist.append(value)
  1246. ... def __delitem__(self, key):
  1247. ... try:
  1248. ... i = self.keylist.index(key)
  1249. ... except ValueError:
  1250. ... raise KeyError
  1251. ... self.keylist.pop(i)
  1252. ... self.valuelist.pop(i)
  1253. ... def keys(self):
  1254. ... return list(self.keylist)
  1255. ...
  1256. >>> s = SeqDict()
  1257. >>> dir(s) # See that other dictionary methods are implemented
  1258. ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
  1259. '__init__', '__iter__', '__len__', '__module__', '__repr__',
  1260. '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
  1261. 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
  1262. 'setdefault', 'update', 'valuelist', 'values']
  1263. (Contributed by Raymond Hettinger.)
  1264. * The DOM implementation in :mod:`xml.dom.minidom` can now generate XML output
  1265. in a particular encoding by providing an optional encoding argument to the
  1266. :meth:`toxml` and :meth:`toprettyxml` methods of DOM nodes.
  1267. * The :mod:`xmlrpclib` module now supports an XML-RPC extension for handling nil
  1268. data values such as Python's ``None``. Nil values are always supported on
  1269. unmarshalling an XML-RPC response. To generate requests containing ``None``,
  1270. you must supply a true value for the *allow_none* parameter when creating a
  1271. :class:`Marshaller` instance.
  1272. * The new :mod:`DocXMLRPCServer` module allows writing self-documenting XML-RPC
  1273. servers. Run it in demo mode (as a program) to see it in action. Pointing the
  1274. Web browser to the RPC server produces pydoc-style documentation; pointing
  1275. xmlrpclib to the server allows invoking the actual methods. (Contributed by
  1276. Brian Quinlan.)
  1277. * Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)
  1278. has been added. The "idna" encoding can be used to convert between a Unicode
  1279. domain name and the ASCII-compatible encoding (ACE) of that name. ::
  1280. >{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
  1281. 'www.xn--alliancefranaise-npb.nu'
  1282. The :mod:`socket` module has also been extended to transparently convert
  1283. Unicode hostnames to the ACE version before passing them to the C library.
  1284. Modules that deal with hostnames such as :mod:`httplib` and :mod:`ftplib`)
  1285. also support Unicode host names; :mod:`httplib` also sends HTTP ``Host``
  1286. headers using the ACE version of the domain name. :mod:`urllib` supports
  1287. Unicode URLs with non-ASCII host names as long as the ``path`` part of the URL
  1288. is ASCII only.
  1289. To implement this change, the :mod:`stringprep` module, the ``mkstringprep``
  1290. tool and the ``punycode`` encoding have been added.
  1291. .. ======================================================================
  1292. Date/Time Type
  1293. --------------
  1294. Date and time types suitable for expressing timestamps were added as the
  1295. :mod:`datetime` module. The types don't support different calendars or many
  1296. fancy features, and just stick to the basics of representing time.
  1297. The three primary types are: :class:`date`, representing a day, month, and year;
  1298. :class:`time`, consisting of hour, minute, and second; and :class:`datetime`,
  1299. which contains all the attributes of both :class:`date` and :class:`time`.
  1300. There's also a :class:`timedelta` class representing differences between two
  1301. points in time, and time zone logic is implemented by classes inheriting from
  1302. the abstract :class:`tzinfo` class.
  1303. You can create instances of :class:`date` and :class:`time` by either supplying
  1304. keyword arguments to the appropriate constructor, e.g.
  1305. ``datetime.date(year=1972, month=10, day=15)``, or by using one of a number of
  1306. class methods. For example, the :meth:`date.today` class method returns the
  1307. current local date.
  1308. Once created, instances of the date/time classes are all immutable. There are a
  1309. number of methods for producing formatted strings from objects::
  1310. >>> import datetime
  1311. >>> now = datetime.datetime.now()
  1312. >>> now.isoformat()
  1313. '2002-12-30T21:27:03.994956'
  1314. >>> now.ctime() # Only available on date, datetime
  1315. 'Mon Dec 30 21:27:03 2002'
  1316. >>> now.strftime('%Y %d %b')
  1317. '2002 30 Dec'
  1318. The :meth:`replace` method allows modifying one or more fields of a
  1319. :class:`date` or :class:`datetime` instance, returning a new instance::
  1320. >>> d = datetime.datetime.now()
  1321. >>> d
  1322. datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
  1323. >>> d.replace(year=2001, hour = 12)
  1324. datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
  1325. >>>
  1326. Instances can be compared, hashed, and converted to strings (the result is the
  1327. same as that of :meth:`isoformat`). :class:`date` and :class:`datetime`
  1328. instances can be subtracted from each other, and added to :class:`timedelta`
  1329. instances. The largest missing feature is that there's no standard library
  1330. support for parsing strings and getting back a :class:`date` or
  1331. :class:`datetime`.
  1332. For more information, refer to the module's reference documentation.
  1333. (Contributed by Tim Peters.)
  1334. .. ======================================================================
  1335. The optparse Module
  1336. -------------------
  1337. The :mod:`getopt` module provides simple parsing of command-line arguments. The
  1338. new :mod:`optparse` module (originally named Optik) provides more elaborate
  1339. command-line parsing that follows the Unix conventions, automatically creates
  1340. the output for :option:`--help`, and can perform different actions for different
  1341. options.
  1342. You start by creating an instance of :class:`OptionParser` and telling it what
  1343. your program's options are. ::
  1344. import sys
  1345. from optparse import OptionParser
  1346. op = OptionParser()
  1347. op.add_option('-i', '--input',
  1348. action='store', type='string', dest='input',
  1349. help='set input filename')
  1350. op.add_option('-l', '--length',
  1351. action='store', type='int', dest='length',
  1352. help='set maximum length of output')
  1353. Parsing a command line is then done by calling the :meth:`parse_args` method. ::
  1354. options, args = op.parse_args(sys.argv[1:])
  1355. print options
  1356. print args
  1357. This returns an object containing all of the option values, and a list of
  1358. strings containing the remaining arguments.
  1359. Invoking the script with the various arguments now works as you'd expect it to.
  1360. Note that the length argument is automatically converted to an integer. ::
  1361. $ ./python opt.py -i data arg1
  1362. <Values at 0x400cad4c: {'input': 'data', 'length': None}>
  1363. ['arg1']
  1364. $ ./python opt.py --input=data --length=4
  1365. <Values at 0x400cad2c: {'input': 'data', 'length': 4}>
  1366. []
  1367. $
  1368. The help message is automatically generated for you::
  1369. $ ./python opt.py --help
  1370. usage: opt.py [options]
  1371. options:
  1372. -h, --help show this help message and exit
  1373. -iINPUT, --input=INPUT
  1374. set input filename
  1375. -lLENGTH, --length=LENGTH
  1376. set maximum length of output
  1377. $
  1378. See the module's documentation for more details.
  1379. Optik was written by Greg Ward, with suggestions from the readers of the Getopt
  1380. SIG.
  1381. .. ======================================================================
  1382. .. _section-pymalloc:
  1383. Pymalloc: A Specialized Object Allocator
  1384. ========================================
  1385. Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a
  1386. feature added to Python 2.1. Pymalloc is intended to be faster than the system
  1387. :cfunc:`malloc` and to have less memory overhead for allocation patterns typical
  1388. of Python programs. The allocator uses C's :cfunc:`malloc` function to get large
  1389. pools of memory and then fulfills smaller memory requests from these pools.
  1390. In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by
  1391. default; you had to explicitly enable it when compiling Python by providing the
  1392. :option:`--with-pymalloc` option to the :program:`configure` script. In 2.3,
  1393. pymalloc has had further enhancements and is now enabled by default; you'll have
  1394. to supply :option:`--without-pymalloc` to disable it.
  1395. This change is transparent to code written in Python; however, pymalloc may
  1396. expose bugs in C extensions. Authors of C extension modules should test their
  1397. code with pymalloc enabled, because some incorrect code may cause core dumps at
  1398. runtime.
  1399. There's one particularly common error that causes problems. There are a number
  1400. of memory allocation functions in Python's C API that have previously just been
  1401. aliases for the C library's :cfunc:`malloc` and :cfunc:`free`, meaning that if
  1402. you accidentally called mismatched functions the error wouldn't be noticeable.
  1403. When the object allocator is enabled, these functions aren't aliases of
  1404. :cfunc:`malloc` and :cfunc:`free` any more, and calling the wrong function to
  1405. free memory may get you a core dump. For example, if memory was allocated using
  1406. :cfunc:`PyObject_Malloc`, it has to be freed using :cfunc:`PyObject_Free`, not
  1407. :cfunc:`free`. A few modules included with Python fell afoul of this and had to
  1408. be fixed; doubtless there are more third-party modules that will have the same
  1409. problem.
  1410. As part of this change, the confusing multiple interfaces for allocating memory
  1411. have been consolidated down into two API families. Memory allocated with one
  1412. family must not be manipulated with functions from the other family. There is
  1413. one family for allocating chunks of memory and another family of functions
  1414. specifically for allocating Python objects.
  1415. * To allocate and free an undistinguished chunk of memory use the "raw memory"
  1416. family: :cfunc:`PyMem_Malloc`, :cfunc:`PyMem_Realloc`, and :cfunc:`PyMem_Free`.
  1417. * The "object memory" family is the interface to the pymalloc facility described
  1418. above and is biased towards a large number of "small" allocations:
  1419. :cfunc:`PyObject_Malloc`, :cfunc:`PyObject_Realloc`, and :cfunc:`PyObject_Free`.
  1420. * To allocate and free Python objects, use the "object" family
  1421. :cfunc:`PyObject_New`, :cfunc:`PyObject_NewVar`, and :cfunc:`PyObject_Del`.
  1422. Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
  1423. features to catch memory overwrites and doubled frees in both extension modules
  1424. and in the interpreter itself. To enable this support, compile a debugging
  1425. version of the Python interpreter by running :program:`configure` with
  1426. :option:`--with-pydebug`.
  1427. To aid extension writers, a header file :file:`Misc/pymemcompat.h` is
  1428. distributed with the source to Python 2.3 that allows Python extensions to use
  1429. the 2.3 interfaces to memory allocation while compiling against any version of
  1430. Python since 1.5.2. You would copy the file from Python's source distribution
  1431. and bundle it with the source of your extension.
  1432. .. seealso::
  1433. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/obmalloc.c
  1434. For the full details of the pymalloc implementation, see the comments at the top
  1435. of the file :file:`Objects/obmalloc.c` in the Python source code. The above
  1436. link points to the file within the SourceForge CVS browser.
  1437. .. ======================================================================
  1438. Build and C API Changes
  1439. =======================
  1440. Changes to Python's build process and to the C API include:
  1441. * The cycle detection implementation used by the garbage collection has proven
  1442. to be stable, so it's now been made mandatory. You can no longer compile Python
  1443. without it, and the :option:`--with-cycle-gc` switch to :program:`configure` has
  1444. been removed.
  1445. * Python can now optionally be built as a shared library
  1446. (:file:`libpython2.3.so`) by supplying :option:`--enable-shared` when running
  1447. Python's :program:`configure` script. (Contributed by Ondrej Palkovsky.)
  1448. * The :cmacro:`DL_EXPORT` and :cmacro:`DL_IMPORT` macros are now deprecated.
  1449. Initialization functions for Python extension modules should now be declared
  1450. using the new macro :cmacro:`PyMODINIT_FUNC`, while the Python core will
  1451. generally use the :cmacro:`PyAPI_FUNC` and :cmacro:`PyAPI_DATA` macros.
  1452. * The interpreter can be compiled without any docstrings for the built-in
  1453. functions and modules by supplying :option:`--without-doc-strings` to the
  1454. :program:`configure` script. This makes the Python executable about 10% smaller,
  1455. but will also mean that you can't get help for Python's built-ins. (Contributed
  1456. by Gustavo Niemeyer.)
  1457. * The :cfunc:`PyArg_NoArgs` macro is now deprecated, and code that uses it
  1458. should be changed. For Python 2.2 and later, the method definition table can
  1459. specify the :const:`METH_NOARGS` flag, signalling that there are no arguments,
  1460. and the argument checking can then be removed. If compatibility with pre-2.2
  1461. versions of Python is important, the code could use ``PyArg_ParseTuple(args,
  1462. "")`` instead, but this will be slower than using :const:`METH_NOARGS`.
  1463. * :cfunc:`PyArg_ParseTuple` accepts new format characters for various sizes of
  1464. unsigned integers: ``B`` for :ctype:`unsigned char`, ``H`` for :ctype:`unsigned
  1465. short int`, ``I`` for :ctype:`unsigned int`, and ``K`` for :ctype:`unsigned
  1466. long long`.
  1467. * A new function, :cfunc:`PyObject_DelItemString(mapping, char \*key)` was added
  1468. as shorthand for ``PyObject_DelItem(mapping, PyString_New(key))``.
  1469. * File objects now manage their internal string buffer differently, increasing
  1470. it exponentially when needed. This results in the benchmark tests in
  1471. :file:`Lib/test/test_bufio.py` speeding up considerably (from 57 seconds to 1.7
  1472. seconds, according to one measurement).
  1473. * It's now possible to define class and static methods for a C extension type by
  1474. setting either the :const:`METH_CLASS` or :const:`METH_STATIC` flags in a
  1475. method's :ctype:`PyMethodDef` structure.
  1476. * Python now includes a copy of the Expat XML parser's source code, removing any
  1477. dependence on a system version or local installation of Expat.
  1478. * If you dynamically allocate type objects in your extension, you should be
  1479. aware of a change in the rules relating to the :attr:`__module__` and
  1480. :attr:`__name__` attributes. In summary, you will want to ensure the type's
  1481. dictionary contains a ``'__module__'`` key; making the module name the part of
  1482. the type name leading up to the final period will no longer have the desired
  1483. effect. For more detail, read the API reference documentation or the source.
  1484. .. ======================================================================
  1485. Port-Specific Changes
  1486. ---------------------
  1487. Support for a port to IBM's OS/2 using the EMX runtime environment was merged
  1488. into the main Python source tree. EMX is a POSIX emulation layer over the OS/2
  1489. system APIs. The Python port for EMX tries to support all the POSIX-like
  1490. capability exposed by the EMX runtime, and mostly succeeds; :func:`fork` and
  1491. :func:`fcntl` are restricted by the limitations of the underlying emulation
  1492. layer. The standard OS/2 port, which uses IBM's Visual Age compiler, also
  1493. gained support for case-sensitive import semantics as part of the integration of
  1494. the EMX port into CVS. (Contributed by Andrew MacIntyre.)
  1495. On MacOS, most toolbox modules have been weaklinked to improve backward
  1496. compatibility. This means that modules will no longer fail to load if a single
  1497. routine is missing on the current OS version. Instead calling the missing
  1498. routine will raise an exception. (Contributed by Jack Jansen.)
  1499. The RPM spec files, found in the :file:`Misc/RPM/` directory in the Python
  1500. source distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)
  1501. Other new platforms now supported by Python include AtheOS
  1502. (http://www.atheos.cx/), GNU/Hurd, and OpenVMS.
  1503. .. ======================================================================
  1504. .. _section-other:
  1505. Other Changes and Fixes
  1506. =======================
  1507. As usual, there were a bunch of other improvements and bugfixes scattered
  1508. throughout the source tree. A search through the CVS change logs finds there
  1509. were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Both
  1510. figures are likely to be underestimates.
  1511. Some of the more notable changes are:
  1512. * If the :envvar:`PYTHONINSPECT` environment variable is set, the Python
  1513. interpreter will enter the interactive prompt after running a Python program, as
  1514. if Python had been invoked with the :option:`-i` option. The environment
  1515. variable can be set before running the Python interpreter, or it can be set by
  1516. the Python program as part of its execution.
  1517. * The :file:`regrtest.py` script now provides a way to allow "all resources
  1518. except *foo*." A resource name passed to the :option:`-u` option can now be
  1519. prefixed with a hyphen (``'-'``) to mean "remove this resource." For example,
  1520. the option '``-uall,-bsddb``' could be used to enable the use of all resources
  1521. except ``bsddb``.
  1522. * The tools used to build the documentation now work under Cygwin as well as
  1523. Unix.
  1524. * The ``SET_LINENO`` opcode has been removed. Back in the mists of time, this
  1525. opcode was needed to produce line numbers in tracebacks and support trace
  1526. functions (for, e.g., :mod:`pdb`). Since Python 1.5, the line numbers in
  1527. tracebacks have been computed using a different mechanism that works with
  1528. "python -O". For Python 2.3 Michael Hudson implemented a similar scheme to
  1529. determine when to call the trace function, removing the need for ``SET_LINENO``
  1530. entirely.
  1531. It would be difficult to detect any resulting difference from Python code, apart
  1532. from a slight speed up when Python is run without :option:`-O`.
  1533. C extensions that access the :attr:`f_lineno` field of frame objects should
  1534. instead call ``PyCode_Addr2Line(f->f_code, f->f_lasti)``. This will have the
  1535. added effect of making the code work as desired under "python -O" in earlier
  1536. versions of Python.
  1537. A nifty new feature is that trace functions can now assign to the
  1538. :attr:`f_lineno` attribute of frame objects, changing the line that will be
  1539. executed next. A ``jump`` command has been added to the :mod:`pdb` debugger
  1540. taking advantage of this new feature. (Implemented by Richie Hindle.)
  1541. .. ======================================================================
  1542. Porting to Python 2.3
  1543. =====================
  1544. This section lists previously described changes that may require changes to your
  1545. code:
  1546. * :keyword:`yield` is now always a keyword; if it's used as a variable name in
  1547. your code, a different name must be chosen.
  1548. * For strings *X* and *Y*, ``X in Y`` now works if *X* is more than one
  1549. character long.
  1550. * The :func:`int` type constructor will now return a long integer instead of
  1551. raising an :exc:`OverflowError` when a string or floating-point number is too
  1552. large to fit into an integer.
  1553. * If you have Unicode strings that contain 8-bit characters, you must declare
  1554. the file's encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top
  1555. of the file. See section :ref:`section-encodings` for more information.
  1556. * Calling Tcl methods through :mod:`_tkinter` no longer returns only strings.
  1557. Instead, if Tcl returns other objects those objects are converted to their
  1558. Python equivalent, if one exists, or wrapped with a :class:`_tkinter.Tcl_Obj`
  1559. object if no Python equivalent exists.
  1560. * Large octal and hex literals such as ``0xffffffff`` now trigger a
  1561. :exc:`FutureWarning`. Currently they're stored as 32-bit numbers and result in a
  1562. negative value, but in Python 2.4 they'll become positive long integers.
  1563. There are a few ways to fix this warning. If you really need a positive number,
  1564. just add an ``L`` to the end of the literal. If you're trying to get a 32-bit
  1565. integer with low bits set and have previously used an expression such as ``~(1
  1566. << 31)``, it's probably clearest to start with all bits set and clear the
  1567. desired upper bits. For example, to clear just the top bit (bit 31), you could
  1568. write ``0xffffffffL &~(1L<<31)``.
  1569. * You can no longer disable assertions by assigning to ``__debug__``.
  1570. * The Distutils :func:`setup` function has gained various new keyword arguments
  1571. such as *depends*. Old versions of the Distutils will abort if passed unknown
  1572. keywords. A solution is to check for the presence of the new
  1573. :func:`get_distutil_options` function in your :file:`setup.py` and only uses the
  1574. new keywords with a version of the Distutils that supports them::
  1575. from distutils import core
  1576. kw = {'sources': 'foo.c', ...}
  1577. if hasattr(core, 'get_distutil_options'):
  1578. kw['depends'] = ['foo.h']
  1579. ext = Extension(**kw)
  1580. * Using ``None`` as a variable name will now result in a :exc:`SyntaxWarning`
  1581. warning.
  1582. * Names of extension types defined by the modules included with Python now
  1583. contain the module and a ``'.'`` in front of the type name.
  1584. .. ======================================================================
  1585. .. _23acks:
  1586. Acknowledgements
  1587. ================
  1588. The author would like to thank the following people for offering suggestions,
  1589. corrections and assistance with various drafts of this article: Jeff Bauer,
  1590. Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David
  1591. Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger,
  1592. Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
  1593. MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
  1594. Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
  1595. Suzi, Jason Tishler, Just van Rossum.