PageRenderTime 65ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Doc/whatsnew/2.4.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 1563 lines | 1178 code | 385 blank | 0 comment | 0 complexity | d5e320b5d99f9f3ea18cb8c91496be14 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. ****************************
  2. What's New in Python 2.4
  3. ****************************
  4. :Author: A.M. Kuchling
  5. .. |release| replace:: 1.02
  6. .. $Id: whatsnew24.tex 54632 2007-03-31 11:59:54Z georg.brandl $
  7. .. Don't write extensive text for new sections; I'll do that.
  8. .. Feel free to add commented-out reminders of things that need
  9. .. to be covered. --amk
  10. This article explains the new features in Python 2.4.1, released on March 30,
  11. 2005.
  12. Python 2.4 is a medium-sized release. It doesn't introduce as many changes as
  13. the radical Python 2.2, but introduces more features than the conservative 2.3
  14. release. The most significant new language features are function decorators and
  15. generator expressions; most other changes are to the standard library.
  16. According to the CVS change logs, there were 481 patches applied and 502 bugs
  17. fixed between Python 2.3 and 2.4. Both figures are likely to be underestimates.
  18. This article doesn't attempt to provide a complete specification of every single
  19. new feature, but instead provides a brief introduction to each feature. For
  20. full details, you should refer to the documentation for Python 2.4, such as the
  21. Python Library Reference and the Python Reference Manual. Often you will be
  22. referred to the PEP for a particular new feature for explanations of the
  23. implementation and design rationale.
  24. .. ======================================================================
  25. PEP 218: Built-In Set Objects
  26. =============================
  27. Python 2.3 introduced the :mod:`sets` module. C implementations of set data
  28. types have now been added to the Python core as two new built-in types,
  29. :func:`set(iterable)` and :func:`frozenset(iterable)`. They provide high speed
  30. operations for membership testing, for eliminating duplicates from sequences,
  31. and for mathematical operations like unions, intersections, differences, and
  32. symmetric differences. ::
  33. >>> a = set('abracadabra') # form a set from a string
  34. >>> 'z' in a # fast membership testing
  35. False
  36. >>> a # unique letters in a
  37. set(['a', 'r', 'b', 'c', 'd'])
  38. >>> ''.join(a) # convert back into a string
  39. 'arbcd'
  40. >>> b = set('alacazam') # form a second set
  41. >>> a - b # letters in a but not in b
  42. set(['r', 'd', 'b'])
  43. >>> a | b # letters in either a or b
  44. set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
  45. >>> a & b # letters in both a and b
  46. set(['a', 'c'])
  47. >>> a ^ b # letters in a or b but not both
  48. set(['r', 'd', 'b', 'm', 'z', 'l'])
  49. >>> a.add('z') # add a new element
  50. >>> a.update('wxy') # add multiple new elements
  51. >>> a
  52. set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
  53. >>> a.remove('x') # take one element out
  54. >>> a
  55. set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])
  56. The :func:`frozenset` type is an immutable version of :func:`set`. Since it is
  57. immutable and hashable, it may be used as a dictionary key or as a member of
  58. another set.
  59. The :mod:`sets` module remains in the standard library, and may be useful if you
  60. wish to subclass the :class:`Set` or :class:`ImmutableSet` classes. There are
  61. currently no plans to deprecate the module.
  62. .. seealso::
  63. :pep:`218` - Adding a Built-In Set Object Type
  64. Originally proposed by Greg Wilson and ultimately implemented by Raymond
  65. Hettinger.
  66. .. ======================================================================
  67. PEP 237: Unifying Long Integers and Integers
  68. ============================================
  69. The lengthy transition process for this PEP, begun in Python 2.2, takes another
  70. step forward in Python 2.4. In 2.3, certain integer operations that would
  71. behave differently after int/long unification triggered :exc:`FutureWarning`
  72. warnings and returned values limited to 32 or 64 bits (depending on your
  73. platform). In 2.4, these expressions no longer produce a warning and instead
  74. produce a different result that's usually a long integer.
  75. The problematic expressions are primarily left shifts and lengthy hexadecimal
  76. and octal constants. For example, ``2 << 32`` results in a warning in 2.3,
  77. evaluating to 0 on 32-bit platforms. In Python 2.4, this expression now returns
  78. the correct answer, 8589934592.
  79. .. seealso::
  80. :pep:`237` - Unifying Long Integers and Integers
  81. Original PEP written by Moshe Zadka and GvR. The changes for 2.4 were
  82. implemented by Kalle Svensson.
  83. .. ======================================================================
  84. PEP 289: Generator Expressions
  85. ==============================
  86. The iterator feature introduced in Python 2.2 and the :mod:`itertools` module
  87. make it easier to write programs that loop through large data sets without
  88. having the entire data set in memory at one time. List comprehensions don't fit
  89. into this picture very well because they produce a Python list object containing
  90. all of the items. This unavoidably pulls all of the objects into memory, which
  91. can be a problem if your data set is very large. When trying to write a
  92. functionally-styled program, it would be natural to write something like::
  93. links = [link for link in get_all_links() if not link.followed]
  94. for link in links:
  95. ...
  96. instead of ::
  97. for link in get_all_links():
  98. if link.followed:
  99. continue
  100. ...
  101. The first form is more concise and perhaps more readable, but if you're dealing
  102. with a large number of link objects you'd have to write the second form to avoid
  103. having all link objects in memory at the same time.
  104. Generator expressions work similarly to list comprehensions but don't
  105. materialize the entire list; instead they create a generator that will return
  106. elements one by one. The above example could be written as::
  107. links = (link for link in get_all_links() if not link.followed)
  108. for link in links:
  109. ...
  110. Generator expressions always have to be written inside parentheses, as in the
  111. above example. The parentheses signalling a function call also count, so if you
  112. want to create an iterator that will be immediately passed to a function you
  113. could write::
  114. print sum(obj.count for obj in list_all_objects())
  115. Generator expressions differ from list comprehensions in various small ways.
  116. Most notably, the loop variable (*obj* in the above example) is not accessible
  117. outside of the generator expression. List comprehensions leave the variable
  118. assigned to its last value; future versions of Python will change this, making
  119. list comprehensions match generator expressions in this respect.
  120. .. seealso::
  121. :pep:`289` - Generator Expressions
  122. Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts
  123. steered by Hye-Shik Chang.
  124. .. ======================================================================
  125. PEP 292: Simpler String Substitutions
  126. =====================================
  127. Some new classes in the standard library provide an alternative mechanism for
  128. substituting variables into strings; this style of substitution may be better
  129. for applications where untrained users need to edit templates.
  130. The usual way of substituting variables by name is the ``%`` operator::
  131. >>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
  132. '2: The Best of Times'
  133. When writing the template string, it can be easy to forget the ``i`` or ``s``
  134. after the closing parenthesis. This isn't a big problem if the template is in a
  135. Python module, because you run the code, get an "Unsupported format character"
  136. :exc:`ValueError`, and fix the problem. However, consider an application such
  137. as Mailman where template strings or translations are being edited by users who
  138. aren't aware of the Python language. The format string's syntax is complicated
  139. to explain to such users, and if they make a mistake, it's difficult to provide
  140. helpful feedback to them.
  141. PEP 292 adds a :class:`Template` class to the :mod:`string` module that uses
  142. ``$`` to indicate a substitution::
  143. >>> import string
  144. >>> t = string.Template('$page: $title')
  145. >>> t.substitute({'page':2, 'title': 'The Best of Times'})
  146. '2: The Best of Times'
  147. If a key is missing from the dictionary, the :meth:`substitute` method will
  148. raise a :exc:`KeyError`. There's also a :meth:`safe_substitute` method that
  149. ignores missing keys::
  150. >>> t = string.Template('$page: $title')
  151. >>> t.safe_substitute({'page':3})
  152. '3: $title'
  153. .. seealso::
  154. :pep:`292` - Simpler String Substitutions
  155. Written and implemented by Barry Warsaw.
  156. .. ======================================================================
  157. PEP 318: Decorators for Functions and Methods
  158. =============================================
  159. Python 2.2 extended Python's object model by adding static methods and class
  160. methods, but it didn't extend Python's syntax to provide any new way of defining
  161. static or class methods. Instead, you had to write a :keyword:`def` statement
  162. in the usual way, and pass the resulting method to a :func:`staticmethod` or
  163. :func:`classmethod` function that would wrap up the function as a method of the
  164. new type. Your code would look like this::
  165. class C:
  166. def meth (cls):
  167. ...
  168. meth = classmethod(meth) # Rebind name to wrapped-up class method
  169. If the method was very long, it would be easy to miss or forget the
  170. :func:`classmethod` invocation after the function body.
  171. The intention was always to add some syntax to make such definitions more
  172. readable, but at the time of 2.2's release a good syntax was not obvious. Today
  173. a good syntax *still* isn't obvious but users are asking for easier access to
  174. the feature; a new syntactic feature has been added to meet this need.
  175. The new feature is called "function decorators". The name comes from the idea
  176. that :func:`classmethod`, :func:`staticmethod`, and friends are storing
  177. additional information on a function object; they're *decorating* functions with
  178. more details.
  179. The notation borrows from Java and uses the ``'@'`` character as an indicator.
  180. Using the new syntax, the example above would be written::
  181. class C:
  182. @classmethod
  183. def meth (cls):
  184. ...
  185. The ``@classmethod`` is shorthand for the ``meth=classmethod(meth)`` assignment.
  186. More generally, if you have the following::
  187. @A
  188. @B
  189. @C
  190. def f ():
  191. ...
  192. It's equivalent to the following pre-decorator code::
  193. def f(): ...
  194. f = A(B(C(f)))
  195. Decorators must come on the line before a function definition, one decorator per
  196. line, and can't be on the same line as the def statement, meaning that ``@A def
  197. f(): ...`` is illegal. You can only decorate function definitions, either at
  198. the module level or inside a class; you can't decorate class definitions.
  199. A decorator is just a function that takes the function to be decorated as an
  200. argument and returns either the same function or some new object. The return
  201. value of the decorator need not be callable (though it typically is), unless
  202. further decorators will be applied to the result. It's easy to write your own
  203. decorators. The following simple example just sets an attribute on the function
  204. object::
  205. >>> def deco(func):
  206. ... func.attr = 'decorated'
  207. ... return func
  208. ...
  209. >>> @deco
  210. ... def f(): pass
  211. ...
  212. >>> f
  213. <function f at 0x402ef0d4>
  214. >>> f.attr
  215. 'decorated'
  216. >>>
  217. As a slightly more realistic example, the following decorator checks that the
  218. supplied argument is an integer::
  219. def require_int (func):
  220. def wrapper (arg):
  221. assert isinstance(arg, int)
  222. return func(arg)
  223. return wrapper
  224. @require_int
  225. def p1 (arg):
  226. print arg
  227. @require_int
  228. def p2(arg):
  229. print arg*2
  230. An example in :pep:`318` contains a fancier version of this idea that lets you
  231. both specify the required type and check the returned type.
  232. Decorator functions can take arguments. If arguments are supplied, your
  233. decorator function is called with only those arguments and must return a new
  234. decorator function; this function must take a single function and return a
  235. function, as previously described. In other words, ``@A @B @C(args)`` becomes::
  236. def f(): ...
  237. _deco = C(args)
  238. f = A(B(_deco(f)))
  239. Getting this right can be slightly brain-bending, but it's not too difficult.
  240. A small related change makes the :attr:`func_name` attribute of functions
  241. writable. This attribute is used to display function names in tracebacks, so
  242. decorators should change the name of any new function that's constructed and
  243. returned.
  244. .. seealso::
  245. :pep:`318` - Decorators for Functions, Methods and Classes
  246. Written by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people
  247. wrote patches implementing function decorators, but the one that was actually
  248. checked in was patch #979728, written by Mark Russell.
  249. http://www.python.org/moin/PythonDecoratorLibrary
  250. This Wiki page contains several examples of decorators.
  251. .. ======================================================================
  252. PEP 322: Reverse Iteration
  253. ==========================
  254. A new built-in function, :func:`reversed(seq)`, takes a sequence and returns an
  255. iterator that loops over the elements of the sequence in reverse order. ::
  256. >>> for i in reversed(xrange(1,4)):
  257. ... print i
  258. ...
  259. 3
  260. 2
  261. 1
  262. Compared to extended slicing, such as ``range(1,4)[::-1]``, :func:`reversed` is
  263. easier to read, runs faster, and uses substantially less memory.
  264. Note that :func:`reversed` only accepts sequences, not arbitrary iterators. If
  265. you want to reverse an iterator, first convert it to a list with :func:`list`.
  266. ::
  267. >>> input = open('/etc/passwd', 'r')
  268. >>> for line in reversed(list(input)):
  269. ... print line
  270. ...
  271. root:*:0:0:System Administrator:/var/root:/bin/tcsh
  272. ...
  273. .. seealso::
  274. :pep:`322` - Reverse Iteration
  275. Written and implemented by Raymond Hettinger.
  276. .. ======================================================================
  277. PEP 324: New subprocess Module
  278. ==============================
  279. The standard library provides a number of ways to execute a subprocess, offering
  280. different features and different levels of complexity.
  281. :func:`os.system(command)` is easy to use, but slow (it runs a shell process
  282. which executes the command) and dangerous (you have to be careful about escaping
  283. the shell's metacharacters). The :mod:`popen2` module offers classes that can
  284. capture standard output and standard error from the subprocess, but the naming
  285. is confusing. The :mod:`subprocess` module cleans this up, providing a unified
  286. interface that offers all the features you might need.
  287. Instead of :mod:`popen2`'s collection of classes, :mod:`subprocess` contains a
  288. single class called :class:`Popen` whose constructor supports a number of
  289. different keyword arguments. ::
  290. class Popen(args, bufsize=0, executable=None,
  291. stdin=None, stdout=None, stderr=None,
  292. preexec_fn=None, close_fds=False, shell=False,
  293. cwd=None, env=None, universal_newlines=False,
  294. startupinfo=None, creationflags=0):
  295. *args* is commonly a sequence of strings that will be the arguments to the
  296. program executed as the subprocess. (If the *shell* argument is true, *args*
  297. can be a string which will then be passed on to the shell for interpretation,
  298. just as :func:`os.system` does.)
  299. *stdin*, *stdout*, and *stderr* specify what the subprocess's input, output, and
  300. error streams will be. You can provide a file object or a file descriptor, or
  301. you can use the constant ``subprocess.PIPE`` to create a pipe between the
  302. subprocess and the parent.
  303. The constructor has a number of handy options:
  304. * *close_fds* requests that all file descriptors be closed before running the
  305. subprocess.
  306. * *cwd* specifies the working directory in which the subprocess will be executed
  307. (defaulting to whatever the parent's working directory is).
  308. * *env* is a dictionary specifying environment variables.
  309. * *preexec_fn* is a function that gets called before the child is started.
  310. * *universal_newlines* opens the child's input and output using Python's
  311. universal newline feature.
  312. Once you've created the :class:`Popen` instance, you can call its :meth:`wait`
  313. method to pause until the subprocess has exited, :meth:`poll` to check if it's
  314. exited without pausing, or :meth:`communicate(data)` to send the string *data*
  315. to the subprocess's standard input. :meth:`communicate(data)` then reads any
  316. data that the subprocess has sent to its standard output or standard error,
  317. returning a tuple ``(stdout_data, stderr_data)``.
  318. :func:`call` is a shortcut that passes its arguments along to the :class:`Popen`
  319. constructor, waits for the command to complete, and returns the status code of
  320. the subprocess. It can serve as a safer analog to :func:`os.system`::
  321. sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
  322. if sts == 0:
  323. # Success
  324. ...
  325. else:
  326. # dpkg returned an error
  327. ...
  328. The command is invoked without use of the shell. If you really do want to use
  329. the shell, you can add ``shell=True`` as a keyword argument and provide a string
  330. instead of a sequence::
  331. sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)
  332. The PEP takes various examples of shell and Python code and shows how they'd be
  333. translated into Python code that uses :mod:`subprocess`. Reading this section
  334. of the PEP is highly recommended.
  335. .. seealso::
  336. :pep:`324` - subprocess - New process module
  337. Written and implemented by Peter Ă…strand, with assistance from Fredrik Lundh and
  338. others.
  339. .. ======================================================================
  340. PEP 327: Decimal Data Type
  341. ==========================
  342. Python has always supported floating-point (FP) numbers, based on the underlying
  343. C :ctype:`double` type, as a data type. However, while most programming
  344. languages provide a floating-point type, many people (even programmers) are
  345. unaware that floating-point numbers don't represent certain decimal fractions
  346. accurately. The new :class:`Decimal` type can represent these fractions
  347. accurately, up to a user-specified precision limit.
  348. Why is Decimal needed?
  349. ----------------------
  350. The limitations arise from the representation used for floating-point numbers.
  351. FP numbers are made up of three components:
  352. * The sign, which is positive or negative.
  353. * The mantissa, which is a single-digit binary number followed by a fractional
  354. part. For example, ``1.01`` in base-2 notation is ``1 + 0/2 + 1/4``, or 1.25 in
  355. decimal notation.
  356. * The exponent, which tells where the decimal point is located in the number
  357. represented.
  358. For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in
  359. binary), and an exponent of 0 (the decimal point doesn't need to be shifted).
  360. The number 5 has the same sign and mantissa, but the exponent is 2 because the
  361. mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 \* 4 equals
  362. 5.
  363. Modern systems usually provide floating-point support that conforms to a
  364. standard called IEEE 754. C's :ctype:`double` type is usually implemented as a
  365. 64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This
  366. means that numbers can only be specified to 52 bits of precision. If you're
  367. trying to represent numbers whose expansion repeats endlessly, the expansion is
  368. cut off after 52 bits. Unfortunately, most software needs to produce output in
  369. base 10, and common fractions in base 10 are often repeating decimals in binary.
  370. For example, 1.1 decimal is binary ``1.0001100110011 ...``; .1 = 1/16 + 1/32 +
  371. 1/256 plus an infinite number of additional terms. IEEE 754 has to chop off
  372. that infinitely repeated decimal after 52 digits, so the representation is
  373. slightly inaccurate.
  374. Sometimes you can see this inaccuracy when the number is printed::
  375. >>> 1.1
  376. 1.1000000000000001
  377. The inaccuracy isn't always visible when you print the number because the FP-to-
  378. decimal-string conversion is provided by the C library, and most C libraries try
  379. to produce sensible output. Even if it's not displayed, however, the inaccuracy
  380. is still there and subsequent operations can magnify the error.
  381. For many applications this doesn't matter. If I'm plotting points and
  382. displaying them on my monitor, the difference between 1.1 and 1.1000000000000001
  383. is too small to be visible. Reports often limit output to a certain number of
  384. decimal places, and if you round the number to two or three or even eight
  385. decimal places, the error is never apparent. However, for applications where it
  386. does matter, it's a lot of work to implement your own custom arithmetic
  387. routines.
  388. Hence, the :class:`Decimal` type was created.
  389. The :class:`Decimal` type
  390. -------------------------
  391. A new module, :mod:`decimal`, was added to Python's standard library. It
  392. contains two classes, :class:`Decimal` and :class:`Context`. :class:`Decimal`
  393. instances represent numbers, and :class:`Context` instances are used to wrap up
  394. various settings such as the precision and default rounding mode.
  395. :class:`Decimal` instances are immutable, like regular Python integers and FP
  396. numbers; once it's been created, you can't change the value an instance
  397. represents. :class:`Decimal` instances can be created from integers or
  398. strings::
  399. >>> import decimal
  400. >>> decimal.Decimal(1972)
  401. Decimal("1972")
  402. >>> decimal.Decimal("1.1")
  403. Decimal("1.1")
  404. You can also provide tuples containing the sign, the mantissa represented as a
  405. tuple of decimal digits, and the exponent::
  406. >>> decimal.Decimal((1, (1, 4, 7, 5), -2))
  407. Decimal("-14.75")
  408. Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is
  409. negative.
  410. Converting from floating-point numbers poses a bit of a problem: should the FP
  411. number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1
  412. plus whatever inaccuracies are introduced? The decision was to dodge the issue
  413. and leave such a conversion out of the API. Instead, you should convert the
  414. floating-point number into a string using the desired precision and pass the
  415. string to the :class:`Decimal` constructor::
  416. >>> f = 1.1
  417. >>> decimal.Decimal(str(f))
  418. Decimal("1.1")
  419. >>> decimal.Decimal('%.12f' % f)
  420. Decimal("1.100000000000")
  421. Once you have :class:`Decimal` instances, you can perform the usual mathematical
  422. operations on them. One limitation: exponentiation requires an integer
  423. exponent::
  424. >>> a = decimal.Decimal('35.72')
  425. >>> b = decimal.Decimal('1.73')
  426. >>> a+b
  427. Decimal("37.45")
  428. >>> a-b
  429. Decimal("33.99")
  430. >>> a*b
  431. Decimal("61.7956")
  432. >>> a/b
  433. Decimal("20.64739884393063583815028902")
  434. >>> a ** 2
  435. Decimal("1275.9184")
  436. >>> a**b
  437. Traceback (most recent call last):
  438. ...
  439. decimal.InvalidOperation: x ** (non-integer)
  440. You can combine :class:`Decimal` instances with integers, but not with floating-
  441. point numbers::
  442. >>> a + 4
  443. Decimal("39.72")
  444. >>> a + 4.5
  445. Traceback (most recent call last):
  446. ...
  447. TypeError: You can interact Decimal only with int, long or Decimal data types.
  448. >>>
  449. :class:`Decimal` numbers can be used with the :mod:`math` and :mod:`cmath`
  450. modules, but note that they'll be immediately converted to floating-point
  451. numbers before the operation is performed, resulting in a possible loss of
  452. precision and accuracy. You'll also get back a regular floating-point number
  453. and not a :class:`Decimal`. ::
  454. >>> import math, cmath
  455. >>> d = decimal.Decimal('123456789012.345')
  456. >>> math.sqrt(d)
  457. 351364.18288201344
  458. >>> cmath.sqrt(-d)
  459. 351364.18288201344j
  460. :class:`Decimal` instances have a :meth:`sqrt` method that returns a
  461. :class:`Decimal`, but if you need other things such as trigonometric functions
  462. you'll have to implement them. ::
  463. >>> d.sqrt()
  464. Decimal("351364.1828820134592177245001")
  465. The :class:`Context` type
  466. -------------------------
  467. Instances of the :class:`Context` class encapsulate several settings for
  468. decimal operations:
  469. * :attr:`prec` is the precision, the number of decimal places.
  470. * :attr:`rounding` specifies the rounding mode. The :mod:`decimal` module has
  471. constants for the various possibilities: :const:`ROUND_DOWN`,
  472. :const:`ROUND_CEILING`, :const:`ROUND_HALF_EVEN`, and various others.
  473. * :attr:`traps` is a dictionary specifying what happens on encountering certain
  474. error conditions: either an exception is raised or a value is returned. Some
  475. examples of error conditions are division by zero, loss of precision, and
  476. overflow.
  477. There's a thread-local default context available by calling :func:`getcontext`;
  478. you can change the properties of this context to alter the default precision,
  479. rounding, or trap handling. The following example shows the effect of changing
  480. the precision of the default context::
  481. >>> decimal.getcontext().prec
  482. 28
  483. >>> decimal.Decimal(1) / decimal.Decimal(7)
  484. Decimal("0.1428571428571428571428571429")
  485. >>> decimal.getcontext().prec = 9
  486. >>> decimal.Decimal(1) / decimal.Decimal(7)
  487. Decimal("0.142857143")
  488. The default action for error conditions is selectable; the module can either
  489. return a special value such as infinity or not-a-number, or exceptions can be
  490. raised::
  491. >>> decimal.Decimal(1) / decimal.Decimal(0)
  492. Traceback (most recent call last):
  493. ...
  494. decimal.DivisionByZero: x / 0
  495. >>> decimal.getcontext().traps[decimal.DivisionByZero] = False
  496. >>> decimal.Decimal(1) / decimal.Decimal(0)
  497. Decimal("Infinity")
  498. >>>
  499. The :class:`Context` instance also has various methods for formatting numbers
  500. such as :meth:`to_eng_string` and :meth:`to_sci_string`.
  501. For more information, see the documentation for the :mod:`decimal` module, which
  502. includes a quick-start tutorial and a reference.
  503. .. seealso::
  504. :pep:`327` - Decimal Data Type
  505. Written by Facundo Batista and implemented by Facundo Batista, Eric Price,
  506. Raymond Hettinger, Aahz, and Tim Peters.
  507. http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
  508. A more detailed overview of the IEEE-754 representation.
  509. http://www.lahey.com/float.htm
  510. The article uses Fortran code to illustrate many of the problems that floating-
  511. point inaccuracy can cause.
  512. http://www2.hursley.ibm.com/decimal/
  513. A description of a decimal-based representation. This representation is being
  514. proposed as a standard, and underlies the new Python decimal type. Much of this
  515. material was written by Mike Cowlishaw, designer of the Rexx language.
  516. .. ======================================================================
  517. PEP 328: Multi-line Imports
  518. ===========================
  519. One language change is a small syntactic tweak aimed at making it easier to
  520. import many names from a module. In a ``from module import names`` statement,
  521. *names* is a sequence of names separated by commas. If the sequence is very
  522. long, you can either write multiple imports from the same module, or you can use
  523. backslashes to escape the line endings like this::
  524. from SimpleXMLRPCServer import SimpleXMLRPCServer,\
  525. SimpleXMLRPCRequestHandler,\
  526. CGIXMLRPCRequestHandler,\
  527. resolve_dotted_attribute
  528. The syntactic change in Python 2.4 simply allows putting the names within
  529. parentheses. Python ignores newlines within a parenthesized expression, so the
  530. backslashes are no longer needed::
  531. from SimpleXMLRPCServer import (SimpleXMLRPCServer,
  532. SimpleXMLRPCRequestHandler,
  533. CGIXMLRPCRequestHandler,
  534. resolve_dotted_attribute)
  535. The PEP also proposes that all :keyword:`import` statements be absolute imports,
  536. with a leading ``.`` character to indicate a relative import. This part of the
  537. PEP was not implemented for Python 2.4, but was completed for Python 2.5.
  538. .. seealso::
  539. :pep:`328` - Imports: Multi-Line and Absolute/Relative
  540. Written by Aahz. Multi-line imports were implemented by Dima Dorfman.
  541. .. ======================================================================
  542. PEP 331: Locale-Independent Float/String Conversions
  543. ====================================================
  544. The :mod:`locale` modules lets Python software select various conversions and
  545. display conventions that are localized to a particular country or language.
  546. However, the module was careful to not change the numeric locale because various
  547. functions in Python's implementation required that the numeric locale remain set
  548. to the ``'C'`` locale. Often this was because the code was using the C
  549. library's :cfunc:`atof` function.
  550. Not setting the numeric locale caused trouble for extensions that used third-
  551. party C libraries, however, because they wouldn't have the correct locale set.
  552. The motivating example was GTK+, whose user interface widgets weren't displaying
  553. numbers in the current locale.
  554. The solution described in the PEP is to add three new functions to the Python
  555. API that perform ASCII-only conversions, ignoring the locale setting:
  556. * :cfunc:`PyOS_ascii_strtod(str, ptr)` and :cfunc:`PyOS_ascii_atof(str, ptr)`
  557. both convert a string to a C :ctype:`double`.
  558. * :cfunc:`PyOS_ascii_formatd(buffer, buf_len, format, d)` converts a
  559. :ctype:`double` to an ASCII string.
  560. The code for these functions came from the GLib library
  561. (http://developer.gnome.org/arch/gtk/glib.html), whose developers kindly
  562. relicensed the relevant functions and donated them to the Python Software
  563. Foundation. The :mod:`locale` module can now change the numeric locale,
  564. letting extensions such as GTK+ produce the correct results.
  565. .. seealso::
  566. :pep:`331` - Locale-Independent Float/String Conversions
  567. Written by Christian R. Reis, and implemented by Gustavo Carneiro.
  568. .. ======================================================================
  569. Other Language Changes
  570. ======================
  571. Here are all of the changes that Python 2.4 makes to the core Python language.
  572. * Decorators for functions and methods were added (:pep:`318`).
  573. * Built-in :func:`set` and :func:`frozenset` types were added (:pep:`218`).
  574. Other new built-ins include the :func:`reversed(seq)` function (:pep:`322`).
  575. * Generator expressions were added (:pep:`289`).
  576. * Certain numeric expressions no longer return values restricted to 32 or 64
  577. bits (:pep:`237`).
  578. * You can now put parentheses around the list of names in a ``from module import
  579. names`` statement (:pep:`328`).
  580. * The :meth:`dict.update` method now accepts the same argument forms as the
  581. :class:`dict` constructor. This includes any mapping, any iterable of key/value
  582. pairs, and keyword arguments. (Contributed by Raymond Hettinger.)
  583. * The string methods :meth:`ljust`, :meth:`rjust`, and :meth:`center` now take
  584. an optional argument for specifying a fill character other than a space.
  585. (Contributed by Raymond Hettinger.)
  586. * Strings also gained an :meth:`rsplit` method that works like the :meth:`split`
  587. method but splits from the end of the string. (Contributed by Sean
  588. Reifschneider.) ::
  589. >>> 'www.python.org'.split('.', 1)
  590. ['www', 'python.org']
  591. 'www.python.org'.rsplit('.', 1)
  592. ['www.python', 'org']
  593. * Three keyword parameters, *cmp*, *key*, and *reverse*, were added to the
  594. :meth:`sort` method of lists. These parameters make some common usages of
  595. :meth:`sort` simpler. All of these parameters are optional.
  596. For the *cmp* parameter, the value should be a comparison function that takes
  597. two parameters and returns -1, 0, or +1 depending on how the parameters compare.
  598. This function will then be used to sort the list. Previously this was the only
  599. parameter that could be provided to :meth:`sort`.
  600. *key* should be a single-parameter function that takes a list element and
  601. returns a comparison key for the element. The list is then sorted using the
  602. comparison keys. The following example sorts a list case-insensitively::
  603. >>> L = ['A', 'b', 'c', 'D']
  604. >>> L.sort() # Case-sensitive sort
  605. >>> L
  606. ['A', 'D', 'b', 'c']
  607. >>> # Using 'key' parameter to sort list
  608. >>> L.sort(key=lambda x: x.lower())
  609. >>> L
  610. ['A', 'b', 'c', 'D']
  611. >>> # Old-fashioned way
  612. >>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
  613. >>> L
  614. ['A', 'b', 'c', 'D']
  615. The last example, which uses the *cmp* parameter, is the old way to perform a
  616. case-insensitive sort. It works but is slower than using a *key* parameter.
  617. Using *key* calls :meth:`lower` method once for each element in the list while
  618. using *cmp* will call it twice for each comparison, so using *key* saves on
  619. invocations of the :meth:`lower` method.
  620. For simple key functions and comparison functions, it is often possible to avoid
  621. a :keyword:`lambda` expression by using an unbound method instead. For example,
  622. the above case-insensitive sort is best written as::
  623. >>> L.sort(key=str.lower)
  624. >>> L
  625. ['A', 'b', 'c', 'D']
  626. Finally, the *reverse* parameter takes a Boolean value. If the value is true,
  627. the list will be sorted into reverse order. Instead of ``L.sort() ;
  628. L.reverse()``, you can now write ``L.sort(reverse=True)``.
  629. The results of sorting are now guaranteed to be stable. This means that two
  630. entries with equal keys will be returned in the same order as they were input.
  631. For example, you can sort a list of people by name, and then sort the list by
  632. age, resulting in a list sorted by age where people with the same age are in
  633. name-sorted order.
  634. (All changes to :meth:`sort` contributed by Raymond Hettinger.)
  635. * There is a new built-in function :func:`sorted(iterable)` that works like the
  636. in-place :meth:`list.sort` method but can be used in expressions. The
  637. differences are:
  638. * the input may be any iterable;
  639. * a newly formed copy is sorted, leaving the original intact; and
  640. * the expression returns the new sorted copy
  641. ::
  642. >>> L = [9,7,8,3,2,4,1,6,5]
  643. >>> [10+i for i in sorted(L)] # usable in a list comprehension
  644. [11, 12, 13, 14, 15, 16, 17, 18, 19]
  645. >>> L # original is left unchanged
  646. [9,7,8,3,2,4,1,6,5]
  647. >>> sorted('Monty Python') # any iterable may be an input
  648. [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']
  649. >>> # List the contents of a dict sorted by key values
  650. >>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
  651. >>> for k, v in sorted(colormap.iteritems()):
  652. ... print k, v
  653. ...
  654. black 4
  655. blue 2
  656. green 3
  657. red 1
  658. yellow 5
  659. (Contributed by Raymond Hettinger.)
  660. * Integer operations will no longer trigger an :exc:`OverflowWarning`. The
  661. :exc:`OverflowWarning` warning will disappear in Python 2.5.
  662. * The interpreter gained a new switch, :option:`-m`, that takes a name, searches
  663. for the corresponding module on ``sys.path``, and runs the module as a script.
  664. For example, you can now run the Python profiler with ``python -m profile``.
  665. (Contributed by Nick Coghlan.)
  666. * The :func:`eval(expr, globals, locals)` and :func:`execfile(filename, globals,
  667. locals)` functions and the :keyword:`exec` statement now accept any mapping type
  668. for the *locals* parameter. Previously this had to be a regular Python
  669. dictionary. (Contributed by Raymond Hettinger.)
  670. * The :func:`zip` built-in function and :func:`itertools.izip` now return an
  671. empty list if called with no arguments. Previously they raised a
  672. :exc:`TypeError` exception. This makes them more suitable for use with variable
  673. length argument lists::
  674. >>> def transpose(array):
  675. ... return zip(*array)
  676. ...
  677. >>> transpose([(1,2,3), (4,5,6)])
  678. [(1, 4), (2, 5), (3, 6)]
  679. >>> transpose([])
  680. []
  681. (Contributed by Raymond Hettinger.)
  682. * Encountering a failure while importing a module no longer leaves a partially-
  683. initialized module object in ``sys.modules``. The incomplete module object left
  684. behind would fool further imports of the same module into succeeding, leading to
  685. confusing errors. (Fixed by Tim Peters.)
  686. * :const:`None` is now a constant; code that binds a new value to the name
  687. ``None`` is now a syntax error. (Contributed by Raymond Hettinger.)
  688. .. ======================================================================
  689. Optimizations
  690. -------------
  691. * The inner loops for list and tuple slicing were optimized and now run about
  692. one-third faster. The inner loops for dictionaries were also optimized,
  693. resulting in performance boosts for :meth:`keys`, :meth:`values`, :meth:`items`,
  694. :meth:`iterkeys`, :meth:`itervalues`, and :meth:`iteritems`. (Contributed by
  695. Raymond Hettinger.)
  696. * The machinery for growing and shrinking lists was optimized for speed and for
  697. space efficiency. Appending and popping from lists now runs faster due to more
  698. efficient code paths and less frequent use of the underlying system
  699. :cfunc:`realloc`. List comprehensions also benefit. :meth:`list.extend` was
  700. also optimized and no longer converts its argument into a temporary list before
  701. extending the base list. (Contributed by Raymond Hettinger.)
  702. * :func:`list`, :func:`tuple`, :func:`map`, :func:`filter`, and :func:`zip` now
  703. run several times faster with non-sequence arguments that supply a
  704. :meth:`__len__` method. (Contributed by Raymond Hettinger.)
  705. * The methods :meth:`list.__getitem__`, :meth:`dict.__getitem__`, and
  706. :meth:`dict.__contains__` are are now implemented as :class:`method_descriptor`
  707. objects rather than :class:`wrapper_descriptor` objects. This form of access
  708. doubles their performance and makes them more suitable for use as arguments to
  709. functionals: ``map(mydict.__getitem__, keylist)``. (Contributed by Raymond
  710. Hettinger.)
  711. * Added a new opcode, ``LIST_APPEND``, that simplifies the generated bytecode
  712. for list comprehensions and speeds them up by about a third. (Contributed by
  713. Raymond Hettinger.)
  714. * The peephole bytecode optimizer has been improved to produce shorter, faster
  715. bytecode; remarkably, the resulting bytecode is more readable. (Enhanced by
  716. Raymond Hettinger.)
  717. * String concatenations in statements of the form ``s = s + "abc"`` and ``s +=
  718. "abc"`` are now performed more efficiently in certain circumstances. This
  719. optimization won't be present in other Python implementations such as Jython, so
  720. you shouldn't rely on it; using the :meth:`join` method of strings is still
  721. recommended when you want to efficiently glue a large number of strings
  722. together. (Contributed by Armin Rigo.)
  723. The net result of the 2.4 optimizations is that Python 2.4 runs the pystone
  724. benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2.
  725. (pystone is not a particularly good benchmark, but it's the most commonly used
  726. measurement of Python's performance. Your own applications may show greater or
  727. smaller benefits from Python 2.4.)
  728. .. pystone is almost useless for comparing different versions of Python;
  729. instead, it excels at predicting relative Python performance on different
  730. machines. So, this section would be more informative if it used other tools
  731. such as pybench and parrotbench. For a more application oriented benchmark,
  732. try comparing the timings of test_decimal.py under 2.3 and 2.4.
  733. .. ======================================================================
  734. New, Improved, and Deprecated Modules
  735. =====================================
  736. As usual, Python's standard library received a number of enhancements and bug
  737. fixes. Here's a partial list of the most notable changes, sorted alphabetically
  738. by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
  739. complete list of changes, or look through the CVS logs for all the details.
  740. * The :mod:`asyncore` module's :func:`loop` function now has a *count* parameter
  741. that lets you perform a limited number of passes through the polling loop. The
  742. default is still to loop forever.
  743. * The :mod:`base64` module now has more complete RFC 3548 support for Base64,
  744. Base32, and Base16 encoding and decoding, including optional case folding and
  745. optional alternative alphabets. (Contributed by Barry Warsaw.)
  746. * The :mod:`bisect` module now has an underlying C implementation for improved
  747. performance. (Contributed by Dmitry Vasiliev.)
  748. * The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang,
  749. was integrated into 2.4. The new encodings are:
  750. * Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz
  751. * Chinese (ROC): big5, cp950
  752. * Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,
  753. iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
  754. shift-jis, shift-jisx0213, shift-jis-2004
  755. * Korean: cp949, euc-kr, johab, iso-2022-kr
  756. * Some other new encodings were added: HP Roman8, ISO_8859-11, ISO_8859-16,
  757. PCTP-154, and TIS-620.
  758. * The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
  759. Previously the :class:`StreamReader` class would try to read more data, making
  760. it impossible to resume decoding from the stream. The :meth:`read` method will
  761. now return as much data as it can and future calls will resume decoding where
  762. previous ones left off. (Implemented by Walter Dörwald.)
  763. * There is a new :mod:`collections` module for various specialized collection
  764. datatypes. Currently it contains just one type, :class:`deque`, a double-
  765. ended queue that supports efficiently adding and removing elements from either
  766. end::
  767. >>> from collections import deque
  768. >>> d = deque('ghi') # make a new deque with three items
  769. >>> d.append('j') # add a new entry to the right side
  770. >>> d.appendleft('f') # add a new entry to the left side
  771. >>> d # show the representation of the deque
  772. deque(['f', 'g', 'h', 'i', 'j'])
  773. >>> d.pop() # return and remove the rightmost item
  774. 'j'
  775. >>> d.popleft() # return and remove the leftmost item
  776. 'f'
  777. >>> list(d) # list the contents of the deque
  778. ['g', 'h', 'i']
  779. >>> 'h' in d # search the deque
  780. True
  781. Several modules, such as the :mod:`Queue` and :mod:`threading` modules, now take
  782. advantage of :class:`collections.deque` for improved performance. (Contributed
  783. by Raymond Hettinger.)
  784. * The :mod:`ConfigParser` classes have been enhanced slightly. The :meth:`read`
  785. method now returns a list of the files that were successfully parsed, and the
  786. :meth:`set` method raises :exc:`TypeError` if passed a *value* argument that
  787. isn't a string. (Contributed by John Belmonte and David Goodger.)
  788. * The :mod:`curses` module now supports the ncurses extension
  789. :func:`use_default_colors`. On platforms where the terminal supports
  790. transparency, this makes it possible to use a transparent background.
  791. (Contributed by Jörg Lehmann.)
  792. * The :mod:`difflib` module now includes an :class:`HtmlDiff` class that creates
  793. an HTML table showing a side by side comparison of two versions of a text.
  794. (Contributed by Dan Gass.)
  795. * The :mod:`email` package was updated to version 3.0, which dropped various
  796. deprecated APIs and removes support for Python versions earlier than 2.3. The
  797. 3.0 version of the package uses a new incremental parser for MIME messages,
  798. available in the :mod:`email.FeedParser` module. The new parser doesn't require
  799. reading the entire message into memory, and doesn't throw exceptions if a
  800. message is malformed; instead it records any problems in the :attr:`defect`
  801. attribute of the message. (Developed by Anthony Baxter, Barry Warsaw, Thomas
  802. Wouters, and others.)
  803. * The :mod:`heapq` module has been converted to C. The resulting tenfold
  804. improvement in speed makes the module suitable for handling high volumes of
  805. data. In addition, the module has two new functions :func:`nlargest` and
  806. :func:`nsmallest` that use heaps to find the N largest or smallest values in a
  807. dataset without the expense of a full sort. (Contributed by Raymond Hettinger.)
  808. * The :mod:`httplib` module now contains constants for HTTP status codes defined
  809. in various HTTP-related RFC documents. Constants have names such as
  810. :const:`OK`, :const:`CREATED`, :const:`CONTINUE`, and
  811. :const:`MOVED_PERMANENTLY`; use pydoc to get a full list. (Contributed by
  812. Andrew Eland.)
  813. * The :mod:`imaplib` module now supports IMAP's THREAD command (contributed by
  814. Yves Dionne) and new :meth:`deleteacl` and :meth:`myrights` methods (contributed
  815. by Arnaud Mazin).
  816. * The :mod:`itertools` module gained a :func:`groupby(iterable[, *func*])`
  817. function. *iterable* is something that can be iterated over to return a stream
  818. of elements, and the optional *func* parameter is a function that takes an
  819. element and returns a key value; if omitted, the key is simply the element
  820. itself. :func:`groupby` then groups the elements into subsequences which have
  821. matching values of the key, and returns a series of 2-tuples containing the key
  822. value and an iterator over the subsequence.
  823. Here's an example to make this clearer. The *key* function simply returns
  824. whether a number is even or odd, so the result of :func:`groupby` is to return
  825. consecutive runs of odd or even numbers. ::
  826. >>> import itertools
  827. >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
  828. >>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
  829. ... print key_val, list(it)
  830. ...
  831. 0 [2, 4, 6]
  832. 1 [7]
  833. 0 [8]
  834. 1 [9, 11]
  835. 0 [12, 14]
  836. >>>
  837. :func:`groupby` is typically used with sorted input. The logic for
  838. :func:`groupby` is similar to the Unix ``uniq`` filter which makes it handy for
  839. eliminating, counting, or identifying duplicate elements::
  840. >>> word = 'abracadabra'
  841. >>> letters = sorted(word) # Turn string into a sorted list of letters
  842. >>> letters
  843. ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
  844. >>> for k, g in itertools.groupby(letters):
  845. ... print k, list(g)
  846. ...
  847. a ['a', 'a', 'a', 'a', 'a']
  848. b ['b', 'b']
  849. c ['c']
  850. d ['d']
  851. r ['r', 'r']
  852. >>> # List unique letters
  853. >>> [k for k, g in groupby(letters)]
  854. ['a', 'b', 'c', 'd', 'r']
  855. >>> # Count letter occurrences
  856. >>> [(k, len(list(g))) for k, g in groupby(letters)]
  857. [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]
  858. (Contributed by Hye-Shik Chang.)
  859. * :mod:`itertools` also gained a function named :func:`tee(iterator, N)` that
  860. returns *N* independent iterators that replicate *iterator*. If *N* is omitted,
  861. the default is 2. ::
  862. >>> L = [1,2,3]
  863. >>> i1, i2 = itertools.tee(L)
  864. >>> i1,i2
  865. (<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
  866. >>> list(i1) # Run the first iterator to exhaustion
  867. [1, 2, 3]
  868. >>> list(i2) # Run the second iterator to exhaustion
  869. [1, 2, 3]
  870. Note that :func:`tee` has to keep copies of the values returned by the
  871. iterator; in the worst case, it may need to keep all of them. This should
  872. therefore be used carefully if the leading iterator can run far ahead of the
  873. trailing iterator in a long stream of inputs. If the separation is large, then
  874. you might as well use :func:`list` instead. When the iterators track closely
  875. with one another, :func:`tee` is ideal. Possible applications include
  876. bookmarking, windowing, or lookahead iterators. (Contributed by Raymond
  877. Hettinger.)
  878. * A number of functions were added to the :mod:`locale` module, such as
  879. :func:`bind_textdomain_codeset` to specify a particular encoding and a family of
  880. :func:`l\*gettext` functions that return messages in the chosen encoding.
  881. (Contributed by Gustavo Niemeyer.)
  882. * Some keyword arguments were added to the :mod:`logging` package's
  883. :func:`basicConfig` function to simplify log configuration. The default
  884. behavior is to log messages to standard error, but various keyword arguments can
  885. be specified to log to a particular file, change the logging format, or set the
  886. logging level. For example::
  887. import logging
  888. logging.basicConfig(filename='/var/log/application.log',
  889. level=0, # Log all messages
  890. format='%(levelname):%(process):%(thread):%(message)')
  891. Other additions to the :mod:`logging` package include a :meth:`log(level, msg)`
  892. convenience method, as well as a :class:`TimedRotatingFileHandler` class that
  893. rotates its log files at a timed interval. The module already had
  894. :class:`RotatingFileHandler`, which rotated logs once the file exceeded a
  895. certain size. Both classes derive from a new :class:`BaseRotatingHandler` class
  896. that can be used to implement other rotating handlers.
  897. (Changes implemented by Vinay Sajip.)
  898. * The :mod:`marshal` module now shares interned strings on unpacking a data
  899. structure. This may shrink the size of certain pickle strings, but the primary
  900. effect is to make :file:`.pyc` files significantly smaller. (Contributed by
  901. Martin von Löwis.)
  902. * The :mod:`nntplib` module's :class:`NNTP` class gained :meth:`description` and
  903. :meth:`descriptions` methods to retrieve newsgroup descriptions for a single
  904. group or for a range of groups. (Contributed by JĂĽrgen A. Erhard.)
  905. * Two new functions were added to the :mod:`operator` module,
  906. :func:`attrgetter(attr)` and :func:`itemgetter(index)`. Both functions return
  907. callables that take a single argument and return the corresponding attribute or
  908. item; these callables make excellent data extractors when used with :func:`map`
  909. or :func:`sorted`. For example::
  910. >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
  911. >>> map(operator.itemgetter(0), L)
  912. ['c', 'd', 'a', 'b']
  913. >>> map(operator.itemgetter(1), L)
  914. [2, 1, 4, 3]
  915. >>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
  916. [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
  917. (Contributed by Raymond Hettinger.)
  918. * The :mod:`optparse` module was updated in various ways. The module now passes
  919. its messages through :func:`gettext.gettext`, making it possible to
  920. internationalize Optik's help and error messages. Help messages for options can
  921. now include the string ``'%default'``, which will be replaced by the option's
  922. default value. (Contributed by Greg Ward.)
  923. * The long-term plan is to deprecate the :mod:`rfc822` module in some future
  924. Python release in favor of the :mod:`email` package. To this end, the
  925. :func:`email.Utils.formatdate` function has been changed to make it usable as a
  926. replacement for :func:`rfc822.formatdate`. You may want to write new e-mail
  927. processing code with this in mind. (Change implemented by Anthony Baxter.)
  928. * A new :func:`urandom(n)` function was added to the :mod:`os` module, returning
  929. a string containing *n* bytes of random data. This function provides access to
  930. platform-specific sources of randomness such as :file:`/dev/urandom` on Linux or
  931. the Windows CryptoAPI. (Contributed by Trevor Perrin.)
  932. * Another new function: :func:`os.path.lexists(path)` returns true if the file
  933. specified by *path* exists, whether or not it's a symbolic link. This differs
  934. from the existing :func:`os.path.exists(path)` function, which returns false if
  935. *path* is a symlink that points to a destination that doesn't exist.
  936. (Contributed by Beni Cherniavsky.)
  937. * A new :func:`getsid` function was added to the :mod:`posix` module that
  938. underlies the :mod:`os` module. (Contributed by J. Raynor.)
  939. * The :mod:`poplib` module now supports POP over SSL. (Contributed by Hector
  940. Urtubia.)
  941. * The :mod:`profile` module can now profile C extension functions. (Contributed
  942. by Nick Bastin.)
  943. * The :mod:`random` module has a new method called :meth:`getrandbits(N)` that
  944. returns a long integer *N* bits in length. The existing :meth:`randrange`
  945. method now uses :meth:`getrandbits` where appropriate, making generation of
  946. arbitrarily large random numbers more efficient. (Contributed by Raymond
  947. Hettinger.)
  948. * The regular expression language accepted by the :mod:`re` module was extended
  949. with simple conditional expressions, written as ``(?(group)A|B)``. *group* is
  950. either a numeric group ID or a group name defined with ``(?P<group>...)``
  951. earlier in the expression. If the specified group matched, the regular
  952. expression pattern *A* will be tested against the string; if the group didn't
  953. match, the pattern *B* will be used instead. (Contributed by Gustavo Niemeyer.)
  954. * The :mod:`re` module is also no longer recursive, thanks to a massive amount
  955. of work by Gustavo Niemeyer. In a recursive regular expression engine, certain
  956. patterns result in a large amount of C stack space being consumed, and it was
  957. possible to overflow the stack. For example, if you matched a 30000-byte string
  958. of ``a`` characters against the expression ``(a|b)+``, one stack frame was
  959. consumed per character. Python 2.3 tried to check for stack overflow and raise
  960. a :exc:`RuntimeError` exception, but certain patterns could sidestep the
  961. checking and if you were unlucky Python could segfault. Python 2.4's regular
  962. expression engine can match this pattern without problems.
  963. * The :mod:`signal` module now performs tighter error-checking on the parameters
  964. to the :func:`signal.signal` function. For example, you can't set a handler on
  965. the :const:`SIGKILL` signal; previous versions of Python would quietly accept
  966. this, but 2.4 will raise a :exc:`RuntimeError` exception.
  967. * Two new functions were added to the :mod:`socket` module. :func:`socketpair`
  968. returns a pair of connected sockets and :func:`getservbyport(port)` looks up the
  969. service name for a given port number. (Contributed by Dave Cole and Barry
  970. Warsaw.)
  971. * The :func:`sys.exitfunc` function has been deprecated. Code should be using
  972. the existing :mod:`atexit` module, which correctly handles calling multiple exit
  973. functions. Eventually :func:`sys.exitfunc` will become a purely internal
  974. interface, accessed only by :mod:`atexit`.
  975. * The :mod:`tarfile` module now generates GNU-format tar files by default.
  976. (Contributed by Lars Gustaebel.)
  977. * The :mod:`threading` module now has an elegantly simple way to support
  978. thread-local data. The module contains a :class:`local` class whose attribute
  979. values are local to different threads. ::
  980. import threading
  981. data = threading.local()
  982. data.number = 42
  983. data.url = ('www.python.org', 80)
  984. Other threads can assign and retrieve their own values for the :attr:`number`
  985. and :attr:`url` attributes. You can subclass :class:`local` to initialize
  986. attributes or to add methods. (Contributed by Jim Fulton.)
  987. * The :mod:`timeit` module now automatically disables periodic garbage
  988. collection during the timing loop. This change makes consecutive timings more
  989. comparable. (Contributed by Raymond Hettinger.)
  990. * The :mod:`weakref` module now supports a wider variety of objects including
  991. Python functions, class instances, sets, frozensets, deques, arrays, files,
  992. sockets, and regular expression pattern objects. (Contributed by Raymond
  993. Hettinger.)
  994. * The :mod:`xmlrpclib` module now supports a multi-call extension for
  995. transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by
  996. Brian Quinlan.)
  997. * The :mod:`mpz`, :mod:`rotor`, and :mod:`xreadlines` modules have been
  998. removed.
  999. .. ======================================================================
  1000. .. whole new modules get described in subsections here
  1001. .. =====================
  1002. cookielib
  1003. ---------
  1004. The :mod:`cookielib` library supports client-side handling for HTTP cookies,
  1005. mirroring the :mod:`Cookie` module's server-side cookie support. Cookies are
  1006. stored in cookie jars; the library transparently stores cookies offered by the
  1007. web server in the cookie jar, and fetches the cookie from the jar when
  1008. connecting to the server. As in web browsers, policy objects control whether
  1009. cookies are accepted or not.
  1010. In order to store cookies across sessions, two implementations of cookie jars
  1011. are provided: one that stores cookies in the Netscape format so applications can
  1012. use the Mozilla or Lynx cookie files, and one that stores cookies in the same
  1013. format as the Perl libwww library.
  1014. :mod:`urllib2` has been changed to interact with :mod:`cookielib`:
  1015. :class:`HTTPCookieProcessor` manages a cookie jar that is used when accessing
  1016. URLs.
  1017. This module was contributed by John J. Lee.
  1018. .. ==================
  1019. doctest
  1020. -------
  1021. The :mod:`doctest` module underwent considerable refactoring thanks to Edward
  1022. Loper and Tim Peters. Testing can still be as simple as running
  1023. :func:`doctest.testmod`, but the refactorings allow customizing the module's
  1024. operation in various ways
  1025. The new :class:`DocTestFinder` class extracts the tests from a given object's
  1026. docstrings::
  1027. def f (x, y):
  1028. """>>> f(2,2)
  1029. 4
  1030. >>> f(3,2)
  1031. 6
  1032. """
  1033. return x*y
  1034. finder = doctest.DocTestFinder()
  1035. # Get list of DocTest instances
  1036. tests = finder.find(f)
  1037. The new :class:`DocTestRunner` class then runs individual tests and can produce
  1038. a summary of the results::
  1039. runner = doctest.DocTestRunner()
  1040. for t in tests:
  1041. tried, failed = runner.run(t)
  1042. runner.summarize(verbose=1)
  1043. The above example produces the following output::
  1044. 1 items passed all tests:
  1045. 2 tests in f
  1046. 2 tests in 1 items.
  1047. 2 passed and 0 failed.
  1048. Test passed.
  1049. :class:`DocTestRunner` uses an instance of the :class:`OutputChecker` class to
  1050. compare the expected output with the actual output. This class takes a number
  1051. of different flags that customize its behaviour; ambitious users can also write
  1052. a completely new subclass of :class:`OutputChecker`.
  1053. The default output checker provides a number of handy features. For example,
  1054. with the :const:`doctest.ELLIPSIS` option flag, an ellipsis (``...``) in the
  1055. expected output matches any substring, making it easier to accommodate outputs
  1056. that vary in minor ways::
  1057. def o (n):
  1058. """>>> o(1)
  1059. <__main__.C instance at 0x...>
  1060. >>>
  1061. """
  1062. Another special string, ``<BLANKLINE>``, matches a blank line::
  1063. def p (n):
  1064. """>>> p(1)
  1065. <BLANKLINE>
  1066. >>>
  1067. """
  1068. Another new capability is producing a diff-style display of the output by
  1069. specifying the :const:`doctest.REPORT_UDIFF` (unified diffs),
  1070. :const:`doctest.REPORT_CDIFF` (context diffs), or :const:`doctest.REPORT_NDIFF`
  1071. (delta-style) option flags. For example::
  1072. def g (n):
  1073. """>>> g(4)
  1074. here
  1075. is
  1076. a
  1077. lengthy
  1078. >>>"""
  1079. L = 'here is a rather lengthy list of words'.split()
  1080. for word in L[:n]:
  1081. print word
  1082. Running the above function's tests with :const:`doctest.REPORT_UDIFF` specified,
  1083. you get the following output::
  1084. **********************************************************************
  1085. File "t.py", line 15, in g
  1086. Failed example:
  1087. g(4)
  1088. Differences (unified diff with -expected +actual):
  1089. @@ -2,3 +2,3 @@
  1090. is
  1091. a
  1092. -lengthy
  1093. +rather
  1094. **********************************************************************
  1095. .. ======================================================================
  1096. Build and C API Changes
  1097. =======================
  1098. Some of the changes to Python's build process and to the C API are:
  1099. * Three new convenience macros were added for common return values from
  1100. extension functions: :cmacro:`Py_RETURN_NONE`, :cmacro:`Py_RETURN_TRUE`, and
  1101. :cmacro:`Py_RETURN_FALSE`. (Contributed by Brett Cannon.)
  1102. * Another new macro, :cmacro:`Py_CLEAR(obj)`, decreases the reference count of
  1103. *obj* and sets *obj* to the null pointer. (Contributed by Jim Fulton.)
  1104. * A new function, :cfunc:`PyTuple_Pack(N, obj1, obj2, ..., objN)`, constructs
  1105. tuples from a variable length argument list of Python objects. (Contributed by
  1106. Raymond Hettinger.)
  1107. * A new function, :cfunc:`PyDict_Contains(d, k)`, implements fast dictionary
  1108. lookups without masking exceptions raised during the look-up process.
  1109. (Contributed by Raymond Hettinger.)
  1110. * The :cmacro:`Py_IS_NAN(X)` macro returns 1 if its float or double argument
  1111. *X* is a NaN. (Contributed by Tim Peters.)
  1112. * C code can avoid unnecessary locking by using the new
  1113. :cfunc:`PyEval_ThreadsInitialized` function to tell if any thread operations
  1114. have been performed. If this function returns false, no lock operations are
  1115. needed. (Contributed by Nick Coghlan.)
  1116. * A new function, :cfunc:`PyArg_VaParseTupleAndKeywords`, is the same as
  1117. :cfunc:`PyArg_ParseTupleAndKeywords` but takes a :ctype:`va_list` instead of a
  1118. number of arguments. (Contributed by Greg Chapman.)
  1119. * A new method flag, :const:`METH_COEXISTS`, allows a function defined in slots
  1120. to co-exist with a :ctype:`PyCFunction` having the same name. This can halve
  1121. the access time for a method such as :meth:`set.__contains__`. (Contributed by
  1122. Raymond Hettinger.)
  1123. * Python can now be built with additional profiling for the interpreter itself,
  1124. intended as an aid to people developing the Python core. Providing
  1125. :option:`----enable-profiling` to the :program:`configure` script will let you
  1126. profile the interpreter with :program:`gprof`, and providing the
  1127. :option:`----with-tsc` switch enables profiling using the Pentium's Time-Stamp-
  1128. Counter register. Note that the :option:`----with-tsc` switch is slightly
  1129. misnamed, because the profiling feature also works on the PowerPC platform,
  1130. though that processor architecture doesn't call that register "the TSC
  1131. register". (Contributed by Jeremy Hylton.)
  1132. * The :ctype:`tracebackobject` type has been renamed to
  1133. :ctype:`PyTracebackObject`.
  1134. .. ======================================================================
  1135. Port-Specific Changes
  1136. ---------------------
  1137. * The Windows port now builds under MSVC++ 7.1 as well as version 6.
  1138. (Contributed by Martin von Löwis.)
  1139. .. ======================================================================
  1140. Porting to Python 2.4
  1141. =====================
  1142. This section lists previously described changes that may require changes to your
  1143. code:
  1144. * Left shifts and hexadecimal/octal constants that are too large no longer
  1145. trigger a :exc:`FutureWarning` and return a value limited to 32 or 64 bits;
  1146. instead they return a long integer.
  1147. * Integer operations will no longer trigger an :exc:`OverflowWarning`. The
  1148. :exc:`OverflowWarning` warning will disappear in Python 2.5.
  1149. * The :func:`zip` built-in function and :func:`itertools.izip` now return an
  1150. empty list instead of raising a :exc:`TypeError` exception if called with no
  1151. arguments.
  1152. * You can no longer compare the :class:`date` and :class:`datetime` instances
  1153. provided by the :mod:`datetime` module. Two instances of different classes
  1154. will now always be unequal, and relative comparisons (``<``, ``>``) will raise
  1155. a :exc:`TypeError`.
  1156. * :func:`dircache.listdir` now passes exceptions to the caller instead of
  1157. returning empty lists.
  1158. * :func:`LexicalHandler.startDTD` used to receive the public and system IDs in
  1159. the wrong order. This has been corrected; applications relying on the wrong
  1160. order need to be fixed.
  1161. * :func:`fcntl.ioctl` now warns if the *mutate* argument is omitted and
  1162. relevant.
  1163. * The :mod:`tarfile` module now generates GNU-format tar files by default.
  1164. * Encountering a failure while importing a module no longer leaves a partially-
  1165. initialized module object in ``sys.modules``.
  1166. * :const:`None` is now a constant; code that binds a new value to the name
  1167. ``None`` is now a syntax error.
  1168. * The :func:`signals.signal` function now raises a :exc:`RuntimeError` exception
  1169. for certain illegal values; previously these errors would pass silently. For
  1170. example, you can no longer set a handler on the :const:`SIGKILL` signal.
  1171. .. ======================================================================
  1172. .. _24acks:
  1173. Acknowledgements
  1174. ================
  1175. The author would like to thank the following people for offering suggestions,
  1176. corrections and assistance with various drafts of this article: Koray Can, Hye-
  1177. Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson, Fredrik
  1178. Lundh, Sean Reifschneider, Sadruddin Rejeb.