~ubuntu-branches/ubuntu/quantal/python2.7/quantal-updates

« back to all changes in this revision

Viewing changes to debian/patches/hg-updates.diff

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2011-11-30 19:16:23 UTC
  • mfrom: (36.1.5 sid)
  • Revision ID: package-import@ubuntu.com-20111130191623-ov9hszutdakcsnbz
Tags: 2.7.2-8
* Update to 20111130, taken from the 2.7 branch.
* New patch, ctypes-arm, allow for ",hard-float" after libc6 in ldconfig -p
  output (Loic Minier). LP: #898172.
* debian/rules: Define DPKG_VARS (Alban Browaeys). Closes: #647419).
* Add python-config man page (Johann Felix Soden). Closes: #650181).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# DP: hg updates of the 2.7 release branch (until 2011-08-16).
 
1
# DP: hg updates of the 2.7 release branch (until 2011-11-30).
2
2
 
3
3
# hg diff -r v2.7.2 | filterdiff --exclude=Lib/pstats.py --exclude=Lib/profile.py --exclude=.*ignore --exclude=.hg* --remove-timestamps
4
4
 
 
5
diff -r 8527427914a2 Demo/threads/sync.py
 
6
--- a/Demo/threads/sync.py
 
7
+++ b/Demo/threads/sync.py
 
8
@@ -265,7 +265,7 @@
 
9
 #      intervening.  If there are other threads waiting to write, they
 
10
 #      are allowed to proceed only if the current thread calls
 
11
 #      .read_out; threads waiting to read are only allowed to proceed
 
12
-#      if there are are no threads waiting to write.  (This is a
 
13
+#      if there are no threads waiting to write.  (This is a
 
14
 #      weakness of the interface!)
 
15
 
 
16
 import thread
 
17
diff -r 8527427914a2 Demo/tix/tixwidgets.py
 
18
--- a/Demo/tix/tixwidgets.py
 
19
+++ b/Demo/tix/tixwidgets.py
 
20
@@ -659,7 +659,7 @@
 
21
 I have implemented a new image type called "compound". It allows you
 
22
 to glue together a bunch of bitmaps, images and text strings together
 
23
 to form a bigger image. Then you can use this image with widgets that
 
24
-support the -image option. For example, you can display a text string string
 
25
+support the -image option. For example, you can display a text string
 
26
 together with a bitmap, at the same time, inside a TK button widget.
 
27
 """)
 
28
     list.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6)
5
29
diff -r 8527427914a2 Demo/turtle/about_turtle.txt
6
30
--- a/Demo/turtle/about_turtle.txt
7
31
+++ b/Demo/turtle/about_turtle.txt
47
71
    * Ng Pheng Siong
48
72
    * Koray Oner
49
73
    * Tomas Oppelstrup
50
 
@@ -197,6 +200,7 @@
 
74
@@ -180,6 +183,7 @@
 
75
    * Joakim Sernbrant
 
76
    * Justin Sheehy
 
77
    * Charlie Shepherd
 
78
+   * Yue Shuaijie
 
79
    * Michael Simcich
 
80
    * Ionel Simionescu
 
81
    * Michael Sloan
 
82
@@ -197,6 +201,7 @@
51
83
    * Kalle Svensson
52
84
    * Jim Tittsler
53
85
    * David Turner
55
87
    * Ville Vainio
56
88
    * Martijn Vries
57
89
    * Charles G. Waldman
 
90
@@ -214,6 +219,7 @@
 
91
    * Collin Winter
 
92
    * Blake Winton
 
93
    * Dan Wolfe
 
94
+   * Adam Woodbeck
 
95
    * Steven Work
 
96
    * Thomas Wouters
 
97
    * Ka-Ping Yee
58
98
diff -r 8527427914a2 Doc/c-api/exceptions.rst
59
99
--- a/Doc/c-api/exceptions.rst
60
100
+++ b/Doc/c-api/exceptions.rst
72
112
    :cdata:`PyExc_Exception`).
73
113
 
74
114
    The :attr:`__module__` attribute of the new class is set to the first part (up
 
115
@@ -475,7 +475,7 @@
 
116
 
 
117
    Marks a point where a recursive C-level call is about to be performed.
 
118
 
 
119
-   If :const:`USE_STACKCHECK` is defined, this function checks if the the OS
 
120
+   If :const:`USE_STACKCHECK` is defined, this function checks if the OS
 
121
    stack overflowed using :cfunc:`PyOS_CheckStack`.  In this is the case, it
 
122
    sets a :exc:`MemoryError` and returns a nonzero value.
 
123
 
 
124
diff -r 8527427914a2 Doc/c-api/file.rst
 
125
--- a/Doc/c-api/file.rst
 
126
+++ b/Doc/c-api/file.rst
 
127
@@ -55,7 +55,8 @@
 
128
 
 
129
    Create a new :ctype:`PyFileObject` from the already-open standard C file
 
130
    pointer, *fp*.  The function *close* will be called when the file should be
 
131
-   closed.  Return *NULL* on failure.
 
132
+   closed.  Return *NULL* and close the file using *close* on failure.
 
133
+   *close* is optional and can be set to *NULL*.
 
134
 
 
135
 
 
136
 .. cfunction:: FILE* PyFile_AsFile(PyObject \*p)
75
137
diff -r 8527427914a2 Doc/c-api/init.rst
76
138
--- a/Doc/c-api/init.rst
77
139
+++ b/Doc/c-api/init.rst
 
140
@@ -126,7 +126,7 @@
 
141
    program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
 
142
    returned string points into static storage; the caller should not modify its
 
143
    value.  This corresponds to the :makevar:`prefix` variable in the top-level
 
144
-   :file:`Makefile` and the :option:`--prefix` argument to the :program:`configure`
 
145
+   :file:`Makefile` and the ``--prefix`` argument to the :program:`configure`
 
146
    script at build time.  The value is available to Python code as ``sys.prefix``.
 
147
    It is only useful on Unix.  See also the next function.
 
148
 
 
149
@@ -139,7 +139,7 @@
 
150
    program name is ``'/usr/local/bin/python'``, the exec-prefix is
 
151
    ``'/usr/local'``.  The returned string points into static storage; the caller
 
152
    should not modify its value.  This corresponds to the :makevar:`exec_prefix`
 
153
-   variable in the top-level :file:`Makefile` and the :option:`--exec-prefix`
 
154
+   variable in the top-level :file:`Makefile` and the ``--exec-prefix``
 
155
    argument to the :program:`configure` script at build  time.  The value is
 
156
    available to Python code as ``sys.exec_prefix``.  It is only useful on Unix.
 
157
 
78
158
@@ -638,6 +638,16 @@
79
159
    .. versionadded:: 2.3
80
160
 
133
213
diff -r 8527427914a2 Doc/distutils/apiref.rst
134
214
--- a/Doc/distutils/apiref.rst
135
215
+++ b/Doc/distutils/apiref.rst
136
 
@@ -72,8 +72,8 @@
 
216
@@ -31,8 +31,9 @@
 
217
    +====================+================================+=============================================================+
 
218
    | *name*             | The name of the package        | a string                                                    |
 
219
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
220
-   | *version*          | The version number of the      | See :mod:`distutils.version`                                |
 
221
-   |                    | package                        |                                                             |
 
222
+   | *version*          | The version number of the      | a string                                                    |
 
223
+   |                    | package; see                   |                                                             |
 
224
+   |                    | :mod:`distutils.version`       |                                                             |
 
225
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
226
    | *description*      | A single line describing the   | a string                                                    |
 
227
    |                    | package                        |                                                             |
 
228
@@ -49,14 +50,14 @@
 
229
    |                    | maintainer, if different from  |                                                             |
 
230
    |                    | the author                     |                                                             |
 
231
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
232
-   | *maintainer_email* | The email address of the       |                                                             |
 
233
+   | *maintainer_email* | The email address of the       | a string                                                    |
 
234
    |                    | current maintainer, if         |                                                             |
 
235
    |                    | different from the author      |                                                             |
 
236
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
237
-   | *url*              | A URL for the package          | a URL                                                       |
 
238
+   | *url*              | A URL for the package          | a string                                                    |
 
239
    |                    | (homepage)                     |                                                             |
 
240
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
241
-   | *download_url*     | A URL to download the package  | a URL                                                       |
 
242
+   | *download_url*     | A URL to download the package  | a string                                                    |
 
243
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
244
    | *packages*         | A list of Python packages that | a list of strings                                           |
 
245
    |                    | distutils will manipulate      |                                                             |
 
246
@@ -68,14 +69,13 @@
 
247
    |                    | files to be built and          |                                                             |
 
248
    |                    | installed                      |                                                             |
 
249
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
250
-   | *ext_modules*      | A list of Python extensions to | A list of  instances of                                     |
 
251
+   | *ext_modules*      | A list of Python extensions to | a list of instances of                                      |
137
252
    |                    | be built                       | :class:`distutils.core.Extension`                           |
138
253
    +--------------------+--------------------------------+-------------------------------------------------------------+
139
 
    | *classifiers*      | A list of categories for the   | The list of available                                       |
 
254
-   | *classifiers*      | A list of categories for the   | The list of available                                       |
140
255
-   |                    | package                        | categorizations is at                                       |
141
256
-   |                    |                                | http://pypi.python.org/pypi?:action=list_classifiers.       |
142
 
+   |                    | package                        | categorizations is available on `PyPI                       |
143
 
+   |                    |                                | <http://pypi.python.org/pypi?:action=list_classifiers>`_.   |
 
257
+   | *classifiers*      | A list of categories for the   | a list of strings; valid classifiers are listed on `PyPI    |
 
258
+   |                    | package                        | <http://pypi.python.org/pypi?:action=list_classifiers>`_.   |
144
259
    +--------------------+--------------------------------+-------------------------------------------------------------+
145
 
    | *distclass*        | the :class:`Distribution`      | A subclass of                                               |
 
260
-   | *distclass*        | the :class:`Distribution`      | A subclass of                                               |
 
261
+   | *distclass*        | the :class:`Distribution`      | a subclass of                                               |
146
262
    |                    | class to use                   | :class:`distutils.core.Distribution`                        |
147
 
@@ -1815,7 +1815,7 @@
 
263
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
264
    | *script_name*      | The name of the setup.py       | a string                                                    |
 
265
@@ -85,15 +85,15 @@
 
266
    | *script_args*      | Arguments to supply to the     | a list of strings                                           |
 
267
    |                    | setup script                   |                                                             |
 
268
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
269
-   | *options*          | default options for the setup  | a string                                                    |
 
270
+   | *options*          | default options for the setup  | a dictionary                                                |
 
271
    |                    | script                         |                                                             |
 
272
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
273
    | *license*          | The license for the package    | a string                                                    |
 
274
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
275
-   | *keywords*         | Descriptive meta-data, see     |                                                             |
 
276
+   | *keywords*         | Descriptive meta-data, see     | a list of strings or a comma-separated string               |
 
277
    |                    | :pep:`314`                     |                                                             |
 
278
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
279
-   | *platforms*        |                                |                                                             |
 
280
+   | *platforms*        |                                | a list of strings or a comma-separated string               |
 
281
    +--------------------+--------------------------------+-------------------------------------------------------------+
 
282
    | *cmdclass*         | A mapping of command names to  | a dictionary                                                |
 
283
    |                    | :class:`Command` subclasses    |                                                             |
 
284
@@ -165,13 +165,13 @@
 
285
    +------------------------+--------------------------------+---------------------------+
 
286
    | argument name          | value                          | type                      |
 
287
    +========================+================================+===========================+
 
288
-   | *name*                 | the full name of the           | string                    |
 
289
+   | *name*                 | the full name of the           | a string                  |
 
290
    |                        | extension, including any       |                           |
 
291
    |                        | packages --- ie. *not* a       |                           |
 
292
    |                        | filename or pathname, but      |                           |
 
293
    |                        | Python dotted name             |                           |
 
294
    +------------------------+--------------------------------+---------------------------+
 
295
-   | *sources*              | list of source filenames,      | string                    |
 
296
+   | *sources*              | list of source filenames,      | a list of strings         |
 
297
    |                        | relative to the distribution   |                           |
 
298
    |                        | root (where the setup script   |                           |
 
299
    |                        | lives), in Unix form (slash-   |                           |
 
300
@@ -184,12 +184,12 @@
 
301
    |                        | as source for a Python         |                           |
 
302
    |                        | extension.                     |                           |
 
303
    +------------------------+--------------------------------+---------------------------+
 
304
-   | *include_dirs*         | list of directories to search  | string                    |
 
305
+   | *include_dirs*         | list of directories to search  | a list of strings         |
 
306
    |                        | for C/C++ header files (in     |                           |
 
307
    |                        | Unix form for portability)     |                           |
 
308
    +------------------------+--------------------------------+---------------------------+
 
309
-   | *define_macros*        | list of macros to define; each | (string, string) tuple or |
 
310
-   |                        | macro is defined using a       | (name, ``None``)          |
 
311
+   | *define_macros*        | list of macros to define; each | a list of tuples          |
 
312
+   |                        | macro is defined using a       |                           |
 
313
    |                        | 2-tuple ``(name, value)``,     |                           |
 
314
    |                        | where *value* is               |                           |
 
315
    |                        | either the string to define it |                           |
 
316
@@ -200,31 +200,31 @@
 
317
    |                        | on Unix C compiler command     |                           |
 
318
    |                        | line)                          |                           |
 
319
    +------------------------+--------------------------------+---------------------------+
 
320
-   | *undef_macros*         | list of macros to undefine     | string                    |
 
321
+   | *undef_macros*         | list of macros to undefine     | a list of strings         |
 
322
    |                        | explicitly                     |                           |
 
323
    +------------------------+--------------------------------+---------------------------+
 
324
-   | *library_dirs*         | list of directories to search  | string                    |
 
325
+   | *library_dirs*         | list of directories to search  | a list of strings         |
 
326
    |                        | for C/C++ libraries at link    |                           |
 
327
    |                        | time                           |                           |
 
328
    +------------------------+--------------------------------+---------------------------+
 
329
-   | *libraries*            | list of library names (not     | string                    |
 
330
+   | *libraries*            | list of library names (not     | a list of strings         |
 
331
    |                        | filenames or paths) to link    |                           |
 
332
    |                        | against                        |                           |
 
333
    +------------------------+--------------------------------+---------------------------+
 
334
-   | *runtime_library_dirs* | list of directories to search  | string                    |
 
335
+   | *runtime_library_dirs* | list of directories to search  | a list of strings         |
 
336
    |                        | for C/C++ libraries at run     |                           |
 
337
    |                        | time (for shared extensions,   |                           |
 
338
    |                        | this is when the extension is  |                           |
 
339
    |                        | loaded)                        |                           |
 
340
    +------------------------+--------------------------------+---------------------------+
 
341
-   | *extra_objects*        | list of extra files to link    | string                    |
 
342
+   | *extra_objects*        | list of extra files to link    | a list of strings         |
 
343
    |                        | with (eg. object files not     |                           |
 
344
    |                        | implied by 'sources', static   |                           |
 
345
    |                        | library that must be           |                           |
 
346
    |                        | explicitly specified, binary   |                           |
 
347
    |                        | resource files, etc.)          |                           |
 
348
    +------------------------+--------------------------------+---------------------------+
 
349
-   | *extra_compile_args*   | any extra platform- and        | string                    |
 
350
+   | *extra_compile_args*   | any extra platform- and        | a list of strings         |
 
351
    |                        | compiler-specific information  |                           |
 
352
    |                        | to use when compiling the      |                           |
 
353
    |                        | source files in 'sources'. For |                           |
 
354
@@ -235,7 +235,7 @@
 
355
    |                        | for other platforms it could   |                           |
 
356
    |                        | be anything.                   |                           |
 
357
    +------------------------+--------------------------------+---------------------------+
 
358
-   | *extra_link_args*      | any extra platform- and        | string                    |
 
359
+   | *extra_link_args*      | any extra platform- and        | a list of strings         |
 
360
    |                        | compiler-specific information  |                           |
 
361
    |                        | to use when linking object     |                           |
 
362
    |                        | files together to create the   |                           |
 
363
@@ -244,7 +244,7 @@
 
364
    |                        | Similar interpretation as for  |                           |
 
365
    |                        | 'extra_compile_args'.          |                           |
 
366
    +------------------------+--------------------------------+---------------------------+
 
367
-   | *export_symbols*       | list of symbols to be exported | string                    |
 
368
+   | *export_symbols*       | list of symbols to be exported | a list of strings         |
 
369
    |                        | from a shared extension. Not   |                           |
 
370
    |                        | used on all platforms, and not |                           |
 
371
    |                        | generally necessary for Python |                           |
 
372
@@ -252,15 +252,20 @@
 
373
    |                        | export exactly one symbol:     |                           |
 
374
    |                        | ``init`` + extension_name.     |                           |
 
375
    +------------------------+--------------------------------+---------------------------+
 
376
-   | *depends*              | list of files that the         | string                    |
 
377
+   | *depends*              | list of files that the         | a list of strings         |
 
378
    |                        | extension depends on           |                           |
 
379
    +------------------------+--------------------------------+---------------------------+
 
380
-   | *language*             | extension language (i.e.       | string                    |
 
381
+   | *language*             | extension language (i.e.       | a string                  |
 
382
    |                        | ``'c'``, ``'c++'``,            |                           |
 
383
    |                        | ``'objc'``). Will be detected  |                           |
 
384
    |                        | from the source extensions if  |                           |
 
385
    |                        | not provided.                  |                           |
 
386
    +------------------------+--------------------------------+---------------------------+
 
387
+   | *optional*             | specifies that a build failure | a boolean                 |
 
388
+   |                        | in the extension should not    |                           |
 
389
+   |                        | abort the build process, but   |                           |
 
390
+   |                        | simply skip the extension.     |                           |
 
391
+   +------------------------+--------------------------------+---------------------------+
 
392
 
 
393
 
 
394
 .. class:: Distribution
 
395
@@ -1736,7 +1741,7 @@
 
396
    Set final values for all the options that this command supports. This is
 
397
    always called as late as possible, ie.  after any option assignments from the
 
398
    command-line or from other commands have been done.  Thus, this is the place
 
399
-   to to code option dependencies: if *foo* depends on *bar*, then it is safe to
 
400
+   to code option dependencies: if *foo* depends on *bar*, then it is safe to
 
401
    set *foo* from *bar* as long as *foo* still has the same value it was
 
402
    assigned in :meth:`initialize_options`.
 
403
 
 
404
@@ -1815,7 +1820,7 @@
148
405
 .. module:: distutils.command.bdist_msi
149
406
    :synopsis: Build a binary distribution as a Windows MSI file
150
407
 
167
424
    python setup.py sdist
168
425
 
169
426
-which will create an archive file (e.g., tarball on Unix, ZIP file on Windows)
170
 
+For Windows, open a command prompt windows ("DOS box") and change the command
171
 
+to::
 
427
+For Windows, open a command prompt windows (:menuselection:`Start -->
 
428
+Accessories`) and change the command to::
172
429
+
173
430
+   setup.py sdist
174
431
+
188
445
 
189
446
 If you use a different convention to lay out your source directory, that's no
190
447
 problem: you just have to supply the :option:`package_dir` option to tell the
 
448
@@ -254,7 +254,7 @@
 
449
 
 
450
 If you need to include header files from some other Python extension, you can
 
451
 take advantage of the fact that header files are installed in a consistent way
 
452
-by the Distutils :command:`install_header` command.  For example, the Numerical
 
453
+by the Distutils :command:`install_headers` command.  For example, the Numerical
 
454
 Python header files are installed (on a standard Unix installation) to
 
455
 :file:`/usr/local/include/python1.5/Numerical`. (The exact location will differ
 
456
 according to your platform and Python installation.)  Since the Python include
191
457
diff -r 8527427914a2 Doc/distutils/sourcedist.rst
192
458
--- a/Doc/distutils/sourcedist.rst
193
459
+++ b/Doc/distutils/sourcedist.rst
250
516
diff -r 8527427914a2 Doc/documenting/building.rst
251
517
--- a/Doc/documenting/building.rst
252
518
+++ b/Doc/documenting/building.rst
253
 
@@ -14,6 +14,7 @@
 
519
@@ -14,11 +14,12 @@
254
520
 Luckily, a Makefile has been prepared so that on Unix, provided you have
255
521
 installed Python and Subversion, you can just run ::
256
522
 
257
523
+   cd Doc
258
524
    make html
259
525
 
260
 
 to check out the necessary toolset in the `tools/` subdirectory and build the
 
526
-to check out the necessary toolset in the `tools/` subdirectory and build the
 
527
-HTML output files.  To view the generated HTML, point your favorite browser at
 
528
-the top-level index `build/html/index.html` after running "make".
 
529
+to check out the necessary toolset in the :file:`tools/` subdirectory and build
 
530
+the HTML output files.  To view the generated HTML, point your favorite browser
 
531
+at the top-level index :file:`build/html/index.html` after running "make".
 
532
 
 
533
 Available make targets are:
 
534
 
 
535
@@ -49,10 +50,10 @@
 
536
 
 
537
  * "pydoc-topics", which builds a Python module containing a dictionary with
 
538
    plain text documentation for the labels defined in
 
539
-   `tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and
 
540
+   :file:`tools/sphinxext/pyspecific.py` -- pydoc needs these to show topic and
 
541
    keyword help.
 
542
 
 
543
-A "make update" updates the Subversion checkouts in `tools/`.
 
544
+A "make update" updates the Subversion checkouts in :file:`tools/`.
 
545
 
 
546
 
 
547
 Without make
261
548
diff -r 8527427914a2 Doc/documenting/markup.rst
262
549
--- a/Doc/documenting/markup.rst
263
550
+++ b/Doc/documenting/markup.rst
279
566
 index entries more informative.
280
567
 
281
568
 The directives are:
 
569
@@ -471,7 +472,10 @@
 
570
 
 
571
 .. describe:: keyword
 
572
 
 
573
-   The name of a keyword in Python.
 
574
+   The name of a Python keyword.  Using this role will generate a link to the
 
575
+   documentation of the keyword.  ``True``, ``False`` and ``None`` do not use
 
576
+   this role, but simple code markup (````True````), given that they're
 
577
+   fundamental to the language and should be known to any programmer.
 
578
 
 
579
 .. describe:: mailheader
 
580
 
 
581
diff -r 8527427914a2 Doc/extending/newtypes.rst
 
582
--- a/Doc/extending/newtypes.rst
 
583
+++ b/Doc/extending/newtypes.rst
 
584
@@ -38,8 +38,7 @@
 
585
 just contains the refcount and a pointer to the object's "type object".  This is
 
586
 where the action is; the type object determines which (C) functions get called
 
587
 when, for instance, an attribute gets looked up on an object or it is multiplied
 
588
-by another object.  These C functions are called "type methods" to distinguish
 
589
-them from things like ``[].append`` (which we call "object methods").
 
590
+by another object.  These C functions are called "type methods".
 
591
 
 
592
 So, if you want to define a new object type, you need to create a new type
 
593
 object.
 
594
diff -r 8527427914a2 Doc/faq/design.rst
 
595
--- a/Doc/faq/design.rst
 
596
+++ b/Doc/faq/design.rst
 
597
@@ -684,7 +684,7 @@
 
598
 Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes
 
599
 (ABCs).  You can then use :func:`isinstance` and :func:`issubclass` to check
 
600
 whether an instance or a class implements a particular ABC.  The
 
601
-:mod:`collections` modules defines a set of useful ABCs such as
 
602
+:mod:`collections` module defines a set of useful ABCs such as
 
603
 :class:`Iterable`, :class:`Container`, and :class:`MutableMapping`.
 
604
 
 
605
 For Python, many of the advantages of interface specifications can be obtained
 
606
diff -r 8527427914a2 Doc/faq/general.rst
 
607
--- a/Doc/faq/general.rst
 
608
+++ b/Doc/faq/general.rst
 
609
@@ -164,9 +164,7 @@
 
610
 several useful pieces of freely distributable software.  The source will compile
 
611
 and run out of the box on most UNIX platforms.
 
612
 
 
613
-.. XXX update link once the dev faq is relocated
 
614
-
 
615
-Consult the `Developer FAQ <http://www.python.org/dev/faq/>`__ for more
 
616
+Consult the `Developer FAQ <http://docs.python.org/devguide/faq>`__ for more
 
617
 information on getting the source code and compiling it.
 
618
 
 
619
 
 
620
@@ -221,10 +219,8 @@
 
621
 newsgroups and on the Python home page at http://www.python.org/; an RSS feed of
 
622
 news is available.
 
623
 
 
624
-.. XXX update link once the dev faq is relocated
 
625
-
 
626
 You can also access the development version of Python through Subversion.  See
 
627
-http://www.python.org/dev/faq/ for details.
 
628
+http://docs.python.org/devguide/faq for details.
 
629
 
 
630
 
 
631
 How do I submit bug reports and patches for Python?
 
632
@@ -239,10 +235,8 @@
 
633
 report bugs to Python, you can obtain your Roundup password through Roundup's
 
634
 `password reset procedure <http://bugs.python.org/user?@template=forgotten>`_.
 
635
 
 
636
-.. XXX adapt link to dev guide
 
637
-
 
638
 For more information on how Python is developed, consult `the Python Developer's
 
639
-Guide <http://python.org/dev/>`_.
 
640
+Guide <http://docs.python.org/devguide/>`_.
 
641
 
 
642
 
 
643
 Are there any published articles about Python that I can reference?
 
644
diff -r 8527427914a2 Doc/faq/programming.rst
 
645
--- a/Doc/faq/programming.rst
 
646
+++ b/Doc/faq/programming.rst
 
647
@@ -171,7 +171,7 @@
 
648
 Thus to get the same effect as::
 
649
 
 
650
    L2 = []
 
651
-   for i in range[3]:
 
652
+   for i in range(3):
 
653
        L2.append(L1[i])
 
654
 
 
655
 it is much shorter and far faster to use ::
 
656
diff -r 8527427914a2 Doc/faq/windows.rst
 
657
--- a/Doc/faq/windows.rst
 
658
+++ b/Doc/faq/windows.rst
 
659
@@ -542,7 +542,7 @@
 
660
 :func:`execfile` with the name of your file as argument.
 
661
 
 
662
 Also note that you can not mix-and-match Debug and Release versions.  If you
 
663
-wish to use the Debug Multithreaded DLL, then your module *must* have an "_d"
 
664
+wish to use the Debug Multithreaded DLL, then your module *must* have ``_d``
 
665
 appended to the base name.
 
666
 
 
667
 
282
668
diff -r 8527427914a2 Doc/glossary.rst
283
669
--- a/Doc/glossary.rst
284
670
+++ b/Doc/glossary.rst
285
 
@@ -27,12 +27,13 @@
 
671
@@ -27,12 +27,16 @@
286
672
       :ref:`2to3-reference`.
287
673
 
288
674
    abstract base class
291
677
       providing a way to define interfaces when other techniques like
292
678
-      :func:`hasattr` would be clumsy. Python comes with many built-in ABCs for
293
679
+      :func:`hasattr` would be clumsy or subtly wrong (for example with
294
 
+      :ref:`magic methods <new-style-special-lookup>`). Python comes with many built-in ABCs for
 
680
+      :ref:`magic methods <new-style-special-lookup>`).  ABCs introduce virtual
 
681
+      subclasses, which are classes that don't inherit from a class but are
 
682
+      still recognized by :func:`isinstance` and :func:`issubclass`; see the
 
683
+      :mod:`abc` module documentation.  Python comes with many built-in ABCs for
295
684
       data structures (in the :mod:`collections` module), numbers (in the
296
685
       :mod:`numbers` module), and streams (in the :mod:`io` module). You can
297
686
-      create your own ABC with the :mod:`abc` module.
299
688
 
300
689
    argument
301
690
       A value passed to a function or method, assigned to a named local
302
 
@@ -424,8 +425,8 @@
 
691
@@ -57,11 +61,14 @@
 
692
 
 
693
    bytecode
 
694
       Python source code is compiled into bytecode, the internal representation
 
695
-      of a Python program in the interpreter.  The bytecode is also cached in
 
696
-      ``.pyc`` and ``.pyo`` files so that executing the same file is faster the
 
697
-      second time (recompilation from source to bytecode can be avoided).  This
 
698
-      "intermediate language" is said to run on a :term:`virtual machine`
 
699
-      that executes the machine code corresponding to each bytecode.
 
700
+      of a Python program in the CPython interpreter.  The bytecode is also
 
701
+      cached in ``.pyc`` and ``.pyo`` files so that executing the same file is
 
702
+      faster the second time (recompilation from source to bytecode can be
 
703
+      avoided).  This "intermediate language" is said to run on a
 
704
+      :term:`virtual machine` that executes the machine code corresponding to
 
705
+      each bytecode. Do note that bytecodes are not expected to work between
 
706
+      different Python virtual machines, nor to be stable between Python
 
707
+      releases.
 
708
 
 
709
       A list of bytecode instructions can be found in the documentation for
 
710
       :ref:`the dis module <bytecodes>`.
 
711
@@ -127,8 +134,9 @@
 
712
          def f(...):
 
713
              ...
 
714
 
 
715
-      See :ref:`the documentation for function definition <function>` for more
 
716
-      about decorators.
 
717
+      The same concept exists for classes, but is less commonly used there.  See
 
718
+      the documentation for :ref:`function definitions <function>` and
 
719
+      :ref:`class definitions <class>` for more about decorators.
 
720
 
 
721
    descriptor
 
722
       Any *new-style* object which defines the methods :meth:`__get__`,
 
723
@@ -164,8 +172,8 @@
 
724
       well-designed code improves its flexibility by allowing polymorphic
 
725
       substitution.  Duck-typing avoids tests using :func:`type` or
 
726
       :func:`isinstance`.  (Note, however, that duck-typing can be complemented
 
727
-      with :term:`abstract base class`\ es.)  Instead, it typically employs
 
728
-      :func:`hasattr` tests or :term:`EAFP` programming.
 
729
+      with :term:`abstract base classes <abstract base class>`.)  Instead, it
 
730
+      typically employs :func:`hasattr` tests or :term:`EAFP` programming.
 
731
 
 
732
    EAFP
 
733
       Easier to ask for forgiveness than permission.  This common Python coding
 
734
@@ -177,17 +185,34 @@
 
735
 
 
736
    expression
 
737
       A piece of syntax which can be evaluated to some value.  In other words,
 
738
-      an expression is an accumulation of expression elements like literals, names,
 
739
-      attribute access, operators or function calls which all return a value.
 
740
-      In contrast to many other languages, not all language constructs are expressions.
 
741
-      There are also :term:`statement`\s which cannot be used as expressions,
 
742
-      such as :keyword:`print` or :keyword:`if`.  Assignments are also statements,
 
743
-      not expressions.
 
744
+      an expression is an accumulation of expression elements like literals,
 
745
+      names, attribute access, operators or function calls which all return a
 
746
+      value.  In contrast to many other languages, not all language constructs
 
747
+      are expressions.  There are also :term:`statement`\s which cannot be used
 
748
+      as expressions, such as :keyword:`print` or :keyword:`if`.  Assignments
 
749
+      are also statements, not expressions.
 
750
 
 
751
    extension module
 
752
       A module written in C or C++, using Python's C API to interact with the
 
753
       core and with user code.
 
754
 
 
755
+   file object
 
756
+      An object exposing a file-oriented API (with methods such as
 
757
+      :meth:`read()` or :meth:`write()`) to an underlying resource.  Depending
 
758
+      on the way it was created, a file object can mediate access to a real
 
759
+      on-disk file or to another other type of storage or communication device
 
760
+      (for example standard input/output, in-memory buffers, sockets, pipes,
 
761
+      etc.).  File objects are also called :dfn:`file-like objects` or
 
762
+      :dfn:`streams`.
 
763
+
 
764
+      There are actually three categories of file objects: raw binary files,
 
765
+      buffered binary files and text files.  Their interfaces are defined in the
 
766
+      :mod:`io` module.  The canonical way to create a file object is by using
 
767
+      the :func:`open` function.
 
768
+
 
769
+   file-like object
 
770
+      A synonym for :term:`file object`.
 
771
+
 
772
    finder
 
773
       An object that tries to find the :term:`loader` for a module. It must
 
774
       implement a method named :meth:`find_module`. See :pep:`302` for
 
775
@@ -334,7 +359,7 @@
 
776
       slowly.  See also :term:`interactive`.
 
777
 
 
778
    iterable
 
779
-      A container object capable of returning its members one at a
 
780
+      An object capable of returning its members one at a
 
781
       time. Examples of iterables include all sequence types (such as
 
782
       :class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence
 
783
       types like :class:`dict` and :class:`file` and objects of any classes you
 
784
@@ -403,6 +428,12 @@
 
785
       the :term:`EAFP` approach and is characterized by the presence of many
 
786
       :keyword:`if` statements.
 
787
 
 
788
+      In a multi-threaded environment, the LBYL approach can risk introducing a
 
789
+      race condition between "the looking" and "the leaping".  For example, the
 
790
+      code, ``if key in mapping: return mapping[key]`` can fail if another
 
791
+      thread removes *key* from *mapping* after the test, but before the lookup.
 
792
+      This issue can be solved with locks or by using the EAFP approach.
 
793
+
 
794
    list
 
795
       A built-in Python :term:`sequence`.  Despite its name it is more akin
 
796
       to an array in other languages than to a linked list since access to
 
797
@@ -423,9 +454,10 @@
 
798
 
303
799
    mapping
304
800
       A container object that supports arbitrary key lookups and implements the
305
 
       methods specified in the :class:`Mapping` or :class:`MutableMapping`
 
801
-      methods specified in the :class:`Mapping` or :class:`MutableMapping`
306
802
-      :ref:`abstract base classes <abstract-base-classes>`. Examples include
307
803
-      :class:`dict`, :class:`collections.defaultdict`,
 
804
+      methods specified in the :class:`~collections.Mapping` or
 
805
+      :class:`~collections.MutableMapping`
308
806
+      :ref:`abstract base classes <collections-abstract-base-classes>`.  Examples
309
807
+      include :class:`dict`, :class:`collections.defaultdict`,
310
808
       :class:`collections.OrderedDict` and :class:`collections.Counter`.
311
809
 
312
810
    metaclass
 
811
@@ -447,6 +479,14 @@
 
812
       its first :term:`argument` (which is usually called ``self``).
 
813
       See :term:`function` and :term:`nested scope`.
 
814
 
 
815
+   method resolution order
 
816
+      Method Resolution Order is the order in which base classes are searched
 
817
+      for a member during lookup. See `The Python 2.3 Method Resolution Order
 
818
+      <http://www.python.org/download/releases/2.3/mro/>`_.
 
819
+
 
820
+   MRO
 
821
+      See :term:`method resolution order`.
 
822
+
 
823
    mutable
 
824
       Mutable objects can change their value but keep their :func:`id`.  See
 
825
       also :term:`immutable`.
 
826
@@ -479,10 +519,11 @@
 
827
    nested scope
 
828
       The ability to refer to a variable in an enclosing definition.  For
 
829
       instance, a function defined inside another function can refer to
 
830
-      variables in the outer function.  Note that nested scopes work only for
 
831
-      reference and not for assignment which will always write to the innermost
 
832
-      scope.  In contrast, local variables both read and write in the innermost
 
833
-      scope.  Likewise, global variables read and write to the global namespace.
 
834
+      variables in the outer function.  Note that nested scopes by default work
 
835
+      only for reference and not for assignment.  Local variables both read and
 
836
+      write in the innermost scope.  Likewise, global variables read and write
 
837
+      to the global namespace.  The :keyword:`nonlocal` allows writing to outer
 
838
+      scopes.
 
839
 
 
840
    new-style class
 
841
       Any class which inherits from :class:`object`.  This includes all built-in
 
842
@@ -505,9 +546,9 @@
 
843
       :term:`argument`.
 
844
 
 
845
    Python 3000
 
846
-      Nickname for the next major Python version, 3.0 (coined long ago
 
847
-      when the release of version 3 was something in the distant future.)  This
 
848
-      is also abbreviated "Py3k".
 
849
+      Nickname for the Python 3.x release line (coined long ago when the release
 
850
+      of version 3 was something in the distant future.)  This is also
 
851
+      abbreviated "Py3k".
 
852
 
 
853
    Pythonic
 
854
       An idea or piece of code which closely follows the most common idioms
 
855
@@ -530,7 +571,7 @@
 
856
       object drops to zero, it is deallocated.  Reference counting is
 
857
       generally not visible to Python code, but it is a key element of the
 
858
       :term:`CPython` implementation.  The :mod:`sys` module defines a
 
859
-      :func:`getrefcount` function that programmers can call to return the
 
860
+      :func:`~sys.getrefcount` function that programmers can call to return the
 
861
       reference count for a particular object.
 
862
 
 
863
    __slots__
 
864
@@ -566,7 +607,15 @@
 
865
    statement
 
866
       A statement is part of a suite (a "block" of code).  A statement is either
 
867
       an :term:`expression` or a one of several constructs with a keyword, such
 
868
-      as :keyword:`if`, :keyword:`while` or :keyword:`print`.
 
869
+      as :keyword:`if`, :keyword:`while` or :keyword:`for`.
 
870
+
 
871
+   struct sequence
 
872
+      A tuple with named elements. Struct sequences expose an interface similiar
 
873
+      to :term:`named tuple` in that elements can either be accessed either by
 
874
+      index or as an attribute. However, they do not have any of the named tuple
 
875
+      methods like :meth:`~collections.somenamedtuple._make` or
 
876
+      :meth:`~collections.somenamedtuple._asdict`. Examples of struct sequences
 
877
+      include :data:`sys.float_info` and the return value of :func:`os.stat`.
 
878
 
 
879
    triple-quoted string
 
880
       A string which is bound by three instances of either a quotation mark
 
881
diff -r 8527427914a2 Doc/howto/cporting.rst
 
882
--- a/Doc/howto/cporting.rst
 
883
+++ b/Doc/howto/cporting.rst
 
884
@@ -1,5 +1,7 @@
 
885
 .. highlightlang:: c
 
886
 
 
887
+.. _cporting-howto:
 
888
+
 
889
 ********************************
 
890
 Porting Extension Modules to 3.0
 
891
 ********************************
 
892
@@ -207,6 +209,58 @@
 
893
    }
 
894
 
 
895
 
 
896
+CObject replaced with Capsule
 
897
+=============================
 
898
+
 
899
+The :ctype:`Capsule` object was introduced in Python 3.1 and 2.7 to replace
 
900
+:ctype:`CObject`.  CObjects were useful,
 
901
+but the :ctype:`CObject` API was problematic: it didn't permit distinguishing
 
902
+between valid CObjects, which allowed mismatched CObjects to crash the
 
903
+interpreter, and some of its APIs relied on undefined behavior in C.
 
904
+(For further reading on the rationale behind Capsules, please see :issue:`5630`.)
 
905
+
 
906
+If you're currently using CObjects, and you want to migrate to 3.1 or newer,
 
907
+you'll need to switch to Capsules.
 
908
+:ctype:`CObject` was deprecated in 3.1 and 2.7 and completely removed in
 
909
+Python 3.2.  If you only support 2.7, or 3.1 and above, you
 
910
+can simply switch to :ctype:`Capsule`.  If you need to support 3.0 or
 
911
+versions of Python earlier than 2.7 you'll have to support both CObjects
 
912
+and Capsules.
 
913
+
 
914
+The following example header file :file:`capsulethunk.h` may
 
915
+solve the problem for you;
 
916
+simply write your code against the :ctype:`Capsule` API, include
 
917
+this header file after ``"Python.h"``, and you'll automatically use CObjects
 
918
+in Python 3.0 or versions earlier than 2.7.
 
919
+
 
920
+:file:`capsulethunk.h` simulates Capsules using CObjects.  However,
 
921
+:ctype:`CObject` provides no place to store the capsule's "name".  As a
 
922
+result the simulated :ctype:`Capsule` objects created by :file:`capsulethunk.h`
 
923
+behave slightly differently from real Capsules.  Specifically:
 
924
+
 
925
+  * The name parameter passed in to :cfunc:`PyCapsule_New` is ignored.
 
926
+
 
927
+  * The name parameter passed in to :cfunc:`PyCapsule_IsValid` and
 
928
+    :cfunc:`PyCapsule_GetPointer` is ignored, and no error checking
 
929
+    of the name is performed.
 
930
+
 
931
+  * :cfunc:`PyCapsule_GetName` always returns NULL.
 
932
+
 
933
+  * :cfunc:`PyCapsule_SetName` always throws an exception and
 
934
+    returns failure.  (Since there's no way to store a name
 
935
+    in a CObject, noisy failure of :cfunc:`PyCapsule_SetName`
 
936
+    was deemed preferable to silent failure here.  If this is
 
937
+    inconveient, feel free to modify your local
 
938
+    copy as you see fit.)
 
939
+
 
940
+You can find :file:`capsulethunk.h` in the Python source distribution
 
941
+in the :file:`Doc/includes` directory.  We also include it here for
 
942
+your reference; here is :file:`capsulethunk.h`:
 
943
+
 
944
+.. literalinclude:: ../includes/capsulethunk.h
 
945
+
 
946
+
 
947
+
 
948
 Other options
 
949
 =============
 
950
 
313
951
diff -r 8527427914a2 Doc/howto/descriptor.rst
314
952
--- a/Doc/howto/descriptor.rst
315
953
+++ b/Doc/howto/descriptor.rst
325
963
diff -r 8527427914a2 Doc/howto/doanddont.rst
326
964
--- a/Doc/howto/doanddont.rst
327
965
+++ b/Doc/howto/doanddont.rst
 
966
@@ -32,8 +32,8 @@
 
967
 versions of Python do not check for the invalidity, it does not make it more
 
968
 valid, no more than having a smart lawyer makes a man innocent. Do not use it
 
969
 like that ever. Even in versions where it was accepted, it made the function
 
970
-execution slower, because the compiler could not be certain which names are
 
971
-local and which are global. In Python 2.1 this construct causes warnings, and
 
972
+execution slower, because the compiler could not be certain which names were
 
973
+local and which were global. In Python 2.1 this construct causes warnings, and
 
974
 sometimes even errors.
 
975
 
 
976
 
 
977
@@ -46,7 +46,7 @@
 
978
 in your favourite editor. You also open yourself to trouble in the future, if
 
979
 some module grows additional functions or classes.
 
980
 
 
981
-One of the most awful question asked on the newsgroup is why this code::
 
982
+One of the most awful questions asked on the newsgroup is why this code::
 
983
 
 
984
    f = open("www")
 
985
    f.read()
328
986
@@ -113,7 +113,7 @@
329
987
 
330
988
 This is a "don't" which is much weaker than the previous "don't"s but is still
334
992
 in two separate namespaces. When the binding in one namespace changes, the
335
993
 binding in the other will not, so there will be a discrepancy between them. This
336
994
 happens when, for example, one module is reloaded, or changes the definition of
 
995
diff -r 8527427914a2 Doc/howto/index.rst
 
996
--- a/Doc/howto/index.rst
 
997
+++ b/Doc/howto/index.rst
 
998
@@ -14,6 +14,7 @@
 
999
    :maxdepth: 1
 
1000
 
 
1001
    advocacy.rst
 
1002
+   pyporting.rst
 
1003
    cporting.rst
 
1004
    curses.rst
 
1005
    descriptor.rst
 
1006
diff -r 8527427914a2 Doc/howto/logging-cookbook.rst
 
1007
--- a/Doc/howto/logging-cookbook.rst
 
1008
+++ b/Doc/howto/logging-cookbook.rst
 
1009
@@ -610,9 +610,10 @@
 
1010
 to have all the processes log to a :class:`SocketHandler`, and have a separate
 
1011
 process which implements a socket server which reads from the socket and logs
 
1012
 to file. (If you prefer, you can dedicate one thread in one of the existing
 
1013
-processes to perform this function.) The following section documents this
 
1014
-approach in more detail and includes a working socket receiver which can be
 
1015
-used as a starting point for you to adapt in your own applications.
 
1016
+processes to perform this function.) :ref:`This section <network-logging>`
 
1017
+documents this approach in more detail and includes a working socket receiver
 
1018
+which can be used as a starting point for you to adapt in your own
 
1019
+applications.
 
1020
 
 
1021
 If you are using a recent version of Python which includes the
 
1022
 :mod:`multiprocessing` module, you could write your own handler which uses the
 
1023
@@ -679,6 +680,68 @@
 
1024
 ``.1``. Each of the existing backup files is renamed to increment the suffix
 
1025
 (``.1`` becomes ``.2``, etc.)  and the ``.6`` file is erased.
 
1026
 
 
1027
-Obviously this example sets the log length much much too small as an extreme
 
1028
+Obviously this example sets the log length much too small as an extreme
 
1029
 example.  You would want to set *maxBytes* to an appropriate value.
 
1030
 
 
1031
+An example dictionary-based configuration
 
1032
+-----------------------------------------
 
1033
+
 
1034
+Below is an example of a logging configuration dictionary - it's taken from
 
1035
+the `documentation on the Django project <https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging>`_.
 
1036
+This dictionary is passed to :func:`~logging.config.dictConfig` to put the configuration into effect::
 
1037
+
 
1038
+    LOGGING = {
 
1039
+        'version': 1,
 
1040
+        'disable_existing_loggers': True,
 
1041
+        'formatters': {
 
1042
+            'verbose': {
 
1043
+                'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
 
1044
+            },
 
1045
+            'simple': {
 
1046
+                'format': '%(levelname)s %(message)s'
 
1047
+            },
 
1048
+        },
 
1049
+        'filters': {
 
1050
+            'special': {
 
1051
+                '()': 'project.logging.SpecialFilter',
 
1052
+                'foo': 'bar',
 
1053
+            }
 
1054
+        },
 
1055
+        'handlers': {
 
1056
+            'null': {
 
1057
+                'level':'DEBUG',
 
1058
+                'class':'django.utils.log.NullHandler',
 
1059
+            },
 
1060
+            'console':{
 
1061
+                'level':'DEBUG',
 
1062
+                'class':'logging.StreamHandler',
 
1063
+                'formatter': 'simple'
 
1064
+            },
 
1065
+            'mail_admins': {
 
1066
+                'level': 'ERROR',
 
1067
+                'class': 'django.utils.log.AdminEmailHandler',
 
1068
+                'filters': ['special']
 
1069
+            }
 
1070
+        },
 
1071
+        'loggers': {
 
1072
+            'django': {
 
1073
+                'handlers':['null'],
 
1074
+                'propagate': True,
 
1075
+                'level':'INFO',
 
1076
+            },
 
1077
+            'django.request': {
 
1078
+                'handlers': ['mail_admins'],
 
1079
+                'level': 'ERROR',
 
1080
+                'propagate': False,
 
1081
+            },
 
1082
+            'myproject.custom': {
 
1083
+                'handlers': ['console', 'mail_admins'],
 
1084
+                'level': 'INFO',
 
1085
+                'filters': ['special']
 
1086
+            }
 
1087
+        }
 
1088
+    }
 
1089
+
 
1090
+For more information about this configuration, you can see the `relevant
 
1091
+section <https://docs.djangoproject.com/en/1.3/topics/logging/#configuring-logging>`_
 
1092
+of the Django documentation.
 
1093
diff -r 8527427914a2 Doc/howto/logging.rst
 
1094
--- a/Doc/howto/logging.rst
 
1095
+++ b/Doc/howto/logging.rst
 
1096
@@ -670,7 +670,7 @@
 
1097
     version: 1
 
1098
     formatters:
 
1099
       simple:
 
1100
-        format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
 
1101
+        format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
 
1102
     handlers:
 
1103
       console:
 
1104
         class: logging.StreamHandler
 
1105
diff -r 8527427914a2 Doc/howto/pyporting.rst
 
1106
--- /dev/null
 
1107
+++ b/Doc/howto/pyporting.rst
 
1108
@@ -0,0 +1,703 @@
 
1109
+.. _pyporting-howto:
 
1110
+
 
1111
+*********************************
 
1112
+Porting Python 2 Code to Python 3
 
1113
+*********************************
 
1114
+
 
1115
+:author: Brett Cannon
 
1116
+
 
1117
+.. topic:: Abstract
 
1118
+
 
1119
+   With Python 3 being the future of Python while Python 2 is still in active
 
1120
+   use, it is good to have your project available for both major releases of
 
1121
+   Python. This guide is meant to help you choose which strategy works best
 
1122
+   for your project to support both Python 2 & 3 along with how to execute
 
1123
+   that strategy.
 
1124
+
 
1125
+   If you are looking to port an extension module instead of pure Python code,
 
1126
+   please see :ref:`cporting-howto`.
 
1127
+
 
1128
+
 
1129
+Choosing a Strategy
 
1130
+===================
 
1131
+
 
1132
+When a project makes the decision that it's time to support both Python 2 & 3,
 
1133
+a decision needs to be made as to how to go about accomplishing that goal.
 
1134
+The chosen strategy will depend on how large the project's existing
 
1135
+codebase is and how much divergence you want from your Python 2 codebase from
 
1136
+your Python 3 one (e.g., starting a new version with Python 3).
 
1137
+
 
1138
+If your project is brand-new or does not have a large codebase, then you may
 
1139
+want to consider writing/porting :ref:`all of your code for Python 3
 
1140
+and use 3to2 <use_3to2>` to port your code for Python 2.
 
1141
+
 
1142
+If you would prefer to maintain a codebase which is semantically **and**
 
1143
+syntactically compatible with Python 2 & 3 simultaneously, you can write
 
1144
+:ref:`use_same_source`. While this tends to lead to somewhat non-idiomatic
 
1145
+code, it does mean you keep a rapid development process for you, the developer.
 
1146
+
 
1147
+Finally, you do have the option of :ref:`using 2to3 <use_2to3>` to translate
 
1148
+Python 2 code into Python 3 code (with some manual help). This can take the
 
1149
+form of branching your code and using 2to3 to start a Python 3 branch. You can
 
1150
+also have users perform the translation as installation time automatically so
 
1151
+that you only have to maintain a Python 2 codebase.
 
1152
+
 
1153
+Regardless of which approach you choose, porting is not as hard or
 
1154
+time-consuming as you might initially think. You can also tackle the problem
 
1155
+piece-meal as a good portion of porting is simply updating your code to follow
 
1156
+current best practices in a Python 2/3 compatible way.
 
1157
+
 
1158
+
 
1159
+Universal Bits of Advice
 
1160
+------------------------
 
1161
+
 
1162
+Regardless of what strategy you pick, there are a few things you should
 
1163
+consider.
 
1164
+
 
1165
+One is make sure you have a robust test suite. You need to make sure everything
 
1166
+continues to work, just like when you support a new minor version of Python.
 
1167
+This means making sure your test suite is thorough and is ported properly
 
1168
+between Python 2 & 3. You will also most likely want to use something like tox_
 
1169
+to automate testing between both a Python 2 and Python 3 VM.
 
1170
+
 
1171
+Two, once your project has Python 3 support, make sure to add the proper
 
1172
+classifier on the Cheeseshop_ (PyPI_). To have your project listed as Python 3
 
1173
+compatible it must have the
 
1174
+`Python 3 classifier <http://pypi.python.org/pypi?:action=browse&c=533>`_
 
1175
+(from
 
1176
+http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/)::
 
1177
+
 
1178
+   setup(
 
1179
+     name='Your Library',
 
1180
+     version='1.0',
 
1181
+     classifiers=[
 
1182
+         # make sure to use :: Python *and* :: Python :: 3 so
 
1183
+         # that pypi can list the package on the python 3 page
 
1184
+         'Programming Language :: Python',
 
1185
+         'Programming Language :: Python :: 3'
 
1186
+     ],
 
1187
+     packages=['yourlibrary'],
 
1188
+     # make sure to add custom_fixers to the MANIFEST.in
 
1189
+     include_package_data=True,
 
1190
+     # ...
 
1191
+   )
 
1192
+
 
1193
+
 
1194
+Doing so will cause your project to show up in the
 
1195
+`Python 3 packages list
 
1196
+<http://pypi.python.org/pypi?:action=browse&c=533&show=all>`_. You will know
 
1197
+you set the classifier properly as visiting your project page on the Cheeseshop
 
1198
+will show a Python 3 logo in the upper-left corner of the page.
 
1199
+
 
1200
+Three, the six_ project provides a library which helps iron out differences
 
1201
+between Python 2 & 3. If you find there is a sticky point that is a continual
 
1202
+point of contention in your translation or maintenance of code, consider using
 
1203
+a source-compatible solution relying on six. If you have to create your own
 
1204
+Python 2/3 compatible solution, you can use ``sys.version_info[0] >= 3`` as a
 
1205
+guard.
 
1206
+
 
1207
+Four, read all the approaches. Just because some bit of advice applies to one
 
1208
+approach more than another doesn't mean that some advice doesn't apply to other
 
1209
+strategies.
 
1210
+
 
1211
+Five, drop support for older Python versions if possible. `Python 2.5`_
 
1212
+introduced a lot of useful syntax and libraries which have become idiomatic
 
1213
+in Python 3. `Python 2.6`_ introduced future statements which makes
 
1214
+compatibility much easier if you are going from Python 2 to 3.
 
1215
+`Python 2.7`_ continues the trend in the stdlib. So choose the newest version
 
1216
+of Python which you believe can be your minimum support version
 
1217
+and work from there.
 
1218
+
 
1219
+
 
1220
+.. _tox: http://codespeak.net/tox/
 
1221
+.. _Cheeseshop:
 
1222
+.. _PyPI: http://pypi.python.org/
 
1223
+.. _six: http://packages.python.org/six
 
1224
+.. _Python 2.7: http://www.python.org/2.7.x
 
1225
+.. _Python 2.6: http://www.python.org/2.6.x
 
1226
+.. _Python 2.5: http://www.python.org/2.5.x
 
1227
+.. _Python 2.4: http://www.python.org/2.4.x
 
1228
+.. _Python 2.3: http://www.python.org/2.3.x
 
1229
+.. _Python 2.2: http://www.python.org/2.2.x
 
1230
+
 
1231
+
 
1232
+.. _use_3to2:
 
1233
+
 
1234
+Python 3 and 3to2
 
1235
+=================
 
1236
+
 
1237
+If you are starting a new project or your codebase is small enough, you may
 
1238
+want to consider writing your code for Python 3 and backporting to Python 2
 
1239
+using 3to2_. Thanks to Python 3 being more strict about things than Python 2
 
1240
+(e.g., bytes vs. strings), the source translation can be easier and more
 
1241
+straightforward than from Python 2 to 3. Plus it gives you more direct
 
1242
+experience developing in Python 3 which, since it is the future of Python, is a
 
1243
+good thing long-term.
 
1244
+
 
1245
+A drawback of this approach is that 3to2 is a third-party project. This means
 
1246
+that the Python core developers (and thus this guide) can make no promises
 
1247
+about how well 3to2 works at any time. There is nothing to suggest, though,
 
1248
+that 3to2 is not a high-quality project.
 
1249
+
 
1250
+
 
1251
+.. _3to2: https://bitbucket.org/amentajo/lib3to2/overview
 
1252
+
 
1253
+
 
1254
+.. _use_2to3:
 
1255
+
 
1256
+Python 2 and 2to3
 
1257
+=================
 
1258
+
 
1259
+Included with Python since 2.6, the 2to3_ tool (and :mod:`lib2to3` module)
 
1260
+helps with porting Python 2 to Python 3 by performing various source
 
1261
+translations. This is a perfect solution for projects which wish to branch
 
1262
+their Python 3 code from their Python 2 codebase and maintain them as
 
1263
+independent codebases. You can even begin preparing to use this approach
 
1264
+today by writing future-compatible Python code which works cleanly in
 
1265
+Python 2 in conjunction with 2to3; all steps outlined below will work
 
1266
+with Python 2 code up to the point when the actual use of 2to3 occurs.
 
1267
+
 
1268
+Use of 2to3 as an on-demand translation step at install time is also possible,
 
1269
+preventing the need to maintain a separate Python 3 codebase, but this approach
 
1270
+does come with some drawbacks. While users will only have to pay the
 
1271
+translation cost once at installation, you as a developer will need to pay the
 
1272
+cost regularly during development. If your codebase is sufficiently large
 
1273
+enough then the translation step ends up acting like a compilation step,
 
1274
+robbing you of the rapid development process you are used to with Python.
 
1275
+Obviously the time required to translate a project will vary, so do an
 
1276
+experimental translation just to see how long it takes to evaluate whether you
 
1277
+prefer this approach compared to using :ref:`use_same_source` or simply keeping
 
1278
+a separate Python 3 codebase.
 
1279
+
 
1280
+Below are the typical steps taken by a project which uses a 2to3-based approach
 
1281
+to supporting Python 2 & 3.
 
1282
+
 
1283
+
 
1284
+Support Python 2.7
 
1285
+------------------
 
1286
+
 
1287
+As a first step, make sure that your project is compatible with `Python 2.7`_.
 
1288
+This is just good to do as Python 2.7 is the last release of Python 2 and thus
 
1289
+will be used for a rather long time. It also allows for use of the ``-3`` flag
 
1290
+to Python to help discover places in your code which 2to3 cannot handle but are
 
1291
+known to cause issues.
 
1292
+
 
1293
+Try to Support `Python 2.6`_ and Newer Only
 
1294
+-------------------------------------------
 
1295
+
 
1296
+While not possible for all projects, if you can support `Python 2.6`_ and newer
 
1297
+**only**, your life will be much easier. Various future statements, stdlib
 
1298
+additions, etc. exist only in Python 2.6 and later which greatly assist in
 
1299
+porting to Python 3. But if you project must keep support for `Python 2.5`_ (or
 
1300
+even `Python 2.4`_) then it is still possible to port to Python 3.
 
1301
+
 
1302
+Below are the benefits you gain if you only have to support Python 2.6 and
 
1303
+newer. Some of these options are personal choice while others are
 
1304
+**strongly** recommended (the ones that are more for personal choice are
 
1305
+labeled as such).  If you continue to support older versions of Python then you
 
1306
+at least need to watch out for situations that these solutions fix.
 
1307
+
 
1308
+
 
1309
+``from __future__ import print_function``
 
1310
+'''''''''''''''''''''''''''''''''''''''''
 
1311
+
 
1312
+This is a personal choice. 2to3 handles the translation from the print
 
1313
+statement to the print function rather well so this is an optional step. This
 
1314
+future statement does help, though, with getting used to typing
 
1315
+``print('Hello, World')`` instead of ``print 'Hello, World'``.
 
1316
+
 
1317
+
 
1318
+``from __future__ import unicode_literals``
 
1319
+'''''''''''''''''''''''''''''''''''''''''''
 
1320
+
 
1321
+Another personal choice. You can always mark what you want to be a (unicode)
 
1322
+string with a ``u`` prefix to get the same effect. But regardless of whether
 
1323
+you use this future statement or not, you **must** make sure you know exactly
 
1324
+which Python 2 strings you want to be bytes, and which are to be strings. This
 
1325
+means you should, **at minimum** mark all strings that are meant to be text
 
1326
+strings with a ``u`` prefix if you do not use this future statement.
 
1327
+
 
1328
+
 
1329
+Bytes literals
 
1330
+''''''''''''''
 
1331
+
 
1332
+This is a **very** important one. The ability to prefix Python 2 strings that
 
1333
+are meant to contain bytes with a ``b`` prefix help to very clearly delineate
 
1334
+what is and is not a Python 3 string. When you run 2to3 on code, all Python 2
 
1335
+strings become Python 3 strings **unless** they are prefixed with ``b``.
 
1336
+
 
1337
+There are some differences between byte literals in Python 2 and those in
 
1338
+Python 3 thanks to the bytes type just being an alias to ``str`` in Python 2.
 
1339
+Probably the biggest "gotcha" is that indexing results in different values. In
 
1340
+Python 2, the value of ``b'py'[1]`` is ``'y'``, while in Python 3 it's ``121``.
 
1341
+You can avoid this disparity by always slicing at the size of a single element:
 
1342
+``b'py'[1:2]`` is ``'y'`` in Python 2 and ``b'y'`` in Python 3 (i.e., close
 
1343
+enough).
 
1344
+
 
1345
+You cannot concatenate bytes and strings in Python 3. But since in Python
 
1346
+2 has bytes aliased to ``str``, it will succeed: ``b'a' + u'b'`` works in
 
1347
+Python 2, but ``b'a' + 'b'`` in Python 3 is a :exc:`TypeError`. A similar issue
 
1348
+also comes about when doing comparisons between bytes and strings.
 
1349
+
 
1350
+
 
1351
+Supporting `Python 2.5`_ and Newer Only
 
1352
+---------------------------------------
 
1353
+
 
1354
+If you are supporting `Python 2.5`_ and newer there are still some features of
 
1355
+Python that you can utilize.
 
1356
+
 
1357
+
 
1358
+``from __future__ import absolute_import``
 
1359
+''''''''''''''''''''''''''''''''''''''''''
 
1360
+
 
1361
+Implicit relative imports (e.g., importing ``spam.bacon`` from within
 
1362
+``spam.eggs`` with the statement ``import bacon``) does not work in Python 3.
 
1363
+This future statement moves away from that and allows the use of explicit
 
1364
+relative imports (e.g., ``from . import bacon``).
 
1365
+
 
1366
+In `Python 2.5`_ you must use
 
1367
+the __future__ statement to get to use explicit relative imports and prevent
 
1368
+implicit ones. In `Python 2.6`_ explicit relative imports are available without
 
1369
+the statement, but you still want the __future__ statement to prevent implicit
 
1370
+relative imports. In `Python 2.7`_ the __future__ statement is not needed. In
 
1371
+other words, unless you are only supporting Python 2.7 or a version earlier
 
1372
+than Python 2.5, use the __future__ statement.
 
1373
+
 
1374
+
 
1375
+
 
1376
+Handle Common "Gotchas"
 
1377
+-----------------------
 
1378
+
 
1379
+There are a few things that just consistently come up as sticking points for
 
1380
+people which 2to3 cannot handle automatically or can easily be done in Python 2
 
1381
+to help modernize your code.
 
1382
+
 
1383
+
 
1384
+``from __future__ import division``
 
1385
+'''''''''''''''''''''''''''''''''''
 
1386
+
 
1387
+While the exact same outcome can be had by using the ``-Qnew`` argument to
 
1388
+Python, using this future statement lifts the requirement that your users use
 
1389
+the flag to get the expected behavior of division in Python 3
 
1390
+(e.g., ``1/2 == 0.5; 1//2 == 0``).
 
1391
+
 
1392
+
 
1393
+
 
1394
+Specify when opening a file as binary
 
1395
+'''''''''''''''''''''''''''''''''''''
 
1396
+
 
1397
+Unless you have been working on Windows, there is a chance you have not always
 
1398
+bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for
 
1399
+binary reading).  Under Python 3, binary files and text files are clearly
 
1400
+distinct and mutually incompatible; see the :mod:`io` module for details.
 
1401
+Therefore, you **must** make a decision of whether a file will be used for
 
1402
+binary access (allowing to read and/or write bytes data) or text access
 
1403
+(allowing to read and/or write unicode data).
 
1404
+
 
1405
+Text files
 
1406
+''''''''''
 
1407
+
 
1408
+Text files created using ``open()`` under Python 2 return byte strings,
 
1409
+while under Python 3 they return unicode strings.  Depending on your porting
 
1410
+strategy, this can be an issue.
 
1411
+
 
1412
+If you want text files to return unicode strings in Python 2, you have two
 
1413
+possibilities:
 
1414
+
 
1415
+* Under Python 2.6 and higher, use :func:`io.open`.  Since :func:`io.open`
 
1416
+  is essentially the same function in both Python 2 and Python 3, it will
 
1417
+  help iron out any issues that might arise.
 
1418
+
 
1419
+* If pre-2.6 compatibility is needed, then you should use :func:`codecs.open`
 
1420
+  instead.  This will make sure that you get back unicode strings in Python 2.
 
1421
+
 
1422
+Subclass ``object``
 
1423
+'''''''''''''''''''
 
1424
+
 
1425
+New-style classes have been around since `Python 2.2`_. You need to make sure
 
1426
+you are subclassing from ``object`` to avoid odd edge cases involving method
 
1427
+resolution order, etc. This continues to be totally valid in Python 3 (although
 
1428
+unneeded as all classes implicitly inherit from ``object``).
 
1429
+
 
1430
+
 
1431
+Deal With the Bytes/String Dichotomy
 
1432
+''''''''''''''''''''''''''''''''''''
 
1433
+
 
1434
+One of the biggest issues people have when porting code to Python 3 is handling
 
1435
+the bytes/string dichotomy. Because Python 2 allowed the ``str`` type to hold
 
1436
+textual data, people have over the years been rather loose in their delineation
 
1437
+of what ``str`` instances held text compared to bytes. In Python 3 you cannot
 
1438
+be so care-free anymore and need to properly handle the difference. The key
 
1439
+handling this issue to make sure that **every** string literal in your
 
1440
+Python 2 code is either syntactically of functionally marked as either bytes or
 
1441
+text data. After this is done you then need to make sure your APIs are designed
 
1442
+to either handle a specific type or made to be properly polymorphic.
 
1443
+
 
1444
+
 
1445
+Mark Up Python 2 String Literals
 
1446
+********************************
 
1447
+
 
1448
+First thing you must do is designate every single string literal in Python 2
 
1449
+as either textual or bytes data. If you are only supporting Python 2.6 or
 
1450
+newer, this can be accomplished by marking bytes literals with a ``b`` prefix
 
1451
+and then designating textual data with a ``u`` prefix or using the
 
1452
+``unicode_literals`` future statement.
 
1453
+
 
1454
+If your project supports versions of Python pre-dating 2.6, then you should use
 
1455
+the six_ project and its ``b()`` function to denote bytes literals. For text
 
1456
+literals you can either use six's ``u()`` function or use a ``u`` prefix.
 
1457
+
 
1458
+
 
1459
+Decide what APIs Will Accept
 
1460
+****************************
 
1461
+
 
1462
+In Python 2 it was very easy to accidentally create an API that accepted both
 
1463
+bytes and textual data. But in Python 3, thanks to the more strict handling of
 
1464
+disparate types, this loose usage of bytes and text together tends to fail.
 
1465
+
 
1466
+Take the dict ``{b'a': 'bytes', u'a': 'text'}`` in Python 2.6. It creates the
 
1467
+dict ``{u'a': 'text'}`` since ``b'a' == u'a'``. But in Python 3 the equivalent
 
1468
+dict creates ``{b'a': 'bytes', 'a': 'text'}``, i.e., no lost data. Similar
 
1469
+issues can crop up when transitioning Python 2 code to Python 3.
 
1470
+
 
1471
+This means you need to choose what an API is going to accept and create and
 
1472
+consistently stick to that API in both Python 2 and 3.
 
1473
+
 
1474
+
 
1475
+Bytes / Unicode Comparison
 
1476
+**************************
 
1477
+
 
1478
+In Python 3, mixing bytes and unicode is forbidden in most situations; it
 
1479
+will raise a :class:`TypeError` where Python 2 would have attempted an implicit
 
1480
+coercion between types.  However, there is one case where it doesn't and
 
1481
+it can be very misleading::
 
1482
+
 
1483
+   >>> b"" == ""
 
1484
+   False
 
1485
+
 
1486
+This is because an equality comparison is required by the language to always
 
1487
+succeed (and return ``False`` for incompatible types).  However, this also
 
1488
+means that code incorrectly ported to Python 3 can display buggy behaviour
 
1489
+if such comparisons are silently executed.  To detect such situations,
 
1490
+Python 3 has a ``-b`` flag that will display a warning::
 
1491
+
 
1492
+   $ python3 -b
 
1493
+   >>> b"" == ""
 
1494
+   __main__:1: BytesWarning: Comparison between bytes and string
 
1495
+   False
 
1496
+
 
1497
+To turn the warning into an exception, use the ``-bb`` flag instead::
 
1498
+
 
1499
+   $ python3 -bb
 
1500
+   >>> b"" == ""
 
1501
+   Traceback (most recent call last):
 
1502
+     File "<stdin>", line 1, in <module>
 
1503
+   BytesWarning: Comparison between bytes and string
 
1504
+
 
1505
+
 
1506
+Indexing bytes objects
 
1507
+''''''''''''''''''''''
 
1508
+
 
1509
+Another potentially surprising change is the indexing behaviour of bytes
 
1510
+objects in Python 3::
 
1511
+
 
1512
+   >>> b"xyz"[0]
 
1513
+   120
 
1514
+
 
1515
+Indeed, Python 3 bytes objects (as well as :class:`bytearray` objects)
 
1516
+are sequences of integers.  But code converted from Python 2 will often
 
1517
+assume that indexing a bytestring produces another bytestring, not an
 
1518
+integer.  To reconcile both behaviours, use slicing::
 
1519
+
 
1520
+   >>> b"xyz"[0:1]
 
1521
+   b'x'
 
1522
+   >>> n = 1
 
1523
+   >>> b"xyz"[n:n+1]
 
1524
+   b'y'
 
1525
+
 
1526
+The only remaining gotcha is that an out-of-bounds slice returns an empty
 
1527
+bytes object instead of raising ``IndexError``:
 
1528
+
 
1529
+   >>> b"xyz"[3]
 
1530
+   Traceback (most recent call last):
 
1531
+     File "<stdin>", line 1, in <module>
 
1532
+   IndexError: index out of range
 
1533
+   >>> b"xyz"[3:4]
 
1534
+   b''
 
1535
+
 
1536
+
 
1537
+``__str__()``/``__unicode__()``
 
1538
+'''''''''''''''''''''''''''''''
 
1539
+
 
1540
+In Python 2, objects can specify both a string and unicode representation of
 
1541
+themselves. In Python 3, though, there is only a string representation. This
 
1542
+becomes an issue as people can inadvertently do things in their ``__str__()``
 
1543
+methods which have unpredictable results (e.g., infinite recursion if you
 
1544
+happen to use the ``unicode(self).encode('utf8')`` idiom as the body of your
 
1545
+``__str__()`` method).
 
1546
+
 
1547
+There are two ways to solve this issue. One is to use a custom 2to3 fixer. The
 
1548
+blog post at http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
 
1549
+specifies how to do this. That will allow 2to3 to change all instances of ``def
 
1550
+__unicode(self): ...`` to ``def __str__(self): ...``. This does require you
 
1551
+define your ``__str__()`` method in Python 2 before your ``__unicode__()``
 
1552
+method.
 
1553
+
 
1554
+The other option is to use a mixin class. This allows you to only define a
 
1555
+``__unicode__()`` method for your class and let the mixin derive
 
1556
+``__str__()`` for you (code from
 
1557
+http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/)::
 
1558
+
 
1559
+   import sys
 
1560
+
 
1561
+   class UnicodeMixin(object):
 
1562
+
 
1563
+     """Mixin class to handle defining the proper __str__/__unicode__
 
1564
+     methods in Python 2 or 3."""
 
1565
+
 
1566
+     if sys.version_info[0] >= 3: # Python 3
 
1567
+         def __str__(self):
 
1568
+             return self.__unicode__()
 
1569
+     else:  # Python 2
 
1570
+         def __str__(self):
 
1571
+             return self.__unicode__().encode('utf8')
 
1572
+
 
1573
+
 
1574
+   class Spam(UnicodeMixin):
 
1575
+
 
1576
+     def __unicode__(self):
 
1577
+         return u'spam-spam-bacon-spam'  # 2to3 will remove the 'u' prefix
 
1578
+
 
1579
+
 
1580
+Don't Index on Exceptions
 
1581
+'''''''''''''''''''''''''
 
1582
+
 
1583
+In Python 2, the following worked::
 
1584
+
 
1585
+   >>> exc = Exception(1, 2, 3)
 
1586
+   >>> exc.args[1]
 
1587
+   2
 
1588
+   >>> exc[1]  # Python 2 only!
 
1589
+   2
 
1590
+
 
1591
+But in Python 3, indexing directly on an exception is an error. You need to
 
1592
+make sure to only index on the :attr:`BaseException.args` attribute which is a
 
1593
+sequence containing all arguments passed to the :meth:`__init__` method.
 
1594
+
 
1595
+Even better is to use the documented attributes the exception provides.
 
1596
+
 
1597
+Don't use ``__getslice__`` & Friends
 
1598
+''''''''''''''''''''''''''''''''''''
 
1599
+
 
1600
+Been deprecated for a while, but Python 3 finally drops support for
 
1601
+``__getslice__()``, etc. Move completely over to :meth:`__getitem__` and
 
1602
+friends.
 
1603
+
 
1604
+
 
1605
+Updating doctests
 
1606
+'''''''''''''''''
 
1607
+
 
1608
+2to3_ will attempt to generate fixes for doctests that it comes across. It's
 
1609
+not perfect, though. If you wrote a monolithic set of doctests (e.g., a single
 
1610
+docstring containing all of your doctests), you should at least consider
 
1611
+breaking the doctests up into smaller pieces to make it more manageable to fix.
 
1612
+Otherwise it might very well be worth your time and effort to port your tests
 
1613
+to :mod:`unittest`.
 
1614
+
 
1615
+
 
1616
+Eliminate ``-3`` Warnings
 
1617
+-------------------------
 
1618
+
 
1619
+When you run your application's test suite, run it using the ``-3`` flag passed
 
1620
+to Python. This will cause various warnings to be raised during execution about
 
1621
+things that 2to3 cannot handle automatically (e.g., modules that have been
 
1622
+removed). Try to eliminate those warnings to make your code even more portable
 
1623
+to Python 3.
 
1624
+
 
1625
+
 
1626
+Run 2to3
 
1627
+--------
 
1628
+
 
1629
+Once you have made your Python 2 code future-compatible with Python 3, it's
 
1630
+time to use 2to3_ to actually port your code.
 
1631
+
 
1632
+
 
1633
+Manually
 
1634
+''''''''
 
1635
+
 
1636
+To manually convert source code using 2to3_, you use the ``2to3`` script that
 
1637
+is installed with Python 2.6 and later.::
 
1638
+
 
1639
+   2to3 <directory or file to convert>
 
1640
+
 
1641
+This will cause 2to3 to write out a diff with all of the fixers applied for the
 
1642
+converted source code. If you would like 2to3 to go ahead and apply the changes
 
1643
+you can pass it the ``-w`` flag::
 
1644
+
 
1645
+   2to3 -w <stuff to convert>
 
1646
+
 
1647
+There are other flags available to control exactly which fixers are applied,
 
1648
+etc.
 
1649
+
 
1650
+
 
1651
+During Installation
 
1652
+'''''''''''''''''''
 
1653
+
 
1654
+When a user installs your project for Python 3, you can have either
 
1655
+:mod:`distutils` or Distribute_ run 2to3_ on your behalf.
 
1656
+For distutils, use the following idiom::
 
1657
+
 
1658
+   try:  # Python 3
 
1659
+     from distutils.command.build_py import build_py_2to3 as build_py
 
1660
+   except ImportError:  # Python 2
 
1661
+     from distutils.command.build_py import build_py
 
1662
+
 
1663
+   setup(cmdclass = {'build_py': build_py},
 
1664
+     # ...
 
1665
+   )
 
1666
+
 
1667
+For Distribute::
 
1668
+
 
1669
+   setup(use_2to3=True,
 
1670
+     # ...
 
1671
+   )
 
1672
+
 
1673
+This will allow you to not have to distribute a separate Python 3 version of
 
1674
+your project. It does require, though, that when you perform development that
 
1675
+you at least build your project and use the built Python 3 source for testing.
 
1676
+
 
1677
+
 
1678
+Verify & Test
 
1679
+-------------
 
1680
+
 
1681
+At this point you should (hopefully) have your project converted in such a way
 
1682
+that it works in Python 3. Verify it by running your unit tests and making sure
 
1683
+nothing has gone awry. If you miss something then figure out how to fix it in
 
1684
+Python 3, backport to your Python 2 code, and run your code through 2to3 again
 
1685
+to verify the fix transforms properly.
 
1686
+
 
1687
+
 
1688
+.. _2to3: http://docs.python.org/py3k/library/2to3.html
 
1689
+.. _Distribute: http://packages.python.org/distribute/
 
1690
+
 
1691
+
 
1692
+.. _use_same_source:
 
1693
+
 
1694
+Python 2/3 Compatible Source
 
1695
+============================
 
1696
+
 
1697
+While it may seem counter-intuitive, you can write Python code which is
 
1698
+source-compatible between Python 2 & 3. It does lead to code that is not
 
1699
+entirely idiomatic Python (e.g., having to extract the currently raised
 
1700
+exception from ``sys.exc_info()[1]``), but it can be run under Python 2
 
1701
+**and** Python 3 without using 2to3_ as a translation step (although the tool
 
1702
+should be used to help find potential portability problems). This allows you to
 
1703
+continue to have a rapid development process regardless of whether you are
 
1704
+developing under Python 2 or Python 3. Whether this approach or using
 
1705
+:ref:`use_2to3` works best for you will be a per-project decision.
 
1706
+
 
1707
+To get a complete idea of what issues you will need to deal with, see the
 
1708
+`What's New in Python 3.0`_. Others have reorganized the data in other formats
 
1709
+such as http://docs.pythonsprints.com/python3_porting/py-porting.html .
 
1710
+
 
1711
+The following are some steps to take to try to support both Python 2 & 3 from
 
1712
+the same source code.
 
1713
+
 
1714
+
 
1715
+.. _What's New in Python 3.0: http://docs.python.org/release/3.0/whatsnew/3.0.html
 
1716
+
 
1717
+
 
1718
+Follow The Steps for Using 2to3_
 
1719
+--------------------------------
 
1720
+
 
1721
+All of the steps outlined in how to
 
1722
+:ref:`port Python 2 code with 2to3 <use_2to3>` apply
 
1723
+to creating a Python 2/3 codebase. This includes trying only support Python 2.6
 
1724
+or newer (the :mod:`__future__` statements work in Python 3 without issue),
 
1725
+eliminating warnings that are triggered by ``-3``, etc.
 
1726
+
 
1727
+You should even consider running 2to3_ over your code (without committing the
 
1728
+changes). This will let you know where potential pain points are within your
 
1729
+code so that you can fix them properly before they become an issue.
 
1730
+
 
1731
+
 
1732
+Use six_
 
1733
+--------
 
1734
+
 
1735
+The six_ project contains many things to help you write portable Python code.
 
1736
+You should make sure to read its documentation from beginning to end and use
 
1737
+any and all features it provides. That way you will minimize any mistakes you
 
1738
+might make in writing cross-version code.
 
1739
+
 
1740
+
 
1741
+Capturing the Currently Raised Exception
 
1742
+----------------------------------------
 
1743
+
 
1744
+One change between Python 2 and 3 that will require changing how you code (if
 
1745
+you support `Python 2.5`_ and earlier) is
 
1746
+accessing the currently raised exception.  In Python 2.5 and earlier the syntax
 
1747
+to access the current exception is::
 
1748
+
 
1749
+   try:
 
1750
+     raise Exception()
 
1751
+   except Exception, exc:
 
1752
+     # Current exception is 'exc'
 
1753
+     pass
 
1754
+
 
1755
+This syntax changed in Python 3 (and backported to `Python 2.6`_ and later)
 
1756
+to::
 
1757
+
 
1758
+   try:
 
1759
+     raise Exception()
 
1760
+   except Exception as exc:
 
1761
+     # Current exception is 'exc'
 
1762
+     # In Python 3, 'exc' is restricted to the block; Python 2.6 will "leak"
 
1763
+     pass
 
1764
+
 
1765
+Because of this syntax change you must change to capturing the current
 
1766
+exception to::
 
1767
+
 
1768
+   try:
 
1769
+     raise Exception()
 
1770
+   except Exception:
 
1771
+     import sys
 
1772
+     exc = sys.exc_info()[1]
 
1773
+     # Current exception is 'exc'
 
1774
+     pass
 
1775
+
 
1776
+You can get more information about the raised exception from
 
1777
+:func:`sys.exc_info` than simply the current exception instance, but you most
 
1778
+likely don't need it.
 
1779
+
 
1780
+.. note::
 
1781
+   In Python 3, the traceback is attached to the exception instance
 
1782
+   through the ``__traceback__`` attribute. If the instance is saved in
 
1783
+   a local variable that persists outside of the ``except`` block, the
 
1784
+   traceback will create a reference cycle with the current frame and its
 
1785
+   dictionary of local variables.  This will delay reclaiming dead
 
1786
+   resources until the next cyclic :term:`garbage collection` pass.
 
1787
+
 
1788
+   In Python 2, this problem only occurs if you save the traceback itself
 
1789
+   (e.g. the third element of the tuple returned by :func:`sys.exc_info`)
 
1790
+   in a variable.
 
1791
+
 
1792
+
 
1793
+Other Resources
 
1794
+===============
 
1795
+
 
1796
+The authors of the following blog posts, wiki pages, and books deserve special
 
1797
+thanks for making public their tips for porting Python 2 code to Python 3 (and
 
1798
+thus helping provide information for this document):
 
1799
+
 
1800
+* http://python3porting.com/
 
1801
+* http://docs.pythonsprints.com/python3_porting/py-porting.html
 
1802
+* http://techspot.zzzeek.org/2011/01/24/zzzeek-s-guide-to-python-3-porting/
 
1803
+* http://dabeaz.blogspot.com/2011/01/porting-py65-and-my-superboard-to.html
 
1804
+* http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
 
1805
+* http://lucumr.pocoo.org/2010/2/11/porting-to-python-3-a-guide/
 
1806
+* http://wiki.python.org/moin/PortingPythonToPy3k
 
1807
+
 
1808
+If you feel there is something missing from this document that should be added,
 
1809
+please email the python-porting_ mailing list.
 
1810
+
 
1811
+.. _python-porting: http://mail.python.org/mailman/listinfo/python-porting
337
1812
diff -r 8527427914a2 Doc/howto/sorting.rst
338
1813
--- a/Doc/howto/sorting.rst
339
1814
+++ b/Doc/howto/sorting.rst
395
1870
 
396
1871
 Notice that the full URL is created by adding a ``?`` to the URL, followed by
397
1872
 the encoded values.
 
1873
diff -r 8527427914a2 Doc/howto/webservers.rst
 
1874
--- a/Doc/howto/webservers.rst
 
1875
+++ b/Doc/howto/webservers.rst
 
1876
@@ -264,7 +264,7 @@
 
1877
 
 
1878
    * `FastCGI, SCGI, and Apache: Background and Future
 
1879
      <http://www.vmunix.com/mark/blog/archives/2006/01/02/fastcgi-scgi-and-apache-background-and-future/>`_
 
1880
-     is a discussion on why the concept of FastCGI and SCGI is better that that
 
1881
+     is a discussion on why the concept of FastCGI and SCGI is better than that
 
1882
      of mod_python.
 
1883
 
 
1884
 
 
1885
diff -r 8527427914a2 Doc/includes/capsulethunk.h
 
1886
--- /dev/null
 
1887
+++ b/Doc/includes/capsulethunk.h
 
1888
@@ -0,0 +1,134 @@
 
1889
+#ifndef __CAPSULETHUNK_H
 
1890
+#define __CAPSULETHUNK_H
 
1891
+
 
1892
+#if (    (PY_VERSION_HEX <  0x02070000) \
 
1893
+     || ((PY_VERSION_HEX >= 0x03000000) \
 
1894
+      && (PY_VERSION_HEX <  0x03010000)) )
 
1895
+
 
1896
+#define __PyCapsule_GetField(capsule, field, default_value) \
 
1897
+    ( PyCapsule_CheckExact(capsule) \
 
1898
+        ? (((PyCObject *)capsule)->field) \
 
1899
+        : (default_value) \
 
1900
+    ) \
 
1901
+
 
1902
+#define __PyCapsule_SetField(capsule, field, value) \
 
1903
+    ( PyCapsule_CheckExact(capsule) \
 
1904
+        ? (((PyCObject *)capsule)->field = value), 1 \
 
1905
+        : 0 \
 
1906
+    ) \
 
1907
+
 
1908
+
 
1909
+#define PyCapsule_Type PyCObject_Type
 
1910
+
 
1911
+#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
 
1912
+#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
 
1913
+
 
1914
+
 
1915
+#define PyCapsule_New(pointer, name, destructor) \
 
1916
+    (PyCObject_FromVoidPtr(pointer, destructor))
 
1917
+
 
1918
+
 
1919
+#define PyCapsule_GetPointer(capsule, name) \
 
1920
+    (PyCObject_AsVoidPtr(capsule))
 
1921
+
 
1922
+/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
 
1923
+#define PyCapsule_SetPointer(capsule, pointer) \
 
1924
+    __PyCapsule_SetField(capsule, cobject, pointer)
 
1925
+
 
1926
+
 
1927
+#define PyCapsule_GetDestructor(capsule) \
 
1928
+    __PyCapsule_GetField(capsule, destructor)
 
1929
+
 
1930
+#define PyCapsule_SetDestructor(capsule, dtor) \
 
1931
+    __PyCapsule_SetField(capsule, destructor, dtor)
 
1932
+
 
1933
+
 
1934
+/*
 
1935
+ * Sorry, there's simply no place
 
1936
+ * to store a Capsule "name" in a CObject.
 
1937
+ */
 
1938
+#define PyCapsule_GetName(capsule) NULL
 
1939
+
 
1940
+static int
 
1941
+PyCapsule_SetName(PyObject *capsule, const char *unused)
 
1942
+{
 
1943
+    unused = unused;
 
1944
+    PyErr_SetString(PyExc_NotImplementedError,
 
1945
+        "can't use PyCapsule_SetName with CObjects");
 
1946
+    return 1;
 
1947
+}
 
1948
+
 
1949
+
 
1950
+
 
1951
+#define PyCapsule_GetContext(capsule) \
 
1952
+    __PyCapsule_GetField(capsule, descr)
 
1953
+
 
1954
+#define PyCapsule_SetContext(capsule, context) \
 
1955
+    __PyCapsule_SetField(capsule, descr, context)
 
1956
+
 
1957
+
 
1958
+static void *
 
1959
+PyCapsule_Import(const char *name, int no_block)
 
1960
+{
 
1961
+    PyObject *object = NULL;
 
1962
+    void *return_value = NULL;
 
1963
+    char *trace;
 
1964
+    size_t name_length = (strlen(name) + 1) * sizeof(char);
 
1965
+    char *name_dup = (char *)PyMem_MALLOC(name_length);
 
1966
+
 
1967
+    if (!name_dup) {
 
1968
+        return NULL;
 
1969
+    }
 
1970
+
 
1971
+    memcpy(name_dup, name, name_length);
 
1972
+
 
1973
+    trace = name_dup;
 
1974
+    while (trace) {
 
1975
+        char *dot = strchr(trace, '.');
 
1976
+        if (dot) {
 
1977
+            *dot++ = '\0';
 
1978
+        }
 
1979
+
 
1980
+        if (object == NULL) {
 
1981
+            if (no_block) {
 
1982
+                object = PyImport_ImportModuleNoBlock(trace);
 
1983
+            } else {
 
1984
+                object = PyImport_ImportModule(trace);
 
1985
+                if (!object) {
 
1986
+                    PyErr_Format(PyExc_ImportError,
 
1987
+                        "PyCapsule_Import could not "
 
1988
+                        "import module \"%s\"", trace);
 
1989
+                }
 
1990
+            }
 
1991
+        } else {
 
1992
+            PyObject *object2 = PyObject_GetAttrString(object, trace);
 
1993
+            Py_DECREF(object);
 
1994
+            object = object2;
 
1995
+        }
 
1996
+        if (!object) {
 
1997
+            goto EXIT;
 
1998
+        }
 
1999
+
 
2000
+        trace = dot;
 
2001
+    }
 
2002
+
 
2003
+    if (PyCObject_Check(object)) {
 
2004
+        PyCObject *cobject = (PyCObject *)object;
 
2005
+        return_value = cobject->cobject;
 
2006
+    } else {
 
2007
+        PyErr_Format(PyExc_AttributeError,
 
2008
+            "PyCapsule_Import \"%s\" is not valid",
 
2009
+            name);
 
2010
+    }
 
2011
+
 
2012
+EXIT:
 
2013
+    Py_XDECREF(object);
 
2014
+    if (name_dup) {
 
2015
+        PyMem_FREE(name_dup);
 
2016
+    }
 
2017
+    return return_value;
 
2018
+}
 
2019
+
 
2020
+#endif /* #if PY_VERSION_HEX < 0x02070000 */
 
2021
+
 
2022
+#endif /* __CAPSULETHUNK_H */
 
2023
diff -r 8527427914a2 Doc/includes/sqlite3/ctx_manager.py
 
2024
--- a/Doc/includes/sqlite3/ctx_manager.py
 
2025
+++ b/Doc/includes/sqlite3/ctx_manager.py
 
2026
@@ -8,7 +8,7 @@
 
2027
     con.execute("insert into person(firstname) values (?)", ("Joe",))
 
2028
 
 
2029
 # con.rollback() is called after the with block finishes with an exception, the
 
2030
-# exception is still raised and must be catched
 
2031
+# exception is still raised and must be caught
 
2032
 try:
 
2033
     with con:
 
2034
         con.execute("insert into person(firstname) values (?)", ("Joe",))
398
2035
diff -r 8527427914a2 Doc/install/index.rst
399
2036
--- a/Doc/install/index.rst
400
2037
+++ b/Doc/install/index.rst
417
2054
 
418
2055
    python setup.py install
419
2056
 
420
 
+For Windows, this command should be run from a command prompt windows ("DOS
421
 
+box")::
 
2057
+For Windows, this command should be run from a command prompt window
 
2058
+(:menuselection:`Start --> Accessories`)::
422
2059
+
423
2060
+   setup.py install
424
2061
+
442
2079
 
443
2080
 .. _inst-platform-variations:
444
2081
 
 
2082
@@ -141,7 +144,7 @@
 
2083
 :file:`C:\\Temp\\foo-1.0`; you can use either a archive manipulator with a
 
2084
 graphical user interface (such as WinZip) or a command-line tool (such as
 
2085
 :program:`unzip` or :program:`pkunzip`) to unpack the archive.  Then, open a
 
2086
-command prompt window ("DOS box"), and run::
 
2087
+command prompt window and run::
 
2088
 
 
2089
    cd c:\Temp\foo-1.0
 
2090
    python setup.py install
 
2091
@@ -276,6 +279,12 @@
 
2092
    >>> sys.exec_prefix
 
2093
    '/usr'
 
2094
 
 
2095
+A few other placeholders are used in this document: :file:`{X.Y}` stands for the
 
2096
+version of Python, for example ``2.7``; :file:`{distname}` will be replaced by
 
2097
+the name of the module distribution being installed.  Dots and capitalization
 
2098
+are important in the paths; for example, a value that uses ``python2.7`` on UNIX
 
2099
+will typically use ``Python27`` on Windows.
 
2100
+
 
2101
 If you don't want to install modules to the standard location, or if you don't
 
2102
 have permission to write there, then you need to read about alternate
 
2103
 installations in section :ref:`inst-alt-install`.  If you want to customize your
 
2104
@@ -304,8 +313,61 @@
 
2105
 differ across platforms, so read whichever of the following sections applies to
 
2106
 you.
 
2107
 
 
2108
+Note that the various alternate installation schemes are mutually exclusive: you
 
2109
+can pass ``--user``, or ``--home``, or ``--prefix`` and ``--exec-prefix``, or
 
2110
+``--install-base`` and ``--install-platbase``, but you can't mix from these
 
2111
+groups.
 
2112
 
 
2113
-.. _inst-alt-install-prefix:
 
2114
+
 
2115
+.. _inst-alt-install-user:
 
2116
+
 
2117
+Alternate installation: the user scheme
 
2118
+---------------------------------------
 
2119
+
 
2120
+This scheme is designed to be the most convenient solution for users that don't
 
2121
+have write permission to the global site-packages directory or don't want to
 
2122
+install into it.  It is enabled with a simple option::
 
2123
+
 
2124
+   python setup.py install --user
 
2125
+
 
2126
+Files will be installed into subdirectories of :data:`site.USER_BASE` (written
 
2127
+as :file:`{userbase}` hereafter).  This scheme installs pure Python modules and
 
2128
+extension modules in the same location (also known as :data:`site.USER_SITE`).
 
2129
+Here are the values for UNIX, including Mac OS X:
 
2130
+
 
2131
+=============== ===========================================================
 
2132
+Type of file    Installation directory
 
2133
+=============== ===========================================================
 
2134
+modules         :file:`{userbase}/lib/python{X.Y}/site-packages`
 
2135
+scripts         :file:`{userbase}/bin`
 
2136
+data            :file:`{userbase}`
 
2137
+C headers       :file:`{userbase}/include/python{X.Y}/{distname}`
 
2138
+=============== ===========================================================
 
2139
+
 
2140
+And here are the values used on Windows:
 
2141
+
 
2142
+=============== ===========================================================
 
2143
+Type of file    Installation directory
 
2144
+=============== ===========================================================
 
2145
+modules         :file:`{userbase}\\Python{XY}\\site-packages`
 
2146
+scripts         :file:`{userbase}\\Scripts`
 
2147
+data            :file:`{userbase}`
 
2148
+C headers       :file:`{userbase}\\Python{XY}\\Include\\{distname}`
 
2149
+=============== ===========================================================
 
2150
+
 
2151
+The advantage of using this scheme compared to the other ones described below is
 
2152
+that the user site-packages directory is under normal conditions always included
 
2153
+in :data:`sys.path` (see :mod:`site` for more information), which means that
 
2154
+there is no additional step to perform after running the :file:`setup.py` script
 
2155
+to finalize the installation.
 
2156
+
 
2157
+The :command:`build_ext` command also has a ``--user`` option to add
 
2158
+:file:`{userbase}/include` to the compiler search path for header files and
 
2159
+:file:`{userbase}/lib` to the compiler search path for libraries as well as to
 
2160
+the runtime search path for shared C libraries (rpath).
 
2161
+
 
2162
+
 
2163
+.. _inst-alt-install-home:
 
2164
 
 
2165
 Alternate installation: the home scheme
 
2166
 ---------------------------------------
 
2167
@@ -327,26 +389,30 @@
 
2168
 
 
2169
    python setup.py install --home=~
 
2170
 
 
2171
+To make Python find the distributions installed with this scheme, you may have
 
2172
+to :ref:`modify Python's search path <inst-search-path>` or edit
 
2173
+:mod:`sitecustomize` (see :mod:`site`) to call :func:`site.addsitedir` or edit
 
2174
+:data:`sys.path`.
 
2175
+
 
2176
 The :option:`--home` option defines the installation base directory.  Files are
 
2177
 installed to the following directories under the installation base as follows:
 
2178
 
 
2179
-+------------------------------+---------------------------+-----------------------------+
 
2180
-| Type of file                 | Installation Directory    | Override option             |
 
2181
-+==============================+===========================+=============================+
 
2182
-| pure module distribution     | :file:`{home}/lib/python` | :option:`--install-purelib` |
 
2183
-+------------------------------+---------------------------+-----------------------------+
 
2184
-| non-pure module distribution | :file:`{home}/lib/python` | :option:`--install-platlib` |
 
2185
-+------------------------------+---------------------------+-----------------------------+
 
2186
-| scripts                      | :file:`{home}/bin`        | :option:`--install-scripts` |
 
2187
-+------------------------------+---------------------------+-----------------------------+
 
2188
-| data                         | :file:`{home}/share`      | :option:`--install-data`    |
 
2189
-+------------------------------+---------------------------+-----------------------------+
 
2190
+=============== ===========================================================
 
2191
+Type of file    Installation directory
 
2192
+=============== ===========================================================
 
2193
+modules         :file:`{home}/lib/python`
 
2194
+scripts         :file:`{home}/bin`
 
2195
+data            :file:`{home}`
 
2196
+C headers       :file:`{home}/include/python/{distname}`
 
2197
+=============== ===========================================================
 
2198
+
 
2199
+(Mentally replace slashes with backslashes if you're on Windows.)
 
2200
 
 
2201
 .. versionchanged:: 2.4
 
2202
    The :option:`--home` option used to be supported only on Unix.
 
2203
 
 
2204
 
 
2205
-.. _inst-alt-install-home:
 
2206
+.. _inst-alt-install-prefix-unix:
 
2207
 
 
2208
 Alternate installation: Unix (the prefix scheme)
 
2209
 ------------------------------------------------
 
2210
@@ -355,7 +421,7 @@
 
2211
 perform the build/install (i.e., to run the setup script), but install modules
 
2212
 into the third-party module directory of a different Python installation (or
 
2213
 something that looks like a different Python installation).  If this sounds a
 
2214
-trifle unusual, it is---that's why the "home scheme" comes first.  However,
 
2215
+trifle unusual, it is---that's why the user and home schemes come before.  However,
 
2216
 there are at least two known cases where the prefix scheme will be useful.
 
2217
 
 
2218
 First, consider that many Linux distributions put Python in :file:`/usr`, rather
 
2219
@@ -383,17 +449,15 @@
 
2220
 executables, etc.)  If :option:`--exec-prefix` is not supplied, it defaults to
 
2221
 :option:`--prefix`.  Files are installed as follows:
 
2222
 
 
2223
-+------------------------------+-----------------------------------------------------+-----------------------------+
 
2224
-| Type of file                 | Installation Directory                              | Override option             |
 
2225
-+==============================+=====================================================+=============================+
 
2226
-| pure module distribution     | :file:`{prefix}/lib/python{X.Y}/site-packages`      | :option:`--install-purelib` |
 
2227
-+------------------------------+-----------------------------------------------------+-----------------------------+
 
2228
-| non-pure module distribution | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :option:`--install-platlib` |
 
2229
-+------------------------------+-----------------------------------------------------+-----------------------------+
 
2230
-| scripts                      | :file:`{prefix}/bin`                                | :option:`--install-scripts` |
 
2231
-+------------------------------+-----------------------------------------------------+-----------------------------+
 
2232
-| data                         | :file:`{prefix}/share`                              | :option:`--install-data`    |
 
2233
-+------------------------------+-----------------------------------------------------+-----------------------------+
 
2234
+================= ==========================================================
 
2235
+Type of file      Installation directory
 
2236
+================= ==========================================================
 
2237
+Python modules    :file:`{prefix}/lib/python{X.Y}/site-packages`
 
2238
+extension modules :file:`{exec-prefix}/lib/python{X.Y}/site-packages`
 
2239
+scripts           :file:`{prefix}/bin`
 
2240
+data              :file:`{prefix}`
 
2241
+C headers         :file:`{prefix}/include/python{X.Y}/{distname}`
 
2242
+================= ==========================================================
 
2243
 
 
2244
 There is no requirement that :option:`--prefix` or :option:`--exec-prefix`
 
2245
 actually point to an alternate Python installation; if the directories listed
 
2246
@@ -418,7 +482,7 @@
 
2247
 alternate Python installation, this is immaterial.)
 
2248
 
 
2249
 
 
2250
-.. _inst-alt-install-windows:
 
2251
+.. _inst-alt-install-prefix-windows:
 
2252
 
 
2253
 Alternate installation: Windows (the prefix scheme)
 
2254
 ---------------------------------------------------
 
2255
@@ -433,20 +497,18 @@
 
2256
 to install modules to the :file:`\\Temp\\Python` directory on the current drive.
 
2257
 
 
2258
 The installation base is defined by the :option:`--prefix` option; the
 
2259
-:option:`--exec-prefix` option is not supported under Windows. Files are
 
2260
-installed as follows:
 
2261
+:option:`--exec-prefix` option is not supported under Windows, which means that
 
2262
+pure Python modules and extension modules are installed into the same location.
 
2263
+Files are installed as follows:
 
2264
 
 
2265
-+------------------------------+---------------------------+-----------------------------+
 
2266
-| Type of file                 | Installation Directory    | Override option             |
 
2267
-+==============================+===========================+=============================+
 
2268
-| pure module distribution     | :file:`{prefix}`          | :option:`--install-purelib` |
 
2269
-+------------------------------+---------------------------+-----------------------------+
 
2270
-| non-pure module distribution | :file:`{prefix}`          | :option:`--install-platlib` |
 
2271
-+------------------------------+---------------------------+-----------------------------+
 
2272
-| scripts                      | :file:`{prefix}\\Scripts` | :option:`--install-scripts` |
 
2273
-+------------------------------+---------------------------+-----------------------------+
 
2274
-| data                         | :file:`{prefix}\\Data`    | :option:`--install-data`    |
 
2275
-+------------------------------+---------------------------+-----------------------------+
 
2276
+=============== ==========================================================
 
2277
+Type of file    Installation directory
 
2278
+=============== ==========================================================
 
2279
+modules         :file:`{prefix}\\Lib\\site-packages`
 
2280
+scripts         :file:`{prefix}\\Scripts`
 
2281
+data            :file:`{prefix}`
 
2282
+C headers       :file:`{prefix}\\Include\\{distname}`
 
2283
+=============== ==========================================================
 
2284
 
 
2285
 
 
2286
 .. _inst-custom-install:
 
2287
@@ -460,13 +522,29 @@
 
2288
 or you might want to completely redefine the installation scheme.  In either
 
2289
 case, you're creating a *custom installation scheme*.
 
2290
 
 
2291
-You probably noticed the column of "override options" in the tables describing
 
2292
-the alternate installation schemes above.  Those options are how you define a
 
2293
-custom installation scheme.  These override options can be relative, absolute,
 
2294
+To create a custom installation scheme, you start with one of the alternate
 
2295
+schemes and override some of the installation directories used for the various
 
2296
+types of files, using these options:
 
2297
+
 
2298
+====================== =======================
 
2299
+Type of file           Override option
 
2300
+====================== =======================
 
2301
+Python modules         ``--install-purelib``
 
2302
+extension modules      ``--install-platlib``
 
2303
+all modules            ``--install-lib``
 
2304
+scripts                ``--install-scripts``
 
2305
+data                   ``--install-data``
 
2306
+C headers              ``--install-headers``
 
2307
+====================== =======================
 
2308
+
 
2309
+These override options can be relative, absolute,
 
2310
 or explicitly defined in terms of one of the installation base directories.
 
2311
 (There are two installation base directories, and they are normally the same---
 
2312
 they only differ when you use the Unix "prefix scheme" and supply different
 
2313
-:option:`--prefix` and :option:`--exec-prefix` options.)
 
2314
+``--prefix`` and ``--exec-prefix`` options; using ``--install-lib`` will
 
2315
+override values computed or given for ``--install-purelib`` and
 
2316
+``--install-platlib``, and is recommended for schemes that don't make a
 
2317
+difference between Python and extension modules.)
 
2318
 
 
2319
 For example, say you're installing a module distribution to your home directory
 
2320
 under Unix---but you want scripts to go in :file:`~/scripts` rather than
 
2321
@@ -493,15 +571,16 @@
 
2322
 a subdirectory of :file:`{prefix}`, rather than right in :file:`{prefix}`
 
2323
 itself.  This is almost as easy as customizing the script installation directory
 
2324
 ---you just have to remember that there are two types of modules to worry about,
 
2325
-pure modules and non-pure modules (i.e., modules from a non-pure distribution).
 
2326
-For example::
 
2327
+Python and extension modules, which can conveniently be both controlled by one
 
2328
+option::
 
2329
 
 
2330
-   python setup.py install --install-purelib=Site --install-platlib=Site
 
2331
+   python setup.py install --install-lib=Site
 
2332
 
 
2333
-The specified installation directories are relative to :file:`{prefix}`.  Of
 
2334
-course, you also have to ensure that these directories are in Python's module
 
2335
-search path, such as by putting a :file:`.pth` file in :file:`{prefix}`.  See
 
2336
-section :ref:`inst-search-path` to find out how to modify Python's search path.
 
2337
+The specified installation directory is relative to :file:`{prefix}`.  Of
 
2338
+course, you also have to ensure that this directory is in Python's module
 
2339
+search path, such as by putting a :file:`.pth` file in a site directory (see
 
2340
+:mod:`site`).  See section :ref:`inst-search-path` to find out how to modify
 
2341
+Python's search path.
 
2342
 
 
2343
 If you want to define an entire installation scheme, you just have to supply all
 
2344
 of the installation directory options.  The recommended way to do this is to
 
2345
@@ -553,8 +632,8 @@
 
2346
 
 
2347
    python setup.py install --install-base=/tmp
 
2348
 
 
2349
-would install pure modules to :file:`{/tmp/python/lib}` in the first case, and
 
2350
-to :file:`{/tmp/lib}` in the second case.  (For the second case, you probably
 
2351
+would install pure modules to :file:`/tmp/python/lib` in the first case, and
 
2352
+to :file:`/tmp/lib` in the second case.  (For the second case, you probably
 
2353
 want to supply an installation base of :file:`/tmp/python`.)
 
2354
 
 
2355
 You probably noticed the use of ``$HOME`` and ``$PLAT`` in the sample
 
2356
@@ -571,7 +650,7 @@
 
2357
    needed on those platforms?
 
2358
 
 
2359
 
 
2360
-.. XXX I'm not sure where this section should go.
 
2361
+.. XXX Move this to Doc/using
 
2362
 
 
2363
 .. _inst-search-path:
 
2364
 
445
2365
diff -r 8527427914a2 Doc/library/2to3.rst
446
2366
--- a/Doc/library/2to3.rst
447
2367
+++ b/Doc/library/2to3.rst
448
 
@@ -230,7 +230,7 @@
 
2368
@@ -123,7 +123,9 @@
 
2369
 .. 2to3fixer:: callable
 
2370
 
 
2371
    Converts ``callable(x)`` to ``isinstance(x, collections.Callable)``, adding
 
2372
-   an import to :mod:`collections` if needed.
 
2373
+   an import to :mod:`collections` if needed. Note ``callable(x)`` has returned
 
2374
+   in Python 3.2, so if you do not intend to support Python 3.1, you can disable
 
2375
+   this fixer.
 
2376
 
 
2377
 .. 2to3fixer:: dict
 
2378
 
 
2379
@@ -230,7 +232,7 @@
449
2380
 
450
2381
 .. 2to3fixer:: long
451
2382
 
468
2399
 
469
2400
 This module is not normally accessed explicitly by most applications, but can be
470
2401
 useful in modules that provide objects with the same name as a built-in value,
 
2402
diff -r 8527427914a2 Doc/library/__future__.rst
 
2403
--- a/Doc/library/__future__.rst
 
2404
+++ b/Doc/library/__future__.rst
 
2405
@@ -4,6 +4,9 @@
 
2406
 .. module:: __future__
 
2407
    :synopsis: Future statement definitions
 
2408
 
 
2409
+**Source code:** :source:`Lib/__future__.py`
 
2410
+
 
2411
+--------------
 
2412
 
 
2413
 :mod:`__future__` is a real module, and serves three purposes:
 
2414
 
471
2415
diff -r 8527427914a2 Doc/library/abc.rst
472
2416
--- a/Doc/library/abc.rst
473
2417
+++ b/Doc/library/abc.rst
474
 
@@ -9,8 +9,8 @@
 
2418
@@ -9,8 +9,12 @@
475
2419
 
476
2420
 .. versionadded:: 2.6
477
2421
 
478
2422
-This module provides the infrastructure for defining an :term:`abstract base
479
2423
-class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
 
2424
+**Source code:** :source:`Lib/abc.py`
 
2425
+
 
2426
+--------------
 
2427
+
480
2428
+This module provides the infrastructure for defining :term:`abstract base
481
2429
+classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
482
2430
 was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
483
2431
 regarding a type hierarchy for numbers based on ABCs.)
484
2432
 
 
2433
diff -r 8527427914a2 Doc/library/aifc.rst
 
2434
--- a/Doc/library/aifc.rst
 
2435
+++ b/Doc/library/aifc.rst
 
2436
@@ -10,6 +10,10 @@
 
2437
    single: AIFF
 
2438
    single: AIFF-C
 
2439
 
 
2440
+**Source code:** :source:`Lib/aifc.py`
 
2441
+
 
2442
+--------------
 
2443
+
 
2444
 This module provides support for reading and writing AIFF and AIFF-C files.
 
2445
 AIFF is Audio Interchange File Format, a format for storing digital audio
 
2446
 samples in a file.  AIFF-C is a newer version of the format that includes the
485
2447
diff -r 8527427914a2 Doc/library/argparse.rst
486
2448
--- a/Doc/library/argparse.rst
487
2449
+++ b/Doc/library/argparse.rst
488
 
@@ -106,7 +106,7 @@
489
 
 :class:`ArgumentParser` parses args through the
 
2450
@@ -2,11 +2,15 @@
 
2451
 ===============================================================================
 
2452
 
 
2453
 .. module:: argparse
 
2454
-   :synopsis: Command-line option and argument-parsing library.
 
2455
+   :synopsis: Command-line option and argument parsing library.
 
2456
 .. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
 
2457
-.. versionadded:: 2.7
 
2458
 .. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
 
2459
 
 
2460
+.. versionadded:: 2.7
 
2461
+
 
2462
+**Source code:** :source:`Lib/argparse.py`
 
2463
+
 
2464
+--------------
 
2465
 
 
2466
 The :mod:`argparse` module makes it easy to write user-friendly command-line
 
2467
 interfaces. The program defines what arguments it requires, and :mod:`argparse`
 
2468
@@ -103,10 +107,10 @@
 
2469
 Parsing arguments
 
2470
 ^^^^^^^^^^^^^^^^^
 
2471
 
 
2472
-:class:`ArgumentParser` parses args through the
 
2473
+:class:`ArgumentParser` parses arguments through the
490
2474
 :meth:`~ArgumentParser.parse_args` method.  This will inspect the command line,
491
 
 convert each arg to the appropriate type and then invoke the appropriate action.
 
2475
-convert each arg to the appropriate type and then invoke the appropriate action.
492
2476
-In most cases, this means a simple namespace object will be built up from
 
2477
+convert each argument to the appropriate type and then invoke the appropriate action.
493
2478
+In most cases, this means a simple :class:`Namespace` object will be built up from
494
2479
 attributes parsed out of the command line::
495
2480
 
496
2481
    >>> parser.parse_args(['--sum', '7', '-1', '42'])
497
 
@@ -714,7 +714,7 @@
 
2482
@@ -114,7 +118,7 @@
 
2483
 
 
2484
 In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
 
2485
 arguments, and the :class:`ArgumentParser` will automatically determine the
 
2486
-command-line args from :data:`sys.argv`.
 
2487
+command-line arguments from :data:`sys.argv`.
 
2488
 
 
2489
 
 
2490
 ArgumentParser objects
 
2491
@@ -149,7 +153,7 @@
 
2492
      conflicting optionals.
 
2493
 
 
2494
    * prog_ - The name of the program (default:
 
2495
-     :data:`sys.argv[0]`)
 
2496
+     ``sys.argv[0]``)
 
2497
 
 
2498
    * usage_ - The string describing the program usage (default: generated)
 
2499
 
 
2500
@@ -238,7 +242,7 @@
 
2501
     --foo FOO  foo help
 
2502
 
 
2503
 The help option is typically ``-h/--help``. The exception to this is
 
2504
-if the ``prefix_chars=`` is specified and does not include ``'-'``, in
 
2505
+if the ``prefix_chars=`` is specified and does not include ``-``, in
 
2506
 which case ``-h`` and ``--help`` are not valid options.  In
 
2507
 this case, the first character in ``prefix_chars`` is used to prefix
 
2508
 the help options::
 
2509
@@ -254,7 +258,7 @@
 
2510
 prefix_chars
 
2511
 ^^^^^^^^^^^^
 
2512
 
 
2513
-Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
 
2514
+Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
 
2515
 Parsers that need to support different or additional prefix
 
2516
 characters, e.g. for options
 
2517
 like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
 
2518
@@ -267,7 +271,7 @@
 
2519
    Namespace(bar='Y', f='X')
 
2520
 
 
2521
 The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
 
2522
-characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
 
2523
+characters that does not include ``-`` will cause ``-f/--foo`` options to be
 
2524
 disallowed.
 
2525
 
 
2526
 
 
2527
@@ -389,7 +393,7 @@
 
2528
    likewise for this epilog whose whitespace will be cleaned up and whose words
 
2529
    will be wrapped across a couple lines
 
2530
 
 
2531
-Passing :class:`~argparse.RawDescriptionHelpFormatter` as ``formatter_class=``
 
2532
+Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
 
2533
 indicates that description_ and epilog_ are already correctly formatted and
 
2534
 should not be line-wrapped::
 
2535
 
 
2536
@@ -415,7 +419,7 @@
 
2537
    optional arguments:
 
2538
     -h, --help  show this help message and exit
 
2539
 
 
2540
-:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text
 
2541
+:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
 
2542
 including argument descriptions.
 
2543
 
 
2544
 The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
 
2545
@@ -642,11 +646,11 @@
 
2546
 action
 
2547
 ^^^^^^
 
2548
 
 
2549
-:class:`ArgumentParser` objects associate command-line args with actions.  These
 
2550
-actions can do just about anything with the command-line args associated with
 
2551
+:class:`ArgumentParser` objects associate command-line arguments with actions.  These
 
2552
+actions can do just about anything with the command-line arguments associated with
 
2553
 them, though most actions simply add an attribute to the object returned by
 
2554
 :meth:`~ArgumentParser.parse_args`.  The ``action`` keyword argument specifies
 
2555
-how the command-line args should be handled. The supported actions are:
 
2556
+how the command-line arguments should be handled. The supported actions are:
 
2557
 
 
2558
 * ``'store'`` - This just stores the argument's value.  This is the default
 
2559
   action. For example::
 
2560
@@ -666,15 +670,17 @@
 
2561
     >>> parser.parse_args('--foo'.split())
 
2562
     Namespace(foo=42)
 
2563
 
 
2564
-* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
 
2565
-  ``False`` respectively.  These are special cases of ``'store_const'``.  For
 
2566
-  example::
 
2567
+* ``'store_true'`` and ``'store_false'`` - These are special cases of
 
2568
+  ``'store_const'`` using for storing the values ``True`` and ``False``
 
2569
+  respectively.  In addition, they create default values of *False* and *True*
 
2570
+  respectively.  For example::
 
2571
 
 
2572
     >>> parser = argparse.ArgumentParser()
 
2573
     >>> parser.add_argument('--foo', action='store_true')
 
2574
     >>> parser.add_argument('--bar', action='store_false')
 
2575
+    >>> parser.add_argument('--baz', action='store_false')
 
2576
     >>> parser.parse_args('--foo --bar'.split())
 
2577
-    Namespace(bar=False, foo=True)
 
2578
+    Namespace(bar=False, baz=True, foo=True)
 
2579
 
 
2580
 * ``'append'`` - This stores a list, and appends each argument value to the
 
2581
   list.  This is useful to allow an option to be specified multiple times.
 
2582
@@ -714,12 +720,12 @@
498
2583
 
499
2584
 * ``parser`` - The ArgumentParser object which contains this action.
500
2585
 
503
2588
   :meth:`~ArgumentParser.parse_args`.  Most actions add an attribute to this
504
2589
   object.
505
2590
 
506
 
@@ -1325,11 +1325,14 @@
 
2591
-* ``values`` - The associated command-line args, with any type-conversions
 
2592
-  applied.  (Type-conversions are specified with the type_ keyword argument to
 
2593
+* ``values`` - The associated command-line arguments, with any type conversions
 
2594
+  applied.  (Type conversions are specified with the type_ keyword argument to
 
2595
   :meth:`~ArgumentParser.add_argument`.
 
2596
 
 
2597
 * ``option_string`` - The option string that was used to invoke this action.
 
2598
@@ -751,7 +757,7 @@
 
2599
 different number of command-line arguments with a single action.  The supported
 
2600
 values are:
 
2601
 
 
2602
-* N (an integer).  N args from the command line will be gathered together into a
 
2603
+* ``N`` (an integer).  ``N`` arguments from the command line will be gathered together into a
 
2604
   list.  For example::
 
2605
 
 
2606
      >>> parser = argparse.ArgumentParser()
 
2607
@@ -763,11 +769,11 @@
 
2608
   Note that ``nargs=1`` produces a list of one item.  This is different from
 
2609
   the default, in which the item is produced by itself.
 
2610
 
 
2611
-* ``'?'``. One arg will be consumed from the command line if possible, and
 
2612
-  produced as a single item.  If no command-line arg is present, the value from
 
2613
+* ``'?'``. One argument will be consumed from the command line if possible, and
 
2614
+  produced as a single item.  If no command-line argument is present, the value from
 
2615
   default_ will be produced.  Note that for optional arguments, there is an
 
2616
   additional case - the option string is present but not followed by a
 
2617
-  command-line arg.  In this case the value from const_ will be produced.  Some
 
2618
+  command-line argument.  In this case the value from const_ will be produced.  Some
 
2619
   examples to illustrate this::
 
2620
 
 
2621
      >>> parser = argparse.ArgumentParser()
 
2622
@@ -795,7 +801,7 @@
 
2623
      Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
 
2624
                outfile=<open file '<stdout>', mode 'w' at 0x...>)
 
2625
 
 
2626
-* ``'*'``.  All command-line args present are gathered into a list.  Note that
 
2627
+* ``'*'``.  All command-line arguments present are gathered into a list.  Note that
 
2628
   it generally doesn't make much sense to have more than one positional argument
 
2629
   with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
 
2630
   possible.  For example::
 
2631
@@ -809,7 +815,7 @@
 
2632
 
 
2633
 * ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
 
2634
   list.  Additionally, an error message will be generated if there wasn't at
 
2635
-  least one command-line arg present.  For example::
 
2636
+  least one command-line argument present.  For example::
 
2637
 
 
2638
      >>> parser = argparse.ArgumentParser(prog='PROG')
 
2639
      >>> parser.add_argument('foo', nargs='+')
 
2640
@@ -819,8 +825,8 @@
 
2641
      usage: PROG [-h] foo [foo ...]
 
2642
      PROG: error: too few arguments
 
2643
 
 
2644
-If the ``nargs`` keyword argument is not provided, the number of args consumed
 
2645
-is determined by the action_.  Generally this means a single command-line arg
 
2646
+If the ``nargs`` keyword argument is not provided, the number of arguments consumed
 
2647
+is determined by the action_.  Generally this means a single command-line argument
 
2648
 will be consumed and a single item (not a list) will be produced.
 
2649
 
 
2650
 
 
2651
@@ -837,9 +843,9 @@
 
2652
 
 
2653
 * When :meth:`~ArgumentParser.add_argument` is called with option strings
 
2654
   (like ``-f`` or ``--foo``) and ``nargs='?'``.  This creates an optional
 
2655
-  argument that can be followed by zero or one command-line args.
 
2656
+  argument that can be followed by zero or one command-line arguments.
 
2657
   When parsing the command line, if the option string is encountered with no
 
2658
-  command-line arg following it, the value of ``const`` will be assumed instead.
 
2659
+  command-line argument following it, the value of ``const`` will be assumed instead.
 
2660
   See the nargs_ description for examples.
 
2661
 
 
2662
 The ``const`` keyword argument defaults to ``None``.
 
2663
@@ -851,7 +857,7 @@
 
2664
 All optional arguments and some positional arguments may be omitted at the
 
2665
 command line.  The ``default`` keyword argument of
 
2666
 :meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
 
2667
-specifies what value should be used if the command-line arg is not present.
 
2668
+specifies what value should be used if the command-line argument is not present.
 
2669
 For optional arguments, the ``default`` value is used when the option string
 
2670
 was not present at the command line::
 
2671
 
 
2672
@@ -862,8 +868,8 @@
 
2673
    >>> parser.parse_args(''.split())
 
2674
    Namespace(foo=42)
 
2675
 
 
2676
-For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
 
2677
-is used when no command-line arg was present::
 
2678
+For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
 
2679
+is used when no command-line argument was present::
 
2680
 
 
2681
    >>> parser = argparse.ArgumentParser()
 
2682
    >>> parser.add_argument('foo', nargs='?', default=42)
 
2683
@@ -887,12 +893,12 @@
 
2684
 type
 
2685
 ^^^^
 
2686
 
 
2687
-By default, ArgumentParser objects read command-line args in as simple strings.
 
2688
-However, quite often the command-line string should instead be interpreted as
 
2689
-another type, like a :class:`float`, :class:`int` or :class:`file`.  The
 
2690
+By default, :class:`ArgumentParser` objects read command-line arguments in as simple
 
2691
+strings. However, quite often the command-line string should instead be
 
2692
+interpreted as another type, like a :class:`float` or :class:`int`.  The
 
2693
 ``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
 
2694
-necessary type-checking and type-conversions to be performed.  Many common
 
2695
-built-in types can be used directly as the value of the ``type`` argument::
 
2696
+necessary type-checking and type conversions to be performed.  Common built-in
 
2697
+types and functions can be used directly as the value of the ``type`` argument::
 
2698
 
 
2699
    >>> parser = argparse.ArgumentParser()
 
2700
    >>> parser.add_argument('foo', type=int)
 
2701
@@ -911,7 +917,7 @@
 
2702
    Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
 
2703
 
 
2704
 ``type=`` can take any callable that takes a single string argument and returns
 
2705
-the type-converted value::
 
2706
+the converted value::
 
2707
 
 
2708
    >>> def perfect_square(string):
 
2709
    ...     value = int(string)
 
2710
@@ -946,11 +952,11 @@
 
2711
 choices
 
2712
 ^^^^^^^
 
2713
 
 
2714
-Some command-line args should be selected from a restricted set of values.
 
2715
+Some command-line arguments should be selected from a restricted set of values.
 
2716
 These can be handled by passing a container object as the ``choices`` keyword
 
2717
 argument to :meth:`~ArgumentParser.add_argument`.  When the command line is
 
2718
-parsed, arg values will be checked, and an error message will be displayed if
 
2719
-the arg was not one of the acceptable values::
 
2720
+parsed, argument values will be checked, and an error message will be displayed if
 
2721
+the argument was not one of the acceptable values::
 
2722
 
 
2723
    >>> parser = argparse.ArgumentParser(prog='PROG')
 
2724
    >>> parser.add_argument('foo', choices='abc')
 
2725
@@ -1052,8 +1058,8 @@
 
2726
 value as the "name" of each object.  By default, for positional argument
 
2727
 actions, the dest_ value is used directly, and for optional argument actions,
 
2728
 the dest_ value is uppercased.  So, a single positional argument with
 
2729
-``dest='bar'`` will that argument will be referred to as ``bar``. A single
 
2730
-optional argument ``--foo`` that should be followed by a single command-line arg
 
2731
+``dest='bar'`` will be referred to as ``bar``. A single
 
2732
+optional argument ``--foo`` that should be followed by a single command-line argument
 
2733
 will be referred to as ``FOO``.  An example::
 
2734
 
 
2735
    >>> parser = argparse.ArgumentParser()
 
2736
@@ -1125,10 +1131,10 @@
 
2737
 
 
2738
 For optional argument actions, the value of ``dest`` is normally inferred from
 
2739
 the option strings.  :class:`ArgumentParser` generates the value of ``dest`` by
 
2740
-taking the first long option string and stripping away the initial ``'--'``
 
2741
+taking the first long option string and stripping away the initial ``--``
 
2742
 string.  If no long option strings were supplied, ``dest`` will be derived from
 
2743
-the first short option string by stripping the initial ``'-'`` character.  Any
 
2744
-internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
 
2745
+the first short option string by stripping the initial ``-`` character.  Any
 
2746
+internal ``-`` characters will be converted to ``_`` characters to make sure
 
2747
 the string is a valid attribute name.  The examples below illustrate this
 
2748
 behavior::
 
2749
 
 
2750
@@ -1160,7 +1166,7 @@
 
2751
    created and how they are assigned. See the documentation for
 
2752
    :meth:`add_argument` for details.
 
2753
 
 
2754
-   By default, the arg strings are taken from :data:`sys.argv`, and a new empty
 
2755
+   By default, the argument strings are taken from :data:`sys.argv`, and a new empty
 
2756
    :class:`Namespace` object is created for the attributes.
 
2757
 
 
2758
 
 
2759
@@ -1231,15 +1237,15 @@
 
2760
    PROG: error: extra arguments found: badger
 
2761
 
 
2762
 
 
2763
-Arguments containing ``"-"``
 
2764
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
2765
+Arguments containing ``-``
 
2766
+^^^^^^^^^^^^^^^^^^^^^^^^^^
 
2767
 
 
2768
 The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
 
2769
 the user has clearly made a mistake, but some situations are inherently
 
2770
-ambiguous.  For example, the command-line arg ``'-1'`` could either be an
 
2771
+ambiguous.  For example, the command-line argument ``-1`` could either be an
 
2772
 attempt to specify an option or an attempt to provide a positional argument.
 
2773
 The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
 
2774
-arguments may only begin with ``'-'`` if they look like negative numbers and
 
2775
+arguments may only begin with ``-`` if they look like negative numbers and
 
2776
 there are no options in the parser that look like negative numbers::
 
2777
 
 
2778
    >>> parser = argparse.ArgumentParser(prog='PROG')
 
2779
@@ -1272,7 +1278,7 @@
 
2780
    usage: PROG [-h] [-1 ONE] [foo]
 
2781
    PROG: error: argument -1: expected one argument
 
2782
 
 
2783
-If you have positional arguments that must begin with ``'-'`` and don't look
 
2784
+If you have positional arguments that must begin with ``-`` and don't look
 
2785
 like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
 
2786
 :meth:`~ArgumentParser.parse_args` that everything after that is a positional
 
2787
 argument::
 
2788
@@ -1304,7 +1310,7 @@
 
2789
 Beyond ``sys.argv``
 
2790
 ^^^^^^^^^^^^^^^^^^^
 
2791
 
 
2792
-Sometimes it may be useful to have an ArgumentParser parse args other than those
 
2793
+Sometimes it may be useful to have an ArgumentParser parse arguments other than those
 
2794
 of :data:`sys.argv`.  This can be accomplished by passing a list of strings to
 
2795
 :meth:`~ArgumentParser.parse_args`.  This is useful for testing at the
 
2796
 interactive prompt::
 
2797
@@ -1325,11 +1331,14 @@
507
2798
 The Namespace object
508
2799
 ^^^^^^^^^^^^^^^^^^^^
509
2800
 
523
2814
 
524
2815
    >>> parser = argparse.ArgumentParser()
525
2816
    >>> parser.add_argument('--foo')
526
 
@@ -1757,7 +1760,7 @@
 
2817
@@ -1387,7 +1396,7 @@
 
2818
      >>> parser_b = subparsers.add_parser('b', help='b help')
 
2819
      >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
 
2820
      >>>
 
2821
-     >>> # parse some arg lists
 
2822
+     >>> # parse some argument lists
 
2823
      >>> parser.parse_args(['a', '12'])
 
2824
      Namespace(bar=12, foo=False)
 
2825
      >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
 
2826
@@ -1396,8 +1405,8 @@
 
2827
    Note that the object returned by :meth:`parse_args` will only contain
 
2828
    attributes for the main parser and the subparser that was selected by the
 
2829
    command line (and not any other subparsers).  So in the example above, when
 
2830
-   the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
 
2831
-   present, and when the ``"b"`` command is specified, only the ``foo`` and
 
2832
+   the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
 
2833
+   present, and when the ``b`` command is specified, only the ``foo`` and
 
2834
    ``baz`` attributes are present.
 
2835
 
 
2836
    Similarly, when a help message is requested from a subparser, only the help
 
2837
@@ -1519,7 +1528,7 @@
 
2838
 
 
2839
    The :class:`FileType` factory creates objects that can be passed to the type
 
2840
    argument of :meth:`ArgumentParser.add_argument`.  Arguments that have
 
2841
-   :class:`FileType` objects as their type will open command-line args as files
 
2842
+   :class:`FileType` objects as their type will open command-line arguments as files
 
2843
    with the requested modes and buffer sizes:
 
2844
 
 
2845
    >>> parser = argparse.ArgumentParser()
 
2846
@@ -1633,7 +1642,7 @@
 
2847
 .. method:: ArgumentParser.set_defaults(**kwargs)
 
2848
 
 
2849
    Most of the time, the attributes of the object returned by :meth:`parse_args`
 
2850
-   will be fully determined by inspecting the command-line args and the argument
 
2851
+   will be fully determined by inspecting the command-line arguments and the argument
 
2852
    actions.  :meth:`set_defaults` allows some additional
 
2853
    attributes that are determined without any inspection of the command line to
 
2854
    be added::
 
2855
@@ -1757,7 +1766,7 @@
527
2856
 .. method:: ArgumentParser.error(message)
528
2857
 
529
2858
    This method prints a usage message including the *message* to the
532
2861
 
533
2862
 
534
2863
 .. _argparse-from-optparse:
 
2864
diff -r 8527427914a2 Doc/library/ast.rst
 
2865
--- a/Doc/library/ast.rst
 
2866
+++ b/Doc/library/ast.rst
 
2867
@@ -1,7 +1,5 @@
 
2868
-.. _ast:
 
2869
-
 
2870
-Abstract Syntax Trees
 
2871
-=====================
 
2872
+:mod:`ast` --- Abstract Syntax Trees
 
2873
+====================================
 
2874
 
 
2875
 .. module:: ast
 
2876
    :synopsis: Abstract Syntax Tree classes and manipulation.
 
2877
@@ -15,6 +13,9 @@
 
2878
 .. versionadded:: 2.6
 
2879
    The high-level ``ast`` module containing all helpers.
 
2880
 
 
2881
+**Source code:** :source:`Lib/ast.py`
 
2882
+
 
2883
+--------------
 
2884
 
 
2885
 The :mod:`ast` module helps Python applications to process trees of the Python
 
2886
 abstract syntax grammar.  The abstract syntax itself might change with each
 
2887
@@ -28,11 +29,6 @@
 
2888
 compiled into a Python code object using the built-in :func:`compile` function.
 
2889
 
 
2890
 
 
2891
-.. seealso::
 
2892
-
 
2893
-   Latest version of the `ast module Python source code
 
2894
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/ast.py?view=markup>`_
 
2895
-
 
2896
 Node classes
 
2897
 ------------
 
2898
 
 
2899
diff -r 8527427914a2 Doc/library/asynchat.rst
 
2900
--- a/Doc/library/asynchat.rst
 
2901
+++ b/Doc/library/asynchat.rst
 
2902
@@ -1,4 +1,3 @@
 
2903
-
 
2904
 :mod:`asynchat` --- Asynchronous socket command/response handler
 
2905
 ================================================================
 
2906
 
 
2907
@@ -7,6 +6,9 @@
 
2908
 .. moduleauthor:: Sam Rushing <rushing@nightmare.com>
 
2909
 .. sectionauthor:: Steve Holden <sholden@holdenweb.com>
 
2910
 
 
2911
+**Source code:** :source:`Lib/asynchat.py`
 
2912
+
 
2913
+--------------
 
2914
 
 
2915
 This module builds on the :mod:`asyncore` infrastructure, simplifying
 
2916
 asynchronous clients and servers and making it easier to handle protocols
 
2917
diff -r 8527427914a2 Doc/library/asyncore.rst
 
2918
--- a/Doc/library/asyncore.rst
 
2919
+++ b/Doc/library/asyncore.rst
 
2920
@@ -1,4 +1,3 @@
 
2921
-
 
2922
 :mod:`asyncore` --- Asynchronous socket handler
 
2923
 ===============================================
 
2924
 
 
2925
@@ -10,6 +9,9 @@
 
2926
 .. sectionauthor:: Steve Holden <sholden@holdenweb.com>
 
2927
 .. heavily adapted from original documentation by Sam Rushing
 
2928
 
 
2929
+**Source code:** :source:`Lib/asyncore.py`
 
2930
+
 
2931
+--------------
 
2932
 
 
2933
 This module provides the basic infrastructure for writing asynchronous  socket
 
2934
 service clients and servers.
535
2935
diff -r 8527427914a2 Doc/library/atexit.rst
536
2936
--- a/Doc/library/atexit.rst
537
2937
+++ b/Doc/library/atexit.rst
538
 
@@ -12,7 +12,9 @@
539
 
 
 
2938
@@ -1,4 +1,3 @@
 
2939
-
 
2940
 :mod:`atexit` --- Exit handlers
 
2941
 ===============================
 
2942
 
 
2943
@@ -10,14 +9,15 @@
 
2944
 
 
2945
 .. versionadded:: 2.0
 
2946
 
 
2947
+**Source code:** :source:`Lib/atexit.py`
 
2948
+
 
2949
+--------------
 
2950
+
540
2951
 The :mod:`atexit` module defines a single function to register cleanup
541
2952
 functions.  Functions thus registered are automatically executed upon normal
542
2953
-interpreter termination.
 
2954
-
 
2955
-.. seealso::
 
2956
-
 
2957
-   Latest version of the `atexit Python source code
 
2958
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/atexit.py?view=markup>`_
543
2959
+interpreter termination.  The order in which the functions are called is not
544
2960
+defined; if you have cleanup operations that depend on each other, you should
545
2961
+wrap them in a function and register that one.  This keeps :mod:`atexit` simple.
546
2962
 
547
 
 .. seealso::
548
 
 
 
2963
 Note: the functions registered via this module are not called when the program
 
2964
 is killed by a signal not handled by Python, when a Python fatal internal error
 
2965
diff -r 8527427914a2 Doc/library/basehttpserver.rst
 
2966
--- a/Doc/library/basehttpserver.rst
 
2967
+++ b/Doc/library/basehttpserver.rst
 
2968
@@ -18,6 +18,10 @@
 
2969
    module: SimpleHTTPServer
 
2970
    module: CGIHTTPServer
 
2971
 
 
2972
+**Source code:** :source:`Lib/BaseHTTPServer.py`
 
2973
+
 
2974
+--------------
 
2975
+
 
2976
 This module defines two classes for implementing HTTP servers (Web servers).
 
2977
 Usually, this module isn't used directly, but is used as a basis for building
 
2978
 functioning Web servers. See the :mod:`SimpleHTTPServer` and
 
2979
diff -r 8527427914a2 Doc/library/bdb.rst
 
2980
--- a/Doc/library/bdb.rst
 
2981
+++ b/Doc/library/bdb.rst
 
2982
@@ -4,6 +4,10 @@
 
2983
 .. module:: bdb
 
2984
    :synopsis: Debugger framework.
 
2985
 
 
2986
+**Source code:** :source:`Lib/bdb.py`
 
2987
+
 
2988
+--------------
 
2989
+
 
2990
 The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
 
2991
 or managing execution via the debugger.
 
2992
 
 
2993
diff -r 8527427914a2 Doc/library/bisect.rst
 
2994
--- a/Doc/library/bisect.rst
 
2995
+++ b/Doc/library/bisect.rst
 
2996
@@ -7,6 +7,12 @@
 
2997
 .. sectionauthor:: Raymond Hettinger <python at rcn.com>
 
2998
 .. example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>
 
2999
 
 
3000
+.. versionadded:: 2.1
 
3001
+
 
3002
+**Source code:** :source:`Lib/bisect.py`
 
3003
+
 
3004
+--------------
 
3005
+
 
3006
 This module provides support for maintaining a list in sorted order without
 
3007
 having to sort the list after each insertion.  For long lists of items with
 
3008
 expensive comparison operations, this can be an improvement over the more common
 
3009
@@ -14,13 +20,6 @@
 
3010
 algorithm to do its work.  The source code may be most useful as a working
 
3011
 example of the algorithm (the boundary conditions are already right!).
 
3012
 
 
3013
-.. versionadded:: 2.1
 
3014
-
 
3015
-.. seealso::
 
3016
-
 
3017
-   Latest version of the `bisect module Python source code
 
3018
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/bisect.py?view=markup>`_
 
3019
-
 
3020
 The following functions are provided:
 
3021
 
 
3022
 
 
3023
diff -r 8527427914a2 Doc/library/calendar.rst
 
3024
--- a/Doc/library/calendar.rst
 
3025
+++ b/Doc/library/calendar.rst
 
3026
@@ -1,4 +1,3 @@
 
3027
-
 
3028
 :mod:`calendar` --- General calendar-related functions
 
3029
 ======================================================
 
3030
 
 
3031
@@ -7,6 +6,9 @@
 
3032
               program.
 
3033
 .. sectionauthor:: Drew Csillag <drew_csillag@geocities.com>
 
3034
 
 
3035
+**Source code:** :source:`Lib/calendar.py`
 
3036
+
 
3037
+--------------
 
3038
 
 
3039
 This module allows you to output calendars like the Unix :program:`cal` program,
 
3040
 and provides additional useful functions related to the calendar. By default,
 
3041
@@ -22,10 +24,6 @@
 
3042
 calendar in Dershowitz and Reingold's book "Calendrical Calculations", where
 
3043
 it's the base calendar for all computations.
 
3044
 
 
3045
-.. seealso::
 
3046
-
 
3047
-   Latest version of the `calendar module Python source code
 
3048
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/calendar.py?view=markup>`_
 
3049
 
 
3050
 .. class:: Calendar([firstweekday])
 
3051
 
 
3052
diff -r 8527427914a2 Doc/library/cgi.rst
 
3053
--- a/Doc/library/cgi.rst
 
3054
+++ b/Doc/library/cgi.rst
 
3055
@@ -13,6 +13,10 @@
 
3056
    single: URL
 
3057
    single: Common Gateway Interface
 
3058
 
 
3059
+**Source code:** :source:`Lib/cgi.py`
 
3060
+
 
3061
+--------------
 
3062
+
 
3063
 Support module for Common Gateway Interface (CGI) scripts.
 
3064
 
 
3065
 This module defines a number of utilities for use by CGI scripts written in
549
3066
diff -r 8527427914a2 Doc/library/cmd.rst
550
3067
--- a/Doc/library/cmd.rst
551
3068
+++ b/Doc/library/cmd.rst
552
 
@@ -56,7 +56,7 @@
 
3069
@@ -1,4 +1,3 @@
 
3070
-
 
3071
 :mod:`cmd` --- Support for line-oriented command interpreters
 
3072
 =============================================================
 
3073
 
 
3074
@@ -6,17 +5,15 @@
 
3075
    :synopsis: Build line-oriented command interpreters.
 
3076
 .. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
 
3077
 
 
3078
+**Source code:** :source:`Lib/cmd.py`
 
3079
+
 
3080
+--------------
 
3081
 
 
3082
 The :class:`Cmd` class provides a simple framework for writing line-oriented
 
3083
 command interpreters.  These are often useful for test harnesses, administrative
 
3084
 tools, and prototypes that will later be wrapped in a more sophisticated
 
3085
 interface.
 
3086
 
 
3087
-.. seealso::
 
3088
-
 
3089
-   Latest version of the `cmd module Python source code
 
3090
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/cmd.py?view=markup>`_
 
3091
-
 
3092
 .. class:: Cmd([completekey[, stdin[, stdout]]])
 
3093
 
 
3094
    A :class:`Cmd` instance or subclass instance is a line-oriented interpreter
 
3095
@@ -56,7 +53,7 @@
553
3096
    the line as argument.
554
3097
 
555
3098
    The optional argument is a banner or intro string to be issued before the first
558
3101
 
559
3102
    If the :mod:`readline` module is loaded, input will automatically inherit
560
3103
    :program:`bash`\ -like history-list editing (e.g. :kbd:`Control-P` scrolls back
 
3104
diff -r 8527427914a2 Doc/library/codecs.rst
 
3105
--- a/Doc/library/codecs.rst
 
3106
+++ b/Doc/library/codecs.rst
 
3107
@@ -782,27 +782,28 @@
 
3108
 Windows). There's a string constant with 256 characters that shows you which
 
3109
 character is mapped to which byte value.
 
3110
 
 
3111
-All of these encodings can only encode 256 of the 65536 (or 1114111) codepoints
 
3112
+All of these encodings can only encode 256 of the 1114112 codepoints
 
3113
 defined in unicode. A simple and straightforward way that can store each Unicode
 
3114
-code point, is to store each codepoint as two consecutive bytes. There are two
 
3115
-possibilities: Store the bytes in big endian or in little endian order. These
 
3116
-two encodings are called UTF-16-BE and UTF-16-LE respectively. Their
 
3117
-disadvantage is that if e.g. you use UTF-16-BE on a little endian machine you
 
3118
-will always have to swap bytes on encoding and decoding. UTF-16 avoids this
 
3119
-problem: Bytes will always be in natural endianness. When these bytes are read
 
3120
+code point, is to store each codepoint as four consecutive bytes. There are two
 
3121
+possibilities: store the bytes in big endian or in little endian order. These
 
3122
+two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
 
3123
+disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
 
3124
+will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
 
3125
+problem: bytes will always be in natural endianness. When these bytes are read
 
3126
 by a CPU with a different endianness, then bytes have to be swapped though. To
 
3127
-be able to detect the endianness of a UTF-16 byte sequence, there's the so
 
3128
-called BOM (the "Byte Order Mark"). This is the Unicode character ``U+FEFF``.
 
3129
-This character will be prepended to every UTF-16 byte sequence. The byte swapped
 
3130
-version of this character (``0xFFFE``) is an illegal character that may not
 
3131
-appear in a Unicode text. So when the first character in an UTF-16 byte sequence
 
3132
+be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
 
3133
+there's the so called BOM ("Byte Order Mark"). This is the Unicode character
 
3134
+``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
 
3135
+byte sequence. The byte swapped version of this character (``0xFFFE``) is an
 
3136
+illegal character that may not appear in a Unicode text. So when the
 
3137
+first character in an ``UTF-16`` or ``UTF-32`` byte sequence
 
3138
 appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
 
3139
-Unfortunately upto Unicode 4.0 the character ``U+FEFF`` had a second purpose as
 
3140
-a ``ZERO WIDTH NO-BREAK SPACE``: A character that has no width and doesn't allow
 
3141
+Unfortunately the character ``U+FEFF`` had a second purpose as
 
3142
+a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
 
3143
 a word to be split. It can e.g. be used to give hints to a ligature algorithm.
 
3144
 With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
 
3145
 deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
 
3146
-Unicode software still must be able to handle ``U+FEFF`` in both roles: As a BOM
 
3147
+Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
 
3148
 it's a device to determine the storage layout of the encoded bytes, and vanishes
 
3149
 once the byte sequence has been decoded into a Unicode string; as a ``ZERO WIDTH
 
3150
 NO-BREAK SPACE`` it's a normal character that will be decoded like any other.
 
3151
@@ -810,8 +811,8 @@
 
3152
 There's another encoding that is able to encoding the full range of Unicode
 
3153
 characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
 
3154
 with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
 
3155
-parts: Marker bits (the most significant bits) and payload bits. The marker bits
 
3156
-are a sequence of zero to six 1 bits followed by a 0 bit. Unicode characters are
 
3157
+parts: marker bits (the most significant bits) and payload bits. The marker bits
 
3158
+are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
 
3159
 encoded like this (with x being payload bits, which when concatenated give the
 
3160
 Unicode character):
 
3161
 
 
3162
@@ -824,12 +825,7 @@
 
3163
 +-----------------------------------+----------------------------------------------+
 
3164
 | ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx                   |
 
3165
 +-----------------------------------+----------------------------------------------+
 
3166
-| ``U-00010000`` ... ``U-001FFFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx          |
 
3167
-+-----------------------------------+----------------------------------------------+
 
3168
-| ``U-00200000`` ... ``U-03FFFFFF`` | 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
 
3169
-+-----------------------------------+----------------------------------------------+
 
3170
-| ``U-04000000`` ... ``U-7FFFFFFF`` | 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx |
 
3171
-|                                   | 10xxxxxx                                     |
 
3172
+| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx          |
 
3173
 +-----------------------------------+----------------------------------------------+
 
3174
 
 
3175
 The least significant bit of the Unicode character is the rightmost x bit.
 
3176
@@ -854,13 +850,14 @@
 
3177
    | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
 
3178
    | INVERTED QUESTION MARK
 
3179
 
 
3180
-in iso-8859-1), this increases the probability that a utf-8-sig encoding can be
 
3181
+in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
 
3182
 correctly guessed from the byte sequence. So here the BOM is not used to be able
 
3183
 to determine the byte order used for generating the byte sequence, but as a
 
3184
 signature that helps in guessing the encoding. On encoding the utf-8-sig codec
 
3185
 will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
 
3186
-decoding utf-8-sig will skip those three bytes if they appear as the first three
 
3187
-bytes in the file.
 
3188
+decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
 
3189
+three bytes in the file.  In UTF-8, the use of the BOM is discouraged and
 
3190
+should generally be avoided.
 
3191
 
 
3192
 
 
3193
 .. _standard-encodings:
561
3194
diff -r 8527427914a2 Doc/library/collections.rst
562
3195
--- a/Doc/library/collections.rst
563
3196
+++ b/Doc/library/collections.rst
564
 
@@ -28,7 +28,7 @@
 
3197
@@ -1,4 +1,3 @@
 
3198
-
 
3199
 :mod:`collections` --- High-performance container datatypes
 
3200
 ===========================================================
 
3201
 
 
3202
@@ -15,6 +14,10 @@
 
3203
    import itertools
 
3204
    __name__ = '<doctest>'
 
3205
 
 
3206
+**Source code:** :source:`Lib/collections.py` and :source:`Lib/_abcoll.py`
 
3207
+
 
3208
+--------------
 
3209
+
 
3210
 This module implements specialized container datatypes providing alternatives to
 
3211
 Python's general purpose built-in containers, :class:`dict`, :class:`list`,
 
3212
 :class:`set`, and :class:`tuple`.
 
3213
@@ -28,13 +31,10 @@
565
3214
 =====================   ====================================================================  ===========================
566
3215
 
567
3216
 In addition to the concrete container classes, the collections module provides
568
3217
-:ref:`abstract-base-classes` that can be used to test whether a class provides a
569
 
+:ref:`collections-abstract-base-classes` that can be used to test whether a class provides a
570
 
 particular interface, for example, whether it is hashable or a mapping.
571
 
 
572
 
 .. seealso::
573
 
@@ -623,7 +623,9 @@
 
3218
-particular interface, for example, whether it is hashable or a mapping.
 
3219
+:ref:`abstract base classes <collections-abstract-base-classes>` that can be
 
3220
+used to test whether a class provides a particular interface, for example,
 
3221
+whether it is hashable or a mapping.
 
3222
 
 
3223
-.. seealso::
 
3224
-
 
3225
-   Latest version of the `collections module Python source code
 
3226
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/collections.py?view=markup>`_
 
3227
 
 
3228
 :class:`Counter` objects
 
3229
 ------------------------
 
3230
@@ -188,7 +188,7 @@
 
3231
    * The multiset methods are designed only for use cases with positive values.
 
3232
      The inputs may be negative or zero, but only outputs with positive values
 
3233
      are created.  There are no type restrictions, but the value type needs to
 
3234
-     support support addition, subtraction, and comparison.
 
3235
+     support addition, subtraction, and comparison.
 
3236
 
 
3237
    * The :meth:`elements` method requires integer counts.  It ignores zero and
 
3238
      negative counts.
 
3239
@@ -202,14 +202,14 @@
 
3240
     * `Bag class <http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
 
3241
       in Smalltalk.
 
3242
 
 
3243
-    * Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_\.
 
3244
+    * Wikipedia entry for `Multisets <http://en.wikipedia.org/wiki/Multiset>`_.
 
3245
 
 
3246
     * `C++ multisets <http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
 
3247
       tutorial with examples.
 
3248
 
 
3249
     * For mathematical operations on multisets and their use cases, see
 
3250
       *Knuth, Donald. The Art of Computer Programming Volume II,
 
3251
-      Section 4.6.3, Exercise 19*\.
 
3252
+      Section 4.6.3, Exercise 19*.
 
3253
 
 
3254
     * To enumerate all distinct multisets of a given size over a given set of
 
3255
       elements, see :func:`itertools.combinations_with_replacement`.
 
3256
@@ -453,8 +453,7 @@
 
3257
    :class:`defaultdict` objects support the following method in addition to the
 
3258
    standard :class:`dict` operations:
 
3259
 
 
3260
-
 
3261
-   .. method:: defaultdict.__missing__(key)
 
3262
+   .. method:: __missing__(key)
 
3263
 
 
3264
       If the :attr:`default_factory` attribute is ``None``, this raises a
 
3265
       :exc:`KeyError` exception with the *key* as argument.
 
3266
@@ -474,7 +473,7 @@
 
3267
    :class:`defaultdict` objects support the following instance variable:
 
3268
 
 
3269
 
 
3270
-   .. attribute:: defaultdict.default_factory
 
3271
+   .. attribute:: default_factory
 
3272
 
 
3273
       This attribute is used by the :meth:`__missing__` method; it is
 
3274
       initialized from the first argument to the constructor, if present, or to
 
3275
@@ -623,7 +622,9 @@
574
3276
                'Return a new OrderedDict which maps field names to their values'
575
3277
                return OrderedDict(zip(self._fields, self))
576
3278
    <BLANKLINE>
581
3283
                'Return a new Point object replacing specified fields with new values'
582
3284
                result = _self._make(map(kwds.pop, ('x', 'y'), _self))
583
3285
                if kwds:
584
 
@@ -849,8 +851,8 @@
 
3286
@@ -849,14 +850,14 @@
585
3287
 original insertion position is changed and moved to the end::
586
3288
 
587
3289
     class LastUpdatedOrderedDict(OrderedDict):
591
3293
         def __setitem__(self, key, value):
592
3294
             if key in self:
593
3295
                 del self[key]
594
 
@@ -869,10 +871,10 @@
 
3296
             OrderedDict.__setitem__(self, key, value)
 
3297
 
 
3298
-An ordered dictionary can combined with the :class:`Counter` class
 
3299
+An ordered dictionary can be combined with the :class:`Counter` class
 
3300
 so that the counter remembers the order elements are first encountered::
 
3301
 
 
3302
    class OrderedCounter(Counter, OrderedDict):
 
3303
@@ -869,10 +870,10 @@
595
3304
             return self.__class__, (OrderedDict(self),)
596
3305
 
597
3306
 
605
3314
 
606
3315
 The collections module offers the following :term:`ABCs <abstract base class>`:
607
3316
 
608
 
@@ -886,7 +888,7 @@
 
3317
@@ -886,7 +887,7 @@
609
3318
 :class:`Sized`                                    ``__len__``
610
3319
 :class:`Callable`                                 ``__call__``
611
3320
 
614
3323
                            :class:`Iterable`,                             ``index``, and ``count``
615
3324
                            :class:`Container`
616
3325
 
 
3326
@@ -1021,9 +1022,6 @@
 
3327
 
 
3328
 .. seealso::
 
3329
 
 
3330
-   * Latest version of the `Python source code for the collections abstract base classes
 
3331
-     <http://svn.python.org/view/python/branches/release27-maint/Lib/_abcoll.py?view=markup>`_
 
3332
-
 
3333
    * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
 
3334
      example built on :class:`MutableSet`.
 
3335
 
 
3336
diff -r 8527427914a2 Doc/library/colorsys.rst
 
3337
--- a/Doc/library/colorsys.rst
 
3338
+++ b/Doc/library/colorsys.rst
 
3339
@@ -5,6 +5,9 @@
 
3340
    :synopsis: Conversion functions between RGB and other color systems.
 
3341
 .. sectionauthor:: David Ascher <da@python.net>
 
3342
 
 
3343
+**Source code:** :source:`Lib/colorsys.py`
 
3344
+
 
3345
+--------------
 
3346
 
 
3347
 The :mod:`colorsys` module defines bidirectional conversions of color values
 
3348
 between colors expressed in the RGB (Red Green Blue) color space used in
617
3349
diff -r 8527427914a2 Doc/library/constants.rst
618
3350
--- a/Doc/library/constants.rst
619
3351
+++ b/Doc/library/constants.rst
623
3355
 Built-in Constants
624
3356
 ==================
625
3357
 
 
3358
diff -r 8527427914a2 Doc/library/contextlib.rst
 
3359
--- a/Doc/library/contextlib.rst
 
3360
+++ b/Doc/library/contextlib.rst
 
3361
@@ -7,15 +7,14 @@
 
3362
 
 
3363
 .. versionadded:: 2.5
 
3364
 
 
3365
+**Source code:** :source:`Lib/contextlib.py`
 
3366
+
 
3367
+--------------
 
3368
+
 
3369
 This module provides utilities for common tasks involving the :keyword:`with`
 
3370
 statement. For more information see also :ref:`typecontextmanager` and
 
3371
 :ref:`context-managers`.
 
3372
 
 
3373
-.. seealso::
 
3374
-
 
3375
-   Latest version of the `contextlib Python source code
 
3376
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/contextlib.py?view=markup>`_
 
3377
-
 
3378
 Functions provided:
 
3379
 
 
3380
 
626
3381
diff -r 8527427914a2 Doc/library/cookie.rst
627
3382
--- a/Doc/library/cookie.rst
628
3383
+++ b/Doc/library/cookie.rst
629
 
@@ -191,7 +191,7 @@
 
3384
@@ -11,6 +11,9 @@
 
3385
    3.0.  The :term:`2to3` tool will automatically adapt imports when converting
 
3386
    your sources to 3.0.
 
3387
 
 
3388
+**Source code:** :source:`Lib/Cookie.py`
 
3389
+
 
3390
+--------------
 
3391
 
 
3392
 The :mod:`Cookie` module defines classes for abstracting the concept of
 
3393
 cookies, an HTTP state management mechanism. It supports both simple string-only
 
3394
@@ -191,7 +194,7 @@
630
3395
 
631
3396
 .. method:: Morsel.set(key, value, coded_value)
632
3397
 
635
3400
 
636
3401
 
637
3402
 .. method:: Morsel.isReservedKey(K)
 
3403
diff -r 8527427914a2 Doc/library/cookielib.rst
 
3404
--- a/Doc/library/cookielib.rst
 
3405
+++ b/Doc/library/cookielib.rst
 
3406
@@ -11,10 +11,11 @@
 
3407
    Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
 
3408
    converting your sources to 3.0.
 
3409
 
 
3410
-
 
3411
 .. versionadded:: 2.4
 
3412
 
 
3413
+**Source code:** :source:`Lib/cookielib.py`
 
3414
 
 
3415
+--------------
 
3416
 
 
3417
 The :mod:`cookielib` module defines classes for automatic handling of HTTP
 
3418
 cookies.  It is useful for accessing web sites that require small pieces of data
638
3419
diff -r 8527427914a2 Doc/library/crypto.rst
639
3420
--- a/Doc/library/crypto.rst
640
3421
+++ b/Doc/library/crypto.rst
661
3442
 
662
3443
 The straightforward translation into ctypes code would be this, but it does not
663
3444
 work::
 
3445
@@ -2000,7 +2000,7 @@
 
3446
 
 
3447
 .. function:: string_at(address[, size])
 
3448
 
 
3449
-   This function returns the string starting at memory address address. If size
 
3450
+   This function returns the string starting at memory address *address*. If size
 
3451
    is specified, it is used as size, otherwise the string is assumed to be
 
3452
    zero-terminated.
 
3453
 
664
3454
diff -r 8527427914a2 Doc/library/curses.rst
665
3455
--- a/Doc/library/curses.rst
666
3456
+++ b/Doc/library/curses.rst
1640
4430
 
1641
4431
    Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
1642
4432
    :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
 
4433
@@ -1161,19 +1164,19 @@
 
4434
 
 
4435
 .. attribute:: time.min
 
4436
 
 
4437
-   The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
 
4438
+   The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
 
4439
 
 
4440
 
 
4441
 .. attribute:: time.max
 
4442
 
 
4443
-   The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
 
4444
+   The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
 
4445
 
 
4446
 
 
4447
 .. attribute:: time.resolution
 
4448
 
 
4449
-   The smallest possible difference between non-equal :class:`time` objects,
 
4450
-   ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
 
4451
-   objects is not supported.
 
4452
+   The smallest possible difference between non-equal :class:`.time` objects,
 
4453
+   ``timedelta(microseconds=1)``, although note that arithmetic on
 
4454
+   :class:`.time` objects is not supported.
 
4455
 
 
4456
 
 
4457
 Instance attributes (read-only):
 
4458
@@ -1200,7 +1203,7 @@
 
4459
 
 
4460
 .. attribute:: time.tzinfo
 
4461
 
 
4462
-   The object passed as the tzinfo argument to the :class:`time` constructor, or
 
4463
+   The object passed as the tzinfo argument to the :class:`.time` constructor, or
 
4464
    ``None`` if none was passed.
 
4465
 
 
4466
 
1643
4467
@@ -1209,14 +1212,14 @@
1644
4468
 * comparison of :class:`time` to :class:`time`, where *a* is considered less
1645
4469
   than *b* when *a* precedes *b* in time.  If one comparand is naive and the other
1671
4495
-   values by whichever keyword arguments are specified.  Note that ``tzinfo=None``
1672
4496
-   can be specified to create a naive :class:`time` from an aware :class:`time`,
1673
4497
-   without conversion of the time members.
1674
 
+   Return a :class:`time` with the same value, except for those attributes given
 
4498
+   Return a :class:`.time` with the same value, except for those attributes given
1675
4499
+   new values by whichever keyword arguments are specified.  Note that
1676
 
+   ``tzinfo=None`` can be specified to create a naive :class:`time` from an
1677
 
+   aware :class:`time`, without conversion of the time data.
 
4500
+   ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
 
4501
+   aware :class:`.time`, without conversion of the time data.
1678
4502
 
1679
4503
 
1680
4504
 .. method:: time.isoformat()
1700
4524
 
1701
4525
    An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1702
4526
    daylight times must be consistent in this sense:
 
4527
@@ -1382,13 +1385,13 @@
 
4528
 
 
4529
    Most implementations of :meth:`dst` will probably look like one of these two::
 
4530
 
 
4531
-      def dst(self):
 
4532
+      def dst(self, dt):
 
4533
           # a fixed-offset class:  doesn't account for DST
 
4534
           return timedelta(0)
 
4535
 
 
4536
    or ::
 
4537
 
 
4538
-      def dst(self):
 
4539
+      def dst(self, dt):
 
4540
           # Code to set dston and dstoff to the time zone's DST
 
4541
           # transition times based on the input dt.year, and expressed
 
4542
           # in standard local time.  Then
1703
4543
@@ -1439,11 +1442,11 @@
1704
4544
 
1705
4545
 .. method:: tzinfo.fromutc(self, dt)
1729
4569
       of an equivalence class. For example, ``Decimal('32.100')`` and
1730
4570
       ``Decimal('0.321000e+2')`` both normalize to the equivalent value
1731
4571
       ``Decimal('32.1')``.
 
4572
diff -r 8527427914a2 Doc/library/dis.rst
 
4573
--- a/Doc/library/dis.rst
 
4574
+++ b/Doc/library/dis.rst
 
4575
@@ -1,21 +1,18 @@
 
4576
-
 
4577
 :mod:`dis` --- Disassembler for Python bytecode
 
4578
 ===============================================
 
4579
 
 
4580
 .. module:: dis
 
4581
    :synopsis: Disassembler for Python bytecode.
 
4582
 
 
4583
+**Source code:** :source:`Lib/dis.py`
 
4584
+
 
4585
+--------------
 
4586
 
 
4587
 The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
 
4588
 disassembling it. The CPython bytecode which this module takes as an
 
4589
 input is defined in the file :file:`Include/opcode.h` and used by the compiler
 
4590
 and the interpreter.
 
4591
 
 
4592
-.. seealso::
 
4593
-
 
4594
-   Latest version of the `dis module Python source code
 
4595
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/dis.py?view=markup>`_
 
4596
-
 
4597
 .. impl-detail::
 
4598
 
 
4599
    Bytecode is an implementation detail of the CPython interpreter!  No
1732
4600
diff -r 8527427914a2 Doc/library/doctest.rst
1733
4601
--- a/Doc/library/doctest.rst
1734
4602
+++ b/Doc/library/doctest.rst
1789
4657
 
1790
4658
 
1791
4659
 .. attribute:: UnexpectedException.test
 
4660
diff -r 8527427914a2 Doc/library/dummy_thread.rst
 
4661
--- a/Doc/library/dummy_thread.rst
 
4662
+++ b/Doc/library/dummy_thread.rst
 
4663
@@ -10,6 +10,9 @@
 
4664
    converting your sources to 3.0; however, you should consider using the
 
4665
    high-lever :mod:`dummy_threading` module instead.
 
4666
 
 
4667
+**Source code:** :source:`Lib/dummy_thread.py`
 
4668
+
 
4669
+--------------
 
4670
 
 
4671
 This module provides a duplicate interface to the :mod:`thread` module.  It is
 
4672
 meant to be imported when the :mod:`thread` module is not provided on a
 
4673
diff -r 8527427914a2 Doc/library/dummy_threading.rst
 
4674
--- a/Doc/library/dummy_threading.rst
 
4675
+++ b/Doc/library/dummy_threading.rst
 
4676
@@ -1,10 +1,12 @@
 
4677
-
 
4678
 :mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module
 
4679
 ==============================================================================
 
4680
 
 
4681
 .. module:: dummy_threading
 
4682
    :synopsis: Drop-in replacement for the threading module.
 
4683
 
 
4684
+**Source code:** :source:`Lib/dummy_threading.py`
 
4685
+
 
4686
+--------------
 
4687
 
 
4688
 This module provides a duplicate interface to the :mod:`threading` module.  It
 
4689
 is meant to be imported when the :mod:`thread` module is not provided on a
 
4690
diff -r 8527427914a2 Doc/library/email.message.rst
 
4691
--- a/Doc/library/email.message.rst
 
4692
+++ b/Doc/library/email.message.rst
 
4693
@@ -295,7 +295,7 @@
 
4694
 
 
4695
          Content-Disposition: attachment; filename="bud.gif"
 
4696
 
 
4697
-      An example with with non-ASCII characters::
 
4698
+      An example with non-ASCII characters::
 
4699
 
 
4700
          msg.add_header('Content-Disposition', 'attachment',
 
4701
                         filename=('iso-8859-1', '', 'Fußballer.ppt'))
 
4702
diff -r 8527427914a2 Doc/library/email.mime.rst
 
4703
--- a/Doc/library/email.mime.rst
 
4704
+++ b/Doc/library/email.mime.rst
 
4705
@@ -196,6 +196,6 @@
 
4706
 
 
4707
    .. versionchanged:: 2.4
 
4708
       The previously deprecated *_encoding* argument has been removed.  Content
 
4709
-      Transfer Encoding now happens happens implicitly based on the *_charset*
 
4710
+      Transfer Encoding now happens implicitly based on the *_charset*
 
4711
       argument.
 
4712
 
 
4713
diff -r 8527427914a2 Doc/library/filecmp.rst
 
4714
--- a/Doc/library/filecmp.rst
 
4715
+++ b/Doc/library/filecmp.rst
 
4716
@@ -1,4 +1,3 @@
 
4717
-
 
4718
 :mod:`filecmp` --- File and Directory Comparisons
 
4719
 =================================================
 
4720
 
 
4721
@@ -6,16 +5,14 @@
 
4722
    :synopsis: Compare files efficiently.
 
4723
 .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
 
4724
 
 
4725
+**Source code:** :source:`Lib/filecmp.py`
 
4726
+
 
4727
+--------------
 
4728
 
 
4729
 The :mod:`filecmp` module defines functions to compare files and directories,
 
4730
 with various optional time/correctness trade-offs. For comparing files,
 
4731
 see also the :mod:`difflib` module.
 
4732
 
 
4733
-.. seealso::
 
4734
-
 
4735
-   Latest version of the `filecmp Python source code
 
4736
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/filecmp.py?view=markup>`_
 
4737
-
 
4738
 The :mod:`filecmp` module defines the following functions:
 
4739
 
 
4740
 
 
4741
diff -r 8527427914a2 Doc/library/fileinput.rst
 
4742
--- a/Doc/library/fileinput.rst
 
4743
+++ b/Doc/library/fileinput.rst
 
4744
@@ -6,6 +6,9 @@
 
4745
 .. moduleauthor:: Guido van Rossum <guido@python.org>
 
4746
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
4747
 
 
4748
+**Source code:** :source:`Lib/fileinput.py`
 
4749
+
 
4750
+--------------
 
4751
 
 
4752
 This module implements a helper class and functions to quickly write a
 
4753
 loop over standard input or a list of files. If you just want to read or
 
4754
@@ -44,11 +47,6 @@
 
4755
 returns an accordingly opened file-like object. Two useful hooks are already
 
4756
 provided by this module.
 
4757
 
 
4758
-.. seealso::
 
4759
-
 
4760
-   Latest version of the `fileinput Python source code
 
4761
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/fileinput.py?view=markup>`_
 
4762
-
 
4763
 The following function is the primary interface of this module:
 
4764
 
 
4765
 
 
4766
diff -r 8527427914a2 Doc/library/fnmatch.rst
 
4767
--- a/Doc/library/fnmatch.rst
 
4768
+++ b/Doc/library/fnmatch.rst
 
4769
@@ -1,4 +1,3 @@
 
4770
-
 
4771
 :mod:`fnmatch` --- Unix filename pattern matching
 
4772
 =================================================
 
4773
 
 
4774
@@ -10,6 +9,10 @@
 
4775
 
 
4776
 .. index:: module: re
 
4777
 
 
4778
+**Source code:** :source:`Lib/fnmatch.py`
 
4779
+
 
4780
+--------------
 
4781
+
 
4782
 This module provides support for Unix shell-style wildcards, which are *not* the
 
4783
 same as regular expressions (which are documented in the :mod:`re` module).  The
 
4784
 special characters used in shell-style wildcards are:
 
4785
@@ -34,10 +37,6 @@
 
4786
 a period are not special for this module, and are matched by the ``*`` and ``?``
 
4787
 patterns.
 
4788
 
 
4789
-.. seealso::
 
4790
-
 
4791
-   Latest version of the `fnmatch Python source code
 
4792
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/fnmatch.py?view=markup>`_
 
4793
 
 
4794
 .. function:: fnmatch(filename, pattern)
 
4795
 
 
4796
@@ -95,4 +94,3 @@
 
4797
 
 
4798
    Module :mod:`glob`
 
4799
       Unix shell-style path expansion.
 
4800
-
 
4801
diff -r 8527427914a2 Doc/library/fractions.rst
 
4802
--- a/Doc/library/fractions.rst
 
4803
+++ b/Doc/library/fractions.rst
 
4804
@@ -1,4 +1,3 @@
 
4805
-
 
4806
 :mod:`fractions` --- Rational numbers
 
4807
 =====================================
 
4808
 
 
4809
@@ -8,6 +7,9 @@
 
4810
 .. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
 
4811
 .. versionadded:: 2.6
 
4812
 
 
4813
+**Source code:** :source:`Lib/fractions.py`
 
4814
+
 
4815
+--------------
 
4816
 
 
4817
 The :mod:`fractions` module provides support for rational number arithmetic.
 
4818
 
 
4819
diff -r 8527427914a2 Doc/library/ftplib.rst
 
4820
--- a/Doc/library/ftplib.rst
 
4821
+++ b/Doc/library/ftplib.rst
 
4822
@@ -9,6 +9,10 @@
 
4823
    pair: FTP; protocol
 
4824
    single: FTP; ftplib (standard module)
 
4825
 
 
4826
+**Source code:** :source:`Lib/ftplib.py`
 
4827
+
 
4828
+--------------
 
4829
+
 
4830
 This module defines the class :class:`FTP` and a few related items. The
 
4831
 :class:`FTP` class implements the client side of the FTP protocol.  You can use
 
4832
 this to write Python programs that perform a variety of automated FTP jobs, such
1792
4833
diff -r 8527427914a2 Doc/library/functions.rst
1793
4834
--- a/Doc/library/functions.rst
1794
4835
+++ b/Doc/library/functions.rst
1795
 
@@ -298,19 +298,18 @@
 
4836
@@ -123,6 +123,8 @@
 
4837
 
 
4838
    Without an argument, an array of size 0 is created.
 
4839
 
 
4840
+   .. versionadded:: 2.6
 
4841
+
 
4842
 
 
4843
 .. function:: callable(object)
 
4844
 
 
4845
@@ -298,19 +300,18 @@
1796
4846
    The resulting list is sorted alphabetically.  For example:
1797
4847
 
1798
4848
       >>> import struct
1820
4870
 
1821
4871
    .. note::
1822
4872
 
1823
 
@@ -342,20 +341,25 @@
 
4873
@@ -342,20 +343,25 @@
1824
4874
    :term:`iterator`, or some other object which supports iteration.  The
1825
4875
    :meth:`!next` method of the iterator returned by :func:`enumerate` returns a
1826
4876
    tuple containing a count (from *start* which defaults to 0) and the
1857
4907
 
1858
4908
 
1859
4909
 .. function:: eval(expression[, globals[, locals]])
1860
 
@@ -579,20 +583,19 @@
 
4910
@@ -579,20 +585,19 @@
1861
4911
    Two objects with non-overlapping lifetimes may have the same :func:`id`
1862
4912
    value.
1863
4913
 
1884
4934
 
1885
4935
    If the :mod:`readline` module was loaded, then :func:`input` will use it to
1886
4936
    provide elaborate line editing and history features.
1887
 
@@ -660,10 +663,10 @@
 
4937
@@ -621,9 +626,11 @@
 
4938
 .. function:: isinstance(object, classinfo)
 
4939
 
 
4940
    Return true if the *object* argument is an instance of the *classinfo* argument,
 
4941
-   or of a (direct or indirect) subclass thereof.  Also return true if *classinfo*
 
4942
+   or of a (direct, indirect or :term:`virtual <abstract base class>`) subclass
 
4943
+   thereof.  Also return true if *classinfo*
 
4944
    is a type object (new-style class) and *object* is an object of that type or of
 
4945
-   a (direct or indirect) subclass thereof.  If *object* is not a class instance or
 
4946
+   a (direct, indirect or :term:`virtual <abstract base class>`) subclass
 
4947
+   thereof.  If *object* is not a class instance or
 
4948
    an object of the given type, the function always returns false.  If *classinfo*
 
4949
    is neither a class object nor a type object, it may be a tuple of class or type
 
4950
    objects, or may recursively contain other such tuples (other sequence types are
 
4951
@@ -636,7 +643,8 @@
 
4952
 
 
4953
 .. function:: issubclass(class, classinfo)
 
4954
 
 
4955
-   Return true if *class* is a subclass (direct or indirect) of *classinfo*.  A
 
4956
+   Return true if *class* is a subclass (direct, indirect or :term:`virtual
 
4957
+   <abstract base class>`) of *classinfo*.  A
 
4958
    class is considered a subclass of itself. *classinfo* may be a tuple of class
 
4959
    objects, in which case every entry in *classinfo* will be checked. In any other
 
4960
    case, a :exc:`TypeError` exception is raised.
 
4961
@@ -660,10 +668,10 @@
1888
4962
 
1889
4963
    One useful application of the second form of :func:`iter` is to read lines of
1890
4964
    a file until a certain line is reached.  The following example reads a file
1898
4972
               process_line(line)
1899
4973
 
1900
4974
    .. versionadded:: 2.2
1901
 
@@ -793,7 +796,7 @@
 
4975
@@ -793,7 +801,7 @@
1902
4976
       Formerly only returned an unsigned literal.
1903
4977
 
1904
4978
 
1907
4981
 
1908
4982
    Open a file, returning an object of the :class:`file` type described in
1909
4983
    section :ref:`bltin-file-objects`.  If the file cannot be opened,
1910
 
@@ -801,7 +804,7 @@
 
4984
@@ -801,7 +809,7 @@
1911
4985
    :func:`open` instead of invoking the :class:`file` constructor directly.
1912
4986
 
1913
4987
    The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`:
1916
4990
    the file is to be opened.
1917
4991
 
1918
4992
    The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for
1919
 
@@ -822,9 +825,9 @@
 
4993
@@ -822,9 +830,9 @@
1920
4994
       single: buffer size, I/O
1921
4995
       single: I/O control; buffering
1922
4996
 
1928
5002
    system default, which is usually line buffered for tty devices and fully
1929
5003
    buffered for other files.  If omitted, the system default is used. [#]_
1930
5004
 
1931
 
@@ -1241,8 +1244,9 @@
 
5005
@@ -1241,8 +1249,9 @@
1932
5006
    It can be called either on the class (such as ``C.f()``) or on an instance (such
1933
5007
    as ``C().f()``).  The instance is ignored except for its class.
1934
5008
 
1940
5014
 
1941
5015
    For more information on static methods, consult the documentation on the
1942
5016
    standard type hierarchy in :ref:`types`.
1943
 
@@ -1335,6 +1339,10 @@
 
5017
@@ -1335,6 +1344,10 @@
1944
5018
    argument form specifies the arguments exactly and makes the appropriate
1945
5019
    references.
1946
5020
 
1951
5025
    .. versionadded:: 2.2
1952
5026
 
1953
5027
 
 
5028
diff -r 8527427914a2 Doc/library/functools.rst
 
5029
--- a/Doc/library/functools.rst
 
5030
+++ b/Doc/library/functools.rst
 
5031
@@ -8,18 +8,16 @@
 
5032
 .. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>
 
5033
 .. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>
 
5034
 
 
5035
+.. versionadded:: 2.5
 
5036
 
 
5037
-.. versionadded:: 2.5
 
5038
+**Source code:** :source:`Lib/functools.py`
 
5039
+
 
5040
+--------------
 
5041
 
 
5042
 The :mod:`functools` module is for higher-order functions: functions that act on
 
5043
 or return other functions. In general, any callable object can be treated as a
 
5044
 function for the purposes of this module.
 
5045
 
 
5046
-.. seealso::
 
5047
-
 
5048
-   Latest version of the `functools Python source code
 
5049
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/functools.py?view=markup>`_
 
5050
-
 
5051
 The :mod:`functools` module defines the following functions:
 
5052
 
 
5053
 ..  function:: cmp_to_key(func)
 
5054
diff -r 8527427914a2 Doc/library/getopt.rst
 
5055
--- a/Doc/library/getopt.rst
 
5056
+++ b/Doc/library/getopt.rst
 
5057
@@ -1,4 +1,3 @@
 
5058
-
 
5059
 :mod:`getopt` --- C-style parser for command line options
 
5060
 =========================================================
 
5061
 
 
5062
@@ -6,6 +5,10 @@
 
5063
    :synopsis: Portable parser for command line options; support both short and long option
 
5064
               names.
 
5065
 
 
5066
+**Source code:** :source:`Lib/getopt.py`
 
5067
+
 
5068
+--------------
 
5069
+
 
5070
 .. note::
 
5071
    The :mod:`getopt` module is a parser for command line options whose API is
 
5072
    designed to be familiar to users of the C :cfunc:`getopt` function. Users who
 
5073
@@ -19,9 +22,6 @@
 
5074
 options similar to those supported by GNU software may be used as well via an
 
5075
 optional third argument.
 
5076
 
 
5077
-A more convenient, flexible, and powerful alternative is the
 
5078
-:mod:`optparse` module.
 
5079
-
 
5080
 This module provides two functions and an
 
5081
 exception:
 
5082
 
 
5083
diff -r 8527427914a2 Doc/library/gettext.rst
 
5084
--- a/Doc/library/gettext.rst
 
5085
+++ b/Doc/library/gettext.rst
 
5086
@@ -1,4 +1,3 @@
 
5087
-
 
5088
 :mod:`gettext` --- Multilingual internationalization services
 
5089
 =============================================================
 
5090
 
 
5091
@@ -7,6 +6,9 @@
 
5092
 .. moduleauthor:: Barry A. Warsaw <barry@zope.com>
 
5093
 .. sectionauthor:: Barry A. Warsaw <barry@zope.com>
 
5094
 
 
5095
+**Source code:** :source:`Lib/gettext.py`
 
5096
+
 
5097
+--------------
 
5098
 
 
5099
 The :mod:`gettext` module provides internationalization (I18N) and localization
 
5100
 (L10N) services for your Python modules and applications. It supports both the
 
5101
@@ -298,7 +300,7 @@
 
5102
 
 
5103
    .. method:: lngettext(singular, plural, n)
 
5104
 
 
5105
-      If a fallback has been set, forward :meth:`ngettext` to the
 
5106
+      If a fallback has been set, forward :meth:`lngettext` to the
 
5107
       fallback. Otherwise, return the translated message.  Overridden in derived
 
5108
       classes.
 
5109
 
 
5110
@@ -754,8 +756,8 @@
 
5111
 .. [#] See the footnote for :func:`bindtextdomain` above.
 
5112
 
 
5113
 .. [#] François Pinard has written a program called :program:`xpot` which does a
 
5114
-   similar job.  It is available as part of his :program:`po-utils` package at http
 
5115
-   ://po-utils.progiciels-bpi.ca/.
 
5116
+   similar job.  It is available as part of his `po-utils package
 
5117
+   <http://po-utils.progiciels-bpi.ca/>`_.
 
5118
 
 
5119
 .. [#] :program:`msgfmt.py` is binary compatible with GNU :program:`msgfmt` except that
 
5120
    it provides a simpler, all-Python implementation.  With this and
 
5121
diff -r 8527427914a2 Doc/library/glob.rst
 
5122
--- a/Doc/library/glob.rst
 
5123
+++ b/Doc/library/glob.rst
 
5124
@@ -1,4 +1,3 @@
 
5125
-
 
5126
 :mod:`glob` --- Unix style pathname pattern expansion
 
5127
 =====================================================
 
5128
 
 
5129
@@ -8,6 +7,10 @@
 
5130
 
 
5131
 .. index:: single: filenames; pathname expansion
 
5132
 
 
5133
+**Source code:** :source:`Lib/glob.py`
 
5134
+
 
5135
+--------------
 
5136
+
 
5137
 The :mod:`glob` module finds all the pathnames matching a specified pattern
 
5138
 according to the rules used by the Unix shell.  No tilde expansion is done, but
 
5139
 ``*``, ``?``, and character ranges expressed with ``[]`` will be correctly
 
5140
@@ -16,10 +19,6 @@
 
5141
 subshell.  (For tilde and shell variable expansion, use
 
5142
 :func:`os.path.expanduser` and :func:`os.path.expandvars`.)
 
5143
 
 
5144
-.. seealso::
 
5145
-
 
5146
-   Latest version of the `glob module Python source code
 
5147
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/glob.py?view=markup>`_
 
5148
 
 
5149
 .. function:: glob(pathname)
 
5150
 
1954
5151
diff -r 8527427914a2 Doc/library/gzip.rst
1955
5152
--- a/Doc/library/gzip.rst
1956
5153
+++ b/Doc/library/gzip.rst
1957
 
@@ -58,7 +58,7 @@
 
5154
@@ -4,6 +4,10 @@
 
5155
 .. module:: gzip
 
5156
    :synopsis: Interfaces for gzip compression and decompression using file objects.
 
5157
 
 
5158
+**Source code:** :source:`Lib/gzip.py`
 
5159
+
 
5160
+--------------
 
5161
+
 
5162
 This module provides a simple interface to compress and decompress files just
 
5163
 like the GNU programs :program:`gzip` and :program:`gunzip` would.
 
5164
 
 
5165
@@ -58,7 +62,7 @@
1958
5166
    time is used.  This module ignores the timestamp when decompressing;
1959
5167
    however, some programs, such as :program:`gunzip`\ , make use of it.
1960
5168
    The format of the timestamp is the same as that of the return value of
1963
5171
    by ``os.stat()``.
1964
5172
 
1965
5173
    Calling a :class:`GzipFile` object's :meth:`close` method does not close
 
5174
diff -r 8527427914a2 Doc/library/hashlib.rst
 
5175
--- a/Doc/library/hashlib.rst
 
5176
+++ b/Doc/library/hashlib.rst
 
5177
@@ -1,4 +1,3 @@
 
5178
-
 
5179
 :mod:`hashlib` --- Secure hashes and message digests
 
5180
 ====================================================
 
5181
 
 
5182
@@ -14,6 +13,10 @@
 
5183
    single: message digest, MD5
 
5184
    single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512
 
5185
 
 
5186
+**Source code:** :source:`Lib/hashlib.py`
 
5187
+
 
5188
+--------------
 
5189
+
 
5190
 This module implements a common interface to many different secure hash and
 
5191
 message digest algorithms.  Included are the FIPS secure hash algorithms SHA1,
 
5192
 SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5
1966
5193
diff -r 8527427914a2 Doc/library/heapq.rst
1967
5194
--- a/Doc/library/heapq.rst
1968
5195
+++ b/Doc/library/heapq.rst
1969
 
@@ -16,7 +16,7 @@
1970
 
 .. seealso::
1971
 
 
1972
 
    Latest version of the `heapq Python source code
 
5196
@@ -10,14 +10,13 @@
 
5197
 
 
5198
 .. versionadded:: 2.3
 
5199
 
 
5200
+**Source code:** :source:`Lib/heapq.py`
 
5201
+
 
5202
+--------------
 
5203
+
 
5204
 This module provides an implementation of the heap queue algorithm, also known
 
5205
 as the priority queue algorithm.
 
5206
 
 
5207
-.. seealso::
 
5208
-
 
5209
-   Latest version of the `heapq Python source code
1973
5210
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/heapq.py?view=markup>`_
1974
 
+   <http://svn.python.org/view/*checkout*/python/branches/release27-maint/Lib/heapq.py?content-type=text%2Fplain>`_
1975
 
 
 
5211
-
1976
5212
 Heaps are binary trees for which every parent node has a value less than or
1977
5213
 equal to any of its children.  This implementation uses arrays for which
 
5214
 ``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting
 
5215
@@ -188,36 +187,36 @@
 
5216
 with a dictionary pointing to an entry in the queue.
 
5217
 
 
5218
 Removing the entry or changing its priority is more difficult because it would
 
5219
-break the heap structure invariants.  So, a possible solution is to mark an
 
5220
-entry as invalid and optionally add a new entry with the revised priority::
 
5221
+break the heap structure invariants.  So, a possible solution is to mark the
 
5222
+existing entry as removed and add a new entry with the revised priority::
 
5223
 
 
5224
-    pq = []                         # the priority queue list
 
5225
-    counter = itertools.count(1)    # unique sequence count
 
5226
-    task_finder = {}                # mapping of tasks to entries
 
5227
-    INVALID = 0                     # mark an entry as deleted
 
5228
+    pq = []                         # list of entries arranged in a heap
 
5229
+    entry_finder = {}               # mapping of tasks to entries
 
5230
+    REMOVED = '<removed-task>'      # placeholder for a removed task
 
5231
+    counter = itertools.count()     # unique sequence count
 
5232
 
 
5233
-    def add_task(priority, task, count=None):
 
5234
-        if count is None:
 
5235
-            count = next(counter)
 
5236
+    def add_task(task, priority=0):
 
5237
+        'Add a new task or update the priority of an existing task'
 
5238
+        if task in entry_finder:
 
5239
+            remove_task(task)
 
5240
+        count = next(counter)
 
5241
         entry = [priority, count, task]
 
5242
-        task_finder[task] = entry
 
5243
+        entry_finder[task] = entry
 
5244
         heappush(pq, entry)
 
5245
 
 
5246
-    def get_top_priority():
 
5247
-        while True:
 
5248
+    def remove_task(task):
 
5249
+        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
 
5250
+        entry = entry_finder.pop(task)
 
5251
+        entry[-1] = REMOVED
 
5252
+
 
5253
+    def pop_task():
 
5254
+        'Remove and return the lowest priority task. Raise KeyError if empty.'
 
5255
+        while pq:
 
5256
             priority, count, task = heappop(pq)
 
5257
-            del task_finder[task]
 
5258
-            if count is not INVALID:
 
5259
+            if task is not REMOVED:
 
5260
+                del entry_finder[task]
 
5261
                 return task
 
5262
-
 
5263
-    def delete_task(task):
 
5264
-        entry = task_finder[task]
 
5265
-        entry[1] = INVALID
 
5266
-
 
5267
-    def reprioritize(priority, task):
 
5268
-        entry = task_finder[task]
 
5269
-        add_task(priority, task, entry[1])
 
5270
-        entry[1] = INVALID
 
5271
+        raise KeyError('pop from an empty priority queue')
 
5272
 
 
5273
 
 
5274
 Theory
 
5275
diff -r 8527427914a2 Doc/library/hmac.rst
 
5276
--- a/Doc/library/hmac.rst
 
5277
+++ b/Doc/library/hmac.rst
 
5278
@@ -1,4 +1,3 @@
 
5279
-
 
5280
 :mod:`hmac` --- Keyed-Hashing for Message Authentication
 
5281
 ========================================================
 
5282
 
 
5283
@@ -10,6 +9,10 @@
 
5284
 
 
5285
 .. versionadded:: 2.2
 
5286
 
 
5287
+**Source code:** :source:`Lib/hmac.py`
 
5288
+
 
5289
+--------------
 
5290
+
 
5291
 This module implements the HMAC algorithm as described by :rfc:`2104`.
 
5292
 
 
5293
 
1978
5294
diff -r 8527427914a2 Doc/library/htmllib.rst
1979
5295
--- a/Doc/library/htmllib.rst
1980
5296
+++ b/Doc/library/htmllib.rst
1981
 
@@ -168,7 +168,7 @@
 
5297
@@ -165,10 +165,13 @@
 
5298
    Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
 
5299
    converting your sources to 3.0.
 
5300
 
 
5301
+**Source code:** :source:`Lib/htmlentitydefs.py`
 
5302
+
 
5303
+--------------
1982
5304
 
1983
5305
 This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``,
1984
5306
 and ``entitydefs``. ``entitydefs`` is used by the :mod:`htmllib` module to
1987
5309
 definition provided here contains all the entities defined by XHTML 1.0  that
1988
5310
 can be handled using simple textual substitution in the Latin-1 character set
1989
5311
 (ISO-8859-1).
 
5312
diff -r 8527427914a2 Doc/library/htmlparser.rst
 
5313
--- a/Doc/library/htmlparser.rst
 
5314
+++ b/Doc/library/htmlparser.rst
 
5315
@@ -8,8 +8,8 @@
 
5316
 .. note::
 
5317
 
 
5318
    The :mod:`HTMLParser` module has been renamed to :mod:`html.parser` in Python
 
5319
-   3.0.  The :term:`2to3` tool will automatically adapt imports when converting
 
5320
-   your sources to 3.0.
 
5321
+   3.  The :term:`2to3` tool will automatically adapt imports when converting
 
5322
+   your sources to Python 3.
 
5323
 
 
5324
 
 
5325
 .. versionadded:: 2.2
 
5326
@@ -18,6 +18,10 @@
 
5327
    single: HTML
 
5328
    single: XHTML
 
5329
 
 
5330
+**Source code:** :source:`Lib/HTMLParser.py`
 
5331
+
 
5332
+--------------
 
5333
+
 
5334
 This module defines a class :class:`HTMLParser` which serves as the basis for
 
5335
 parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
 
5336
 Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser
 
5337
@@ -105,9 +109,9 @@
 
5338
 .. method:: HTMLParser.handle_startendtag(tag, attrs)
 
5339
 
 
5340
    Similar to :meth:`handle_starttag`, but called when the parser encounters an
 
5341
-   XHTML-style empty tag (``<a .../>``).  This method may be overridden by
 
5342
+   XHTML-style empty tag (``<img ... />``).  This method may be overridden by
 
5343
    subclasses which require this particular lexical information; the default
 
5344
-   implementation simple calls :meth:`handle_starttag` and :meth:`handle_endtag`.
 
5345
+   implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`.
 
5346
 
 
5347
 
 
5348
 .. method:: HTMLParser.handle_endtag(tag)
 
5349
@@ -119,7 +123,8 @@
 
5350
 
 
5351
 .. method:: HTMLParser.handle_data(data)
 
5352
 
 
5353
-   This method is called to process arbitrary data.  It is intended to be
 
5354
+   This method is called to process arbitrary data (e.g. the content of
 
5355
+   ``<script>...</script>`` and ``<style>...</style>``).  It is intended to be
 
5356
    overridden by a derived class; the base class implementation does nothing.
 
5357
 
 
5358
 
 
5359
@@ -182,16 +187,21 @@
 
5360
 Example HTML Parser Application
 
5361
 -------------------------------
 
5362
 
 
5363
-As a basic example, below is a very basic HTML parser that uses the
 
5364
-:class:`HTMLParser` class to print out tags as they are encountered::
 
5365
+As a basic example, below is a simple HTML parser that uses the
 
5366
+:class:`HTMLParser` class to print out start tags, end tags and data
 
5367
+as they are encountered::
 
5368
 
 
5369
    from HTMLParser import HTMLParser
 
5370
 
 
5371
    class MyHTMLParser(HTMLParser):
 
5372
+       def handle_starttag(self, tag, attrs):
 
5373
+           print "Encountered a start tag:", tag
 
5374
+       def handle_endtag(self, tag):
 
5375
+           print "Encountered  an end tag:", tag
 
5376
+       def handle_data(self, data):
 
5377
+           print "Encountered   some data:", data
 
5378
 
 
5379
-       def handle_starttag(self, tag, attrs):
 
5380
-           print "Encountered the beginning of a %s tag" % tag
 
5381
 
 
5382
-       def handle_endtag(self, tag):
 
5383
-           print "Encountered the end of a %s tag" % tag
 
5384
-
 
5385
+   parser = MyHTMLParser()
 
5386
+   parser.feed('<html><head><title>Test</title></head>'
 
5387
+               '<body><h1>Parse me!</h1></body></html>')
1990
5388
diff -r 8527427914a2 Doc/library/httplib.rst
1991
5389
--- a/Doc/library/httplib.rst
1992
5390
+++ b/Doc/library/httplib.rst
1993
 
@@ -588,14 +588,16 @@
 
5391
@@ -16,6 +16,10 @@
 
5392
 
 
5393
 .. index:: module: urllib
 
5394
 
 
5395
+**Source code:** :source:`Lib/httplib.py`
 
5396
+
 
5397
+--------------
 
5398
+
 
5399
 This module defines classes which implement the client side of the HTTP and
 
5400
 HTTPS protocols.  It is normally not used directly --- the module :mod:`urllib`
 
5401
 uses it to handle URLs that use HTTP and HTTPS.
 
5402
@@ -448,7 +452,7 @@
 
5403
    Set the host and the port for HTTP Connect Tunnelling. Normally used when
 
5404
    it is required to do HTTPS Conection through a proxy server.
 
5405
 
 
5406
-   The headers argument should be a mapping of extra HTTP headers to to sent
 
5407
+   The headers argument should be a mapping of extra HTTP headers to sent
 
5408
    with the CONNECT request.
 
5409
 
 
5410
    .. versionadded:: 2.7
 
5411
@@ -488,9 +492,16 @@
 
5412
    an argument.
 
5413
 
 
5414
 
 
5415
-.. method:: HTTPConnection.endheaders()
 
5416
+.. method:: HTTPConnection.endheaders(message_body=None)
 
5417
 
 
5418
-   Send a blank line to the server, signalling the end of the headers.
 
5419
+   Send a blank line to the server, signalling the end of the headers. The
 
5420
+   optional *message_body* argument can be used to pass a message body
 
5421
+   associated with the request.  The message body will be sent in the same
 
5422
+   packet as the message headers if it is string, otherwise it is sent in a
 
5423
+   separate packet.
 
5424
+
 
5425
+   .. versionchanged:: 2.7
 
5426
+      *message_body* was added.
 
5427
 
 
5428
 
 
5429
 .. method:: HTTPConnection.send(data)
 
5430
@@ -588,14 +599,16 @@
1994
5431
 Here is an example session that shows how to ``POST`` requests::
1995
5432
 
1996
5433
    >>> import httplib, urllib
2011
5448
+   'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
2012
5449
    >>> conn.close()
2013
5450
 
 
5451
diff -r 8527427914a2 Doc/library/imaplib.rst
 
5452
--- a/Doc/library/imaplib.rst
 
5453
+++ b/Doc/library/imaplib.rst
 
5454
@@ -16,6 +16,10 @@
 
5455
    pair: IMAP4_SSL; protocol
 
5456
    pair: IMAP4_stream; protocol
 
5457
 
 
5458
+**Source code:** :source:`Lib/imaplib.py`
 
5459
+
 
5460
+--------------
 
5461
+
 
5462
 This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
 
5463
 :class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
 
5464
 implement a large subset of the IMAP4rev1 client protocol as defined in
 
5465
diff -r 8527427914a2 Doc/library/imghdr.rst
 
5466
--- a/Doc/library/imghdr.rst
 
5467
+++ b/Doc/library/imghdr.rst
 
5468
@@ -1,10 +1,12 @@
 
5469
-
 
5470
 :mod:`imghdr` --- Determine the type of an image
 
5471
 ================================================
 
5472
 
 
5473
 .. module:: imghdr
 
5474
    :synopsis: Determine the type of image contained in a file or byte stream.
 
5475
 
 
5476
+**Source code:** :source:`Lib/imghdr.py`
 
5477
+
 
5478
+--------------
 
5479
 
 
5480
 The :mod:`imghdr` module determines the type of image contained in a file or
 
5481
 byte stream.
 
5482
diff -r 8527427914a2 Doc/library/inspect.rst
 
5483
--- a/Doc/library/inspect.rst
 
5484
+++ b/Doc/library/inspect.rst
 
5485
@@ -1,4 +1,3 @@
 
5486
-
 
5487
 :mod:`inspect` --- Inspect live objects
 
5488
 =======================================
 
5489
 
 
5490
@@ -10,6 +9,10 @@
 
5491
 
 
5492
 .. versionadded:: 2.1
 
5493
 
 
5494
+**Source code:** :source:`Lib/inspect.py`
 
5495
+
 
5496
+--------------
 
5497
+
 
5498
 The :mod:`inspect` module provides several useful functions to help get
 
5499
 information about live objects such as modules, classes, methods, functions,
 
5500
 tracebacks, frame objects, and code objects.  For example, it can help you
2014
5501
diff -r 8527427914a2 Doc/library/io.rst
2015
5502
--- a/Doc/library/io.rst
2016
5503
+++ b/Doc/library/io.rst
2025
5512
 
2026
5513
    .. attribute:: raw
2027
5514
 
 
5515
@@ -604,25 +604,6 @@
 
5516
       if the buffer needs to be written out but the raw stream blocks.
 
5517
 
 
5518
 
 
5519
-.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
 
5520
-
 
5521
-   A buffered I/O object giving a combined, higher-level access to two
 
5522
-   sequential :class:`RawIOBase` objects: one readable, the other writeable.
 
5523
-   It is useful for pairs of unidirectional communication channels
 
5524
-   (pipes, for instance).  It inherits :class:`BufferedIOBase`.
 
5525
-
 
5526
-   *reader* and *writer* are :class:`RawIOBase` objects that are readable and
 
5527
-   writeable respectively.  If the *buffer_size* is omitted it defaults to
 
5528
-   :data:`DEFAULT_BUFFER_SIZE`.
 
5529
-
 
5530
-   A fourth argument, *max_buffer_size*, is supported, but unused and
 
5531
-   deprecated.
 
5532
-
 
5533
-   :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
 
5534
-   except for :meth:`~BufferedIOBase.detach`, which raises
 
5535
-   :exc:`UnsupportedOperation`.
 
5536
-
 
5537
-
 
5538
 .. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)
 
5539
 
 
5540
    A buffered interface to random access streams.  It inherits
 
5541
@@ -639,6 +620,29 @@
 
5542
    :class:`BufferedWriter` can do.
 
5543
 
 
5544
 
 
5545
+.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)
 
5546
+
 
5547
+   A buffered I/O object combining two unidirectional :class:`RawIOBase`
 
5548
+   objects -- one readable, the other writeable -- into a single bidirectional
 
5549
+   endpoint.  It inherits :class:`BufferedIOBase`.
 
5550
+
 
5551
+   *reader* and *writer* are :class:`RawIOBase` objects that are readable and
 
5552
+   writeable respectively.  If the *buffer_size* is omitted it defaults to
 
5553
+   :data:`DEFAULT_BUFFER_SIZE`.
 
5554
+
 
5555
+   A fourth argument, *max_buffer_size*, is supported, but unused and
 
5556
+   deprecated.
 
5557
+
 
5558
+   :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
 
5559
+   except for :meth:`~BufferedIOBase.detach`, which raises
 
5560
+   :exc:`UnsupportedOperation`.
 
5561
+
 
5562
+   .. warning::
 
5563
+      :class:`BufferedRWPair` does not attempt to synchronize accesses to
 
5564
+      its underlying raw streams.  You should not pass it the same object
 
5565
+      as reader and writer; use :class:`BufferedRandom` instead.
 
5566
+
 
5567
+
 
5568
 Text I/O
 
5569
 --------
 
5570
 
 
5571
diff -r 8527427914a2 Doc/library/itertools.rst
 
5572
--- a/Doc/library/itertools.rst
 
5573
+++ b/Doc/library/itertools.rst
 
5574
@@ -433,9 +433,9 @@
 
5575
 
 
5576
       def izip(*iterables):
 
5577
           # izip('ABCD', 'xy') --> Ax By
 
5578
-          iterables = map(iter, iterables)
 
5579
-          while iterables:
 
5580
-              yield tuple(map(next, iterables))
 
5581
+          iterators = map(iter, iterables)
 
5582
+          while iterators:
 
5583
+              yield tuple(map(next, iterators))
 
5584
 
 
5585
    .. versionchanged:: 2.4
 
5586
       When no iterables are specified, returns a zero length iterator instead of
 
5587
@@ -456,17 +456,24 @@
 
5588
    iterables are of uneven length, missing values are filled-in with *fillvalue*.
 
5589
    Iteration continues until the longest iterable is exhausted.  Equivalent to::
 
5590
 
 
5591
+      class ZipExhausted(Exception):
 
5592
+          pass
 
5593
+
 
5594
       def izip_longest(*args, **kwds):
 
5595
           # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
 
5596
           fillvalue = kwds.get('fillvalue')
 
5597
-          def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
 
5598
-              yield counter()         # yields the fillvalue, or raises IndexError
 
5599
+          counter = [len(args) - 1]
 
5600
+          def sentinel():
 
5601
+              if not counter[0]:
 
5602
+                  raise ZipExhausted
 
5603
+              counter[0] -= 1
 
5604
+              yield fillvalue
 
5605
           fillers = repeat(fillvalue)
 
5606
-          iters = [chain(it, sentinel(), fillers) for it in args]
 
5607
+          iterators = [chain(it, sentinel(), fillers) for it in args]
 
5608
           try:
 
5609
-              for tup in izip(*iters):
 
5610
-                  yield tup
 
5611
-          except IndexError:
 
5612
+              while iterators:
 
5613
+                  yield tuple(map(next, iterators))
 
5614
+          except ZipExhausted:
 
5615
               pass
 
5616
 
 
5617
    If one of the iterables is potentially infinite, then the
 
5618
diff -r 8527427914a2 Doc/library/keyword.rst
 
5619
--- a/Doc/library/keyword.rst
 
5620
+++ b/Doc/library/keyword.rst
 
5621
@@ -1,10 +1,12 @@
 
5622
-
 
5623
 :mod:`keyword` --- Testing for Python keywords
 
5624
 ==============================================
 
5625
 
 
5626
 .. module:: keyword
 
5627
    :synopsis: Test whether a string is a keyword in Python.
 
5628
 
 
5629
+**Source code:** :source:`Lib/keyword.py`
 
5630
+
 
5631
+--------------
 
5632
 
 
5633
 This module allows a Python program to determine if a string is a keyword.
 
5634
 
 
5635
@@ -19,9 +21,3 @@
 
5636
    Sequence containing all the keywords defined for the interpreter.  If any
 
5637
    keywords are defined to only be active when particular :mod:`__future__`
 
5638
    statements are in effect, these will be included as well.
 
5639
-
 
5640
-
 
5641
-.. seealso::
 
5642
-
 
5643
-   Latest version of the `keyword module Python source code
 
5644
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/keyword.py?view=markup>`_
 
5645
diff -r 8527427914a2 Doc/library/linecache.rst
 
5646
--- a/Doc/library/linecache.rst
 
5647
+++ b/Doc/library/linecache.rst
 
5648
@@ -6,17 +6,15 @@
 
5649
    :synopsis: This module provides random access to individual lines from text files.
 
5650
 .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
 
5651
 
 
5652
+**Source code:** :source:`Lib/linecache.py`
 
5653
+
 
5654
+--------------
 
5655
 
 
5656
 The :mod:`linecache` module allows one to get any line from any file, while
 
5657
 attempting to optimize internally, using a cache, the common case where many
 
5658
 lines are read from a single file.  This is used by the :mod:`traceback` module
 
5659
 to retrieve source lines for inclusion in  the formatted traceback.
 
5660
 
 
5661
-.. seealso::
 
5662
-
 
5663
-   Latest version of the `linecache module Python source code
 
5664
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/linecache.py?view=markup>`_
 
5665
-
 
5666
 The :mod:`linecache` module defines the following functions:
 
5667
 
 
5668
 
 
5669
diff -r 8527427914a2 Doc/library/locale.rst
 
5670
--- a/Doc/library/locale.rst
 
5671
+++ b/Doc/library/locale.rst
 
5672
@@ -23,19 +23,19 @@
 
5673
 
 
5674
 .. exception:: Error
 
5675
 
 
5676
-   Exception raised when :func:`setlocale` fails.
 
5677
+   Exception raised when the locale passed to :func:`setlocale` is not
 
5678
+   recognized.
 
5679
 
 
5680
 
 
5681
 .. function:: setlocale(category[, locale])
 
5682
 
 
5683
-   If *locale* is specified, it may be a string, a tuple of the form ``(language
 
5684
-   code, encoding)``, or ``None``. If it is a tuple, it is converted to a string
 
5685
-   using the locale aliasing engine.  If *locale* is given and not ``None``,
 
5686
-   :func:`setlocale` modifies the locale setting for the *category*.  The available
 
5687
-   categories are listed in the data description below.  The value is the name of a
 
5688
-   locale.  An empty string specifies the user's default settings. If the
 
5689
-   modification of the locale fails, the exception :exc:`Error` is raised.  If
 
5690
-   successful, the new locale setting is returned.
 
5691
+   If *locale* is given and not ``None``, :func:`setlocale` modifies the locale
 
5692
+   setting for the *category*. The available categories are listed in the data
 
5693
+   description below. *locale* may be a string, or an iterable of two strings
 
5694
+   (language code and encoding). If it's an iterable, it's converted to a locale
 
5695
+   name using the locale aliasing engine. An empty string specifies the user's
 
5696
+   default settings. If the modification of the locale fails, the exception
 
5697
+   :exc:`Error` is raised. If successful, the new locale setting is returned.
 
5698
 
 
5699
    If *locale* is omitted or ``None``, the current setting for *category* is
 
5700
    returned.
 
5701
@@ -51,7 +51,7 @@
 
5702
    changed thereafter, using multithreading should not cause problems.
 
5703
 
 
5704
    .. versionchanged:: 2.0
 
5705
-      Added support for tuple values of the *locale* parameter.
 
5706
+      Added support for iterable values of the *locale* parameter.
 
5707
 
 
5708
 
 
5709
 .. function:: localeconv()
2028
5710
diff -r 8527427914a2 Doc/library/logging.config.rst
2029
5711
--- a/Doc/library/logging.config.rst
2030
5712
+++ b/Doc/library/logging.config.rst
2063
5745
diff -r 8527427914a2 Doc/library/logging.handlers.rst
2064
5746
--- a/Doc/library/logging.handlers.rst
2065
5747
+++ b/Doc/library/logging.handlers.rst
2066
 
@@ -613,8 +613,14 @@
 
5748
@@ -262,10 +262,7 @@
 
5749
    :meth:`emit`.
 
5750
 
 
5751
    .. versionchanged:: 2.6
 
5752
-      *delay* was added.
 
5753
-
 
5754
-   .. versionchanged:: 2.7
 
5755
-      *utc* was added.
 
5756
+      *delay* and *utc* were added.
 
5757
 
 
5758
 
 
5759
    .. method:: doRollover()
 
5760
@@ -613,8 +610,14 @@
2067
5761
    port, use the (host, port) tuple format for the *mailhost* argument. If you
2068
5762
    use a string, the standard SMTP port is used. If your SMTP server requires
2069
5763
    authentication, you can specify a (username, password) tuple for the
2083
5777
diff -r 8527427914a2 Doc/library/logging.rst
2084
5778
--- a/Doc/library/logging.rst
2085
5779
+++ b/Doc/library/logging.rst
2086
 
@@ -416,6 +416,13 @@
 
5780
@@ -59,9 +59,15 @@
 
5781
 
 
5782
 .. attribute:: Logger.propagate
 
5783
 
 
5784
-   If this evaluates to false, logging messages are not passed by this logger or by
 
5785
-   its child loggers to the handlers of higher level (ancestor) loggers. The
 
5786
-   constructor sets this attribute to 1.
 
5787
+   If this evaluates to true, logging messages are passed by this logger and by
 
5788
+   its child loggers to the handlers of higher level (ancestor) loggers.
 
5789
+   Messages are passed directly to the ancestor loggers' handlers - neither the
 
5790
+   level nor filters of the ancestor loggers in question are considered.
 
5791
+
 
5792
+   If this evaluates to false, logging messages are not passed to the handlers
 
5793
+   of ancestor loggers.
 
5794
+
 
5795
+   The constructor sets this attribute to 1.
 
5796
 
 
5797
 
 
5798
 .. method:: Logger.setLevel(lvl)
 
5799
@@ -416,6 +422,13 @@
2087
5800
       record. Otherwise, the ISO8601 format is used.  The resulting string is
2088
5801
       returned.
2089
5802
 
2097
5810
 
2098
5811
    .. method:: formatException(exc_info)
2099
5812
 
2100
 
@@ -491,6 +498,9 @@
 
5813
@@ -491,6 +504,9 @@
2101
5814
    :param name:  The name of the logger used to log the event represented by
2102
5815
                  this LogRecord.
2103
5816
    :param level: The numeric level of the logging event (one of DEBUG, INFO etc.)
2107
5820
    :param pathname: The full pathname of the source file where the logging call
2108
5821
                     was made.
2109
5822
    :param lineno: The line number in the source file where the logging call was
 
5823
diff -r 8527427914a2 Doc/library/mailbox.rst
 
5824
--- a/Doc/library/mailbox.rst
 
5825
+++ b/Doc/library/mailbox.rst
 
5826
@@ -765,7 +765,7 @@
 
5827
    There is no requirement that :class:`Message` instances be used to represent
 
5828
    messages retrieved using :class:`Mailbox` instances. In some situations, the
 
5829
    time and memory required to generate :class:`Message` representations might
 
5830
-   not not acceptable. For such situations, :class:`Mailbox` instances also
 
5831
+   not be acceptable. For such situations, :class:`Mailbox` instances also
 
5832
    offer string and file-like representations, and a custom message factory may
 
5833
    be specified when a :class:`Mailbox` instance is initialized.
 
5834
 
 
5835
diff -r 8527427914a2 Doc/library/mailcap.rst
 
5836
--- a/Doc/library/mailcap.rst
 
5837
+++ b/Doc/library/mailcap.rst
 
5838
@@ -4,7 +4,9 @@
 
5839
 .. module:: mailcap
 
5840
    :synopsis: Mailcap file handling.
 
5841
 
 
5842
+**Source code:** :source:`Lib/mailcap.py`
 
5843
 
 
5844
+--------------
 
5845
 
 
5846
 Mailcap files are used to configure how MIME-aware applications such as mail
 
5847
 readers and Web browsers react to files with different MIME types. (The name
 
5848
diff -r 8527427914a2 Doc/library/mimetypes.rst
 
5849
--- a/Doc/library/mimetypes.rst
 
5850
+++ b/Doc/library/mimetypes.rst
 
5851
@@ -9,6 +9,10 @@
 
5852
 
 
5853
 .. index:: pair: MIME; content type
 
5854
 
 
5855
+**Source code:** :source:`Lib/mimetypes.py`
 
5856
+
 
5857
+--------------
 
5858
+
 
5859
 The :mod:`mimetypes` module converts between a filename or URL and the MIME type
 
5860
 associated with the filename extension.  Conversions are provided from filename
 
5861
 to MIME type and from MIME type to filename extension; encodings are not
2110
5862
diff -r 8527427914a2 Doc/library/mmap.rst
2111
5863
--- a/Doc/library/mmap.rst
2112
5864
+++ b/Doc/library/mmap.rst
2123
5875
 For both the Unix and Windows versions of the constructor, *access* may be
2124
5876
 specified as an optional keyword parameter. *access* accepts one of three
2125
5877
 values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
 
5878
diff -r 8527427914a2 Doc/library/modulefinder.rst
 
5879
--- a/Doc/library/modulefinder.rst
 
5880
+++ b/Doc/library/modulefinder.rst
 
5881
@@ -1,15 +1,16 @@
 
5882
-
 
5883
 :mod:`modulefinder` --- Find modules used by a script
 
5884
 =====================================================
 
5885
 
 
5886
+.. module:: modulefinder
 
5887
+   :synopsis: Find modules used by a script.
 
5888
 .. sectionauthor:: A.M. Kuchling <amk@amk.ca>
 
5889
 
 
5890
 
 
5891
-.. module:: modulefinder
 
5892
-   :synopsis: Find modules used by a script.
 
5893
+.. versionadded:: 2.3
 
5894
 
 
5895
+**Source code:** :source:`Lib/modulefinder.py`
 
5896
 
 
5897
-.. versionadded:: 2.3
 
5898
+--------------
 
5899
 
 
5900
 This module provides a :class:`ModuleFinder` class that can be used to determine
 
5901
 the set of modules imported by a script. ``modulefinder.py`` can also be run as
2126
5902
diff -r 8527427914a2 Doc/library/multiprocessing.rst
2127
5903
--- a/Doc/library/multiprocessing.rst
2128
5904
+++ b/Doc/library/multiprocessing.rst
2129
 
@@ -1602,7 +1602,7 @@
2130
 
       the process pool as separate tasks.  The (approximate) size of these
2131
 
       chunks can be specified by setting *chunksize* to a positive integer.
2132
 
 
2133
 
-   .. method:: map_async(func, iterable[, chunksize[, callback]])
2134
 
+   .. method:: map_async(func, iterable[, chunksize[, callback[, error_callback]]])
2135
 
 
2136
 
       A variant of the :meth:`.map` method which returns a result object.
2137
 
 
 
5905
@@ -552,9 +552,9 @@
 
5906
       Return ``True`` if the queue is full, ``False`` otherwise.  Because of
 
5907
       multithreading/multiprocessing semantics, this is not reliable.
 
5908
 
 
5909
-   .. method:: put(item[, block[, timeout]])
 
5910
-
 
5911
-      Put item into the queue.  If the optional argument *block* is ``True``
 
5912
+   .. method:: put(obj[, block[, timeout]])
 
5913
+
 
5914
+      Put obj into the queue.  If the optional argument *block* is ``True``
 
5915
       (the default) and *timeout* is ``None`` (the default), block if necessary until
 
5916
       a free slot is available.  If *timeout* is a positive number, it blocks at
 
5917
       most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
 
5918
@@ -563,9 +563,9 @@
 
5919
       available, else raise the :exc:`Queue.Full` exception (*timeout* is
 
5920
       ignored in that case).
 
5921
 
 
5922
-   .. method:: put_nowait(item)
 
5923
-
 
5924
-      Equivalent to ``put(item, False)``.
 
5925
+   .. method:: put_nowait(obj)
 
5926
+
 
5927
+      Equivalent to ``put(obj, False)``.
 
5928
 
 
5929
    .. method:: get([block[, timeout]])
 
5930
 
 
5931
@@ -1494,7 +1494,7 @@
 
5932
       a new shared object -- see documentation for the *method_to_typeid*
 
5933
       argument of :meth:`BaseManager.register`.
 
5934
 
 
5935
-      If an exception is raised by the call, then then is re-raised by
 
5936
+      If an exception is raised by the call, then is re-raised by
 
5937
       :meth:`_callmethod`.  If some other exception is raised in the manager's
 
5938
       process then this is converted into a :exc:`RemoteError` exception and is
 
5939
       raised by :meth:`_callmethod`.
 
5940
@@ -1617,7 +1617,7 @@
 
5941
 
 
5942
       The *chunksize* argument is the same as the one used by the :meth:`.map`
 
5943
       method.  For very long iterables using a large value for *chunksize* can
 
5944
-      make make the job complete **much** faster than using the default value of
 
5945
+      make the job complete **much** faster than using the default value of
 
5946
       ``1``.
 
5947
 
 
5948
       Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
 
5949
diff -r 8527427914a2 Doc/library/netrc.rst
 
5950
--- a/Doc/library/netrc.rst
 
5951
+++ b/Doc/library/netrc.rst
 
5952
@@ -10,6 +10,10 @@
 
5953
 
 
5954
 .. versionadded:: 1.5.2
 
5955
 
 
5956
+**Source code:** :source:`Lib/netrc.py`
 
5957
+
 
5958
+--------------
 
5959
+
 
5960
 The :class:`netrc` class parses and encapsulates the netrc file format used by
 
5961
 the Unix :program:`ftp` program and other FTP clients.
 
5962
 
 
5963
diff -r 8527427914a2 Doc/library/nntplib.rst
 
5964
--- a/Doc/library/nntplib.rst
 
5965
+++ b/Doc/library/nntplib.rst
 
5966
@@ -10,6 +10,10 @@
 
5967
    pair: NNTP; protocol
 
5968
    single: Network News Transfer Protocol
 
5969
 
 
5970
+**Source code:** :source:`Lib/nntplib.py`
 
5971
+
 
5972
+--------------
 
5973
+
 
5974
 This module defines the class :class:`NNTP` which implements the client side of
 
5975
 the NNTP protocol.  It can be used to implement a news reader or poster, or
 
5976
 automated news processors.  For more information on NNTP (Network News Transfer
2138
5977
diff -r 8527427914a2 Doc/library/numbers.rst
2139
5978
--- a/Doc/library/numbers.rst
2140
5979
+++ b/Doc/library/numbers.rst
2154
5993
diff -r 8527427914a2 Doc/library/optparse.rst
2155
5994
--- a/Doc/library/optparse.rst
2156
5995
+++ b/Doc/library/optparse.rst
2157
 
@@ -657,8 +657,9 @@
 
5996
@@ -4,17 +4,18 @@
 
5997
 .. module:: optparse
 
5998
    :synopsis: Command-line option parsing library.
 
5999
    :deprecated:
 
6000
+.. moduleauthor:: Greg Ward <gward@python.net>
 
6001
+.. sectionauthor:: Greg Ward <gward@python.net>
 
6002
+
 
6003
+.. versionadded:: 2.3
 
6004
 
 
6005
 .. deprecated:: 2.7
 
6006
    The :mod:`optparse` module is deprecated and will not be developed further;
 
6007
    development will continue with the :mod:`argparse` module.
 
6008
 
 
6009
-.. moduleauthor:: Greg Ward <gward@python.net>
 
6010
-
 
6011
-.. versionadded:: 2.3
 
6012
-
 
6013
-.. sectionauthor:: Greg Ward <gward@python.net>
 
6014
-
 
6015
+**Source code:** :source:`Lib/optparse.py`
 
6016
+
 
6017
+--------------
 
6018
 
 
6019
 :mod:`optparse` is a more convenient, flexible, and powerful library for parsing
 
6020
 command-line options than the old :mod:`getopt` module.  :mod:`optparse` uses a
 
6021
@@ -609,8 +610,8 @@
 
6022
 
 
6023
        -g                  Group option.
 
6024
 
 
6025
-A bit more complete example might invole using more than one group: still
 
6026
-extendind the previous example::
 
6027
+A bit more complete example might involve using more than one group: still
 
6028
+extending the previous example::
 
6029
 
 
6030
     group = OptionGroup(parser, "Dangerous Options",
 
6031
                         "Caution: use these options at your own risk.  "
 
6032
@@ -657,8 +658,9 @@
2158
6033
 
2159
6034
 .. method:: OptionParser.get_option_group(opt_str)
2160
6035
 
2202
6077
 
2203
6078
 .. _os-procinfo:
2204
6079
 
 
6080
@@ -929,7 +936,7 @@
 
6081
          try:
 
6082
              fp = open("myfile")
 
6083
          except IOError as e:
 
6084
-             if e.errno == errno.EACCESS:
 
6085
+             if e.errno == errno.EACCES:
 
6086
                  return "some default data"
 
6087
              # Not a permission error.
 
6088
              raise
2205
6089
@@ -1014,6 +1021,8 @@
2206
6090
    * :data:`stat.UF_APPEND`
2207
6091
    * :data:`stat.UF_OPAQUE`
2229
6113
 
2230
6114
    For backward compatibility, the return value of :func:`~os.stat` is also accessible
2231
6115
    as a tuple of at least 10 integers giving the most important (and portable)
 
6116
@@ -1588,7 +1598,7 @@
 
6117
    ineffective, because in bottom-up mode the directories in *dirnames* are
 
6118
    generated before *dirpath* itself is generated.
 
6119
 
 
6120
-   By default errors from the :func:`listdir` call are ignored.  If optional
 
6121
+   By default, errors from the :func:`listdir` call are ignored.  If optional
 
6122
    argument *onerror* is specified, it should be a function; it will be called with
 
6123
    one argument, an :exc:`OSError` instance.  It can report the error to continue
 
6124
    with the walk, or raise the exception to abort the walk.  Note that the filename
2232
6125
@@ -1663,8 +1673,9 @@
2233
6126
 
2234
6127
    Generate a :const:`SIGABRT` signal to the current process.  On Unix, the default
2264
6157
 
2265
6158
    Sounds like things are also complicated for other BSDs.  In response
2266
6159
    to my python-dev query, Thomas Wouters said:
 
6160
diff -r 8527427914a2 Doc/library/pickle.rst
 
6161
--- a/Doc/library/pickle.rst
 
6162
+++ b/Doc/library/pickle.rst
 
6163
@@ -364,7 +364,7 @@
 
6164
 
 
6165
 Note that functions (built-in and user-defined) are pickled by "fully qualified"
 
6166
 name reference, not by value.  This means that only the function name is
 
6167
-pickled, along with the name of module the function is defined in.  Neither the
 
6168
+pickled, along with the name of the module the function is defined in.  Neither the
 
6169
 function's code, nor any of its function attributes are pickled.  Thus the
 
6170
 defining module must be importable in the unpickling environment, and the module
 
6171
 must contain the named object, otherwise an exception will be raised. [#]_
 
6172
diff -r 8527427914a2 Doc/library/pickletools.rst
 
6173
--- a/Doc/library/pickletools.rst
 
6174
+++ b/Doc/library/pickletools.rst
 
6175
@@ -8,6 +8,10 @@
 
6176
 
 
6177
 .. versionadded:: 2.3
 
6178
 
 
6179
+**Source code:** :source:`Lib/pickletools.py`
 
6180
+
 
6181
+--------------
 
6182
+
 
6183
 This module contains various constants relating to the intimate details of the
 
6184
 :mod:`pickle` module, some lengthy comments about the implementation, and a few
 
6185
 useful functions for analyzing pickled data.  The contents of this module are
 
6186
diff -r 8527427914a2 Doc/library/pipes.rst
 
6187
--- a/Doc/library/pipes.rst
 
6188
+++ b/Doc/library/pipes.rst
 
6189
@@ -1,4 +1,3 @@
 
6190
-
 
6191
 :mod:`pipes` --- Interface to shell pipelines
 
6192
 =============================================
 
6193
 
 
6194
@@ -7,6 +6,9 @@
 
6195
    :synopsis: A Python interface to Unix shell pipelines.
 
6196
 .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
 
6197
 
 
6198
+**Source code:** :source:`Lib/pipes.py`
 
6199
+
 
6200
+--------------
 
6201
 
 
6202
 The :mod:`pipes` module defines a class to abstract the concept of a *pipeline*
 
6203
 --- a sequence of converters from one file to  another.
 
6204
diff -r 8527427914a2 Doc/library/pkgutil.rst
 
6205
--- a/Doc/library/pkgutil.rst
 
6206
+++ b/Doc/library/pkgutil.rst
 
6207
@@ -1,15 +1,18 @@
 
6208
-
 
6209
 :mod:`pkgutil` --- Package extension utility
 
6210
 ============================================
 
6211
 
 
6212
 .. module:: pkgutil
 
6213
    :synopsis: Utilities for the import system.
 
6214
 
 
6215
+.. versionadded:: 2.3
 
6216
+
 
6217
+**Source code:** :source:`Lib/pkgutil.py`
 
6218
+
 
6219
+--------------
 
6220
+
 
6221
 This module provides utilities for the import system, in particular package
 
6222
 support.
 
6223
 
 
6224
-.. versionadded:: 2.3
 
6225
-
 
6226
 
 
6227
 .. function:: extend_path(path, name)
 
6228
 
 
6229
@@ -187,3 +190,5 @@
 
6230
 
 
6231
    If the package cannot be located or loaded, or it uses a :pep:`302` loader
 
6232
    which does not support :func:`get_data`, then ``None`` is returned.
 
6233
+
 
6234
+   .. versionadded:: 2.6
2267
6235
diff -r 8527427914a2 Doc/library/platform.rst
2268
6236
--- a/Doc/library/platform.rst
2269
6237
+++ b/Doc/library/platform.rst
2270
 
@@ -233,9 +233,6 @@
 
6238
@@ -9,6 +9,10 @@
 
6239
 
 
6240
 .. versionadded:: 2.3
 
6241
 
 
6242
+**Source code:** :source:`Lib/platform.py`
 
6243
+
 
6244
+--------------
 
6245
+
 
6246
 .. note::
 
6247
 
 
6248
    Specific platforms listed alphabetically, with Linux included in the Unix
 
6249
@@ -233,9 +237,6 @@
2271
6250
    Entries which cannot be determined are set to ``''``.  All tuple entries are
2272
6251
    strings.
2273
6252
 
2277
6256
 
2278
6257
 Unix Platforms
2279
6258
 --------------
 
6259
diff -r 8527427914a2 Doc/library/plistlib.rst
 
6260
--- a/Doc/library/plistlib.rst
 
6261
+++ b/Doc/library/plistlib.rst
 
6262
@@ -15,6 +15,10 @@
 
6263
    pair: plist; file
 
6264
    single: property list
 
6265
 
 
6266
+**Source code:** :source:`Lib/plistlib.py`
 
6267
+
 
6268
+--------------
 
6269
+
 
6270
 This module provides an interface for reading and writing the "property list"
 
6271
 XML files used mainly by Mac OS X.
 
6272
 
 
6273
diff -r 8527427914a2 Doc/library/poplib.rst
 
6274
--- a/Doc/library/poplib.rst
 
6275
+++ b/Doc/library/poplib.rst
 
6276
@@ -1,4 +1,3 @@
 
6277
-
 
6278
 :mod:`poplib` --- POP3 protocol client
 
6279
 ======================================
 
6280
 
 
6281
@@ -9,6 +8,10 @@
 
6282
 
 
6283
 .. index:: pair: POP3; protocol
 
6284
 
 
6285
+**Source code:** :source:`Lib/poplib.py`
 
6286
+
 
6287
+--------------
 
6288
+
 
6289
 This module defines a class, :class:`POP3`, which encapsulates a connection to a
 
6290
 POP3 server and implements the protocol as defined in :rfc:`1725`.  The
 
6291
 :class:`POP3` class supports both the minimal and optional command sets.
 
6292
diff -r 8527427914a2 Doc/library/pprint.rst
 
6293
--- a/Doc/library/pprint.rst
 
6294
+++ b/Doc/library/pprint.rst
 
6295
@@ -1,4 +1,3 @@
 
6296
-
 
6297
 :mod:`pprint` --- Data pretty printer
 
6298
 =====================================
 
6299
 
 
6300
@@ -7,6 +6,9 @@
 
6301
 .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
6302
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
6303
 
 
6304
+**Source code:** :source:`Lib/pprint.py`
 
6305
+
 
6306
+--------------
 
6307
 
 
6308
 The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
 
6309
 Python data structures in a form which can be used as input to the interpreter.
 
6310
@@ -28,10 +30,6 @@
 
6311
 .. versionchanged:: 2.6
 
6312
    Added support for :class:`set` and :class:`frozenset`.
 
6313
 
 
6314
-.. seealso::
 
6315
-
 
6316
-   Latest version of the `pprint module Python source code
 
6317
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/pprint.py?view=markup>`_
 
6318
 
 
6319
 The :mod:`pprint` module defines one class:
 
6320
 
2280
6321
diff -r 8527427914a2 Doc/library/profile.rst
2281
6322
--- a/Doc/library/profile.rst
2282
6323
+++ b/Doc/library/profile.rst
2283
 
@@ -10,29 +10,6 @@
 
6324
@@ -1,4 +1,3 @@
 
6325
-
 
6326
 .. _profile:
 
6327
 
 
6328
 ********************
 
6329
@@ -10,29 +9,9 @@
2284
6330
 .. module:: profile
2285
6331
    :synopsis: Python source profiler.
2286
6332
 
2287
6333
-.. index:: single: InfoSeek Corporation
2288
 
-
 
6334
+**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py`
 
6335
 
2289
6336
-Copyright © 1994, by InfoSeek Corporation, all rights reserved.
2290
6337
-
2291
6338
-Written by James Roskind. [#]_
2307
6354
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
2308
6355
-WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
2309
6356
-OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
6357
+--------------
2310
6358
 
2311
6359
 .. _profiler-introduction:
2312
6360
 
2313
 
@@ -65,7 +42,6 @@
 
6361
@@ -65,7 +44,6 @@
2314
6362
    :mod:`cProfile`.  Adds significant overhead to profiled programs.
2315
6363
    If you're trying to extend
2316
6364
    the profiler in some way, the task might be easier with this module.
2318
6366
 
2319
6367
    .. versionchanged:: 2.4
2320
6368
       Now also reports the time spent in calls to built-in functions and methods.
 
6369
diff -r 8527427914a2 Doc/library/py_compile.rst
 
6370
--- a/Doc/library/py_compile.rst
 
6371
+++ b/Doc/library/py_compile.rst
 
6372
@@ -8,6 +8,10 @@
 
6373
 
 
6374
 .. index:: pair: file; byte-code
 
6375
 
 
6376
+**Source code:** :source:`Lib/py_compile.py`
 
6377
+
 
6378
+--------------
 
6379
+
 
6380
 The :mod:`py_compile` module provides a function to generate a byte-code file
 
6381
 from a source file, and another function used when the module source file is
 
6382
 invoked as a script.
2321
6383
diff -r 8527427914a2 Doc/library/pyclbr.rst
2322
6384
--- a/Doc/library/pyclbr.rst
2323
6385
+++ b/Doc/library/pyclbr.rst
2324
 
@@ -43,7 +43,7 @@
 
6386
@@ -1,4 +1,3 @@
 
6387
-
 
6388
 :mod:`pyclbr` --- Python class browser support
 
6389
 ==============================================
 
6390
 
 
6391
@@ -6,6 +5,9 @@
 
6392
    :synopsis: Supports information extraction for a Python class browser.
 
6393
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
6394
 
 
6395
+**Source code:** :source:`Lib/pyclbr.py`
 
6396
+
 
6397
+--------------
 
6398
 
 
6399
 The :mod:`pyclbr` module can be used to determine some limited information
 
6400
 about the classes, methods and top-level functions defined in a module.  The
 
6401
@@ -43,7 +45,7 @@
2325
6402
 
2326
6403
 The :class:`Class` objects used as values in the dictionary returned by
2327
6404
 :func:`readmodule` and :func:`readmodule_ex` provide the following data
2330
6407
 
2331
6408
 
2332
6409
 .. attribute:: Class.module
2333
 
@@ -87,7 +87,7 @@
 
6410
@@ -87,7 +89,7 @@
2334
6411
 ----------------
2335
6412
 
2336
6413
 The :class:`Function` objects used as values in the dictionary returned by
2339
6416
 
2340
6417
 
2341
6418
 .. attribute:: Function.module
 
6419
diff -r 8527427914a2 Doc/library/pydoc.rst
 
6420
--- a/Doc/library/pydoc.rst
 
6421
+++ b/Doc/library/pydoc.rst
 
6422
@@ -1,4 +1,3 @@
 
6423
-
 
6424
 :mod:`pydoc` --- Documentation generator and online help system
 
6425
 ===============================================================
 
6426
 
 
6427
@@ -15,6 +14,10 @@
 
6428
    single: documentation; online
 
6429
    single: help; online
 
6430
 
 
6431
+**Source code:** :source:`Lib/pydoc.py`
 
6432
+
 
6433
+--------------
 
6434
+
 
6435
 The :mod:`pydoc` module automatically generates documentation from Python
 
6436
 modules.  The documentation can be presented as pages of text on the console,
 
6437
 served to a Web browser, or saved to HTML files.
2342
6438
diff -r 8527427914a2 Doc/library/queue.rst
2343
6439
--- a/Doc/library/queue.rst
2344
6440
+++ b/Doc/library/queue.rst
2348
6444
 ===========================================
2349
6445
 
2350
6446
 .. module:: Queue
2351
 
@@ -26,7 +26,7 @@
2352
 
 
2353
 
 .. seealso::
2354
 
 
 
6447
@@ -9,6 +9,9 @@
 
6448
    :term:`2to3` tool will automatically adapt imports when converting your
 
6449
    sources to 3.0.
 
6450
 
 
6451
+**Source code:** :source:`Lib/Queue.py`
 
6452
+
 
6453
+--------------
 
6454
 
 
6455
 The :mod:`Queue` module implements multi-producer, multi-consumer queues.
 
6456
 It is especially useful in threaded programming when information must be
 
6457
@@ -24,11 +27,6 @@
 
6458
 the entries are kept sorted (using the :mod:`heapq` module) and the
 
6459
 lowest valued entry is retrieved first.
 
6460
 
 
6461
-.. seealso::
 
6462
-
2355
6463
-   Latest version of the `queue module Python source code
2356
 
+   Latest version of the `Queue module Python source code
2357
 
    <http://svn.python.org/view/python/branches/release27-maint/Lib/Queue.py?view=markup>`_.
2358
 
 
 
6464
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/Queue.py?view=markup>`_.
 
6465
-
2359
6466
 The :mod:`Queue` module defines the following classes and exceptions:
 
6467
 
 
6468
 .. class:: Queue(maxsize=0)
 
6469
diff -r 8527427914a2 Doc/library/quopri.rst
 
6470
--- a/Doc/library/quopri.rst
 
6471
+++ b/Doc/library/quopri.rst
 
6472
@@ -1,4 +1,3 @@
 
6473
-
 
6474
 :mod:`quopri` --- Encode and decode MIME quoted-printable data
 
6475
 ==============================================================
 
6476
 
 
6477
@@ -10,6 +9,10 @@
 
6478
    pair: quoted-printable; encoding
 
6479
    single: MIME; quoted-printable encoding
 
6480
 
 
6481
+**Source code:** :source:`Lib/quopri.py`
 
6482
+
 
6483
+--------------
 
6484
+
 
6485
 This module performs quoted-printable transport encoding and decoding, as
 
6486
 defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One:
 
6487
 Mechanisms for Specifying and Describing the Format of Internet Message Bodies".
 
6488
@@ -18,11 +21,6 @@
 
6489
 :mod:`base64` module is more compact if there are many such characters, as when
 
6490
 sending a graphics file.
 
6491
 
 
6492
-.. seealso::
 
6493
-
 
6494
-   Latest version of the `quopri module Python source code
 
6495
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/quopri.py?view=markup>`_
 
6496
-
 
6497
 .. function:: decode(input, output[,header])
 
6498
 
 
6499
    Decode the contents of the *input* file and write the resulting decoded binary
 
6500
diff -r 8527427914a2 Doc/library/random.rst
 
6501
--- a/Doc/library/random.rst
 
6502
+++ b/Doc/library/random.rst
 
6503
@@ -1,19 +1,16 @@
 
6504
-
 
6505
 :mod:`random` --- Generate pseudo-random numbers
 
6506
 ================================================
 
6507
 
 
6508
 .. module:: random
 
6509
    :synopsis: Generate pseudo-random numbers with various common distributions.
 
6510
 
 
6511
+**Source code:** :source:`Lib/random.py`
 
6512
+
 
6513
+--------------
 
6514
 
 
6515
 This module implements pseudo-random number generators for various
 
6516
 distributions.
 
6517
 
 
6518
-.. seealso::
 
6519
-
 
6520
-   Latest version of the `random module Python source code
 
6521
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/random.py?view=markup>`_
 
6522
-
 
6523
 For integers, uniform selection from a range. For sequences, uniform selection
 
6524
 of a random element, a function to generate a random permutation of a list
 
6525
 in-place, and a function for random sampling without replacement.
 
6526
@@ -199,6 +196,7 @@
 
6527
    The end-point value ``b`` may or may not be included in the range
 
6528
    depending on floating-point rounding in the equation ``a + (b-a) * random()``.
 
6529
 
 
6530
+
 
6531
 .. function:: triangular(low, high, mode)
 
6532
 
 
6533
    Return a random floating point number *N* such that ``low <= N <= high`` and
 
6534
@@ -229,6 +227,12 @@
 
6535
    Gamma distribution.  (*Not* the gamma function!)  Conditions on the
 
6536
    parameters are ``alpha > 0`` and ``beta > 0``.
 
6537
 
 
6538
+   The probability distribution function is::
 
6539
+
 
6540
+                 x ** (alpha - 1) * math.exp(-x / beta)
 
6541
+       pdf(x) =  --------------------------------------
 
6542
+                   math.gamma(alpha) * beta ** alpha
 
6543
+
 
6544
 
 
6545
 .. function:: gauss(mu, sigma)
 
6546
 
 
6547
diff -r 8527427914a2 Doc/library/re.rst
 
6548
--- a/Doc/library/re.rst
 
6549
+++ b/Doc/library/re.rst
 
6550
@@ -156,30 +156,36 @@
 
6551
    raw strings for all but the simplest expressions.
 
6552
 
 
6553
 ``[]``
 
6554
-   Used to indicate a set of characters.  Characters can be listed individually, or
 
6555
-   a range of characters can be indicated by giving two characters and separating
 
6556
-   them by a ``'-'``.  Special characters are not active inside sets.  For example,
 
6557
-   ``[akm$]`` will match any of the characters ``'a'``, ``'k'``,
 
6558
-   ``'m'``, or ``'$'``; ``[a-z]`` will match any lowercase letter, and
 
6559
-   ``[a-zA-Z0-9]`` matches any letter or digit.  Character classes such
 
6560
-   as ``\w`` or ``\S`` (defined below) are also acceptable inside a
 
6561
-   range, although the characters they match depends on whether :const:`LOCALE`
 
6562
-   or  :const:`UNICODE` mode is in force.  If you want to include a
 
6563
-   ``']'`` or a ``'-'`` inside a set, precede it with a backslash, or
 
6564
-   place it as the first character.  The pattern ``[]]`` will match
 
6565
-   ``']'``, for example.
 
6566
+   Used to indicate a set of characters.  In a set:
 
6567
 
 
6568
-   You can match the characters not within a range by :dfn:`complementing` the set.
 
6569
-   This is indicated by including a ``'^'`` as the first character of the set;
 
6570
-   ``'^'`` elsewhere will simply match the ``'^'`` character.  For example,
 
6571
-   ``[^5]`` will match any character except ``'5'``, and ``[^^]`` will match any
 
6572
-   character except ``'^'``.
 
6573
+   * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``,
 
6574
+     ``'m'``, or ``'k'``.
 
6575
 
 
6576
-   Note that inside ``[]`` the special forms and special characters lose
 
6577
-   their meanings and only the syntaxes described here are valid. For
 
6578
-   example, ``+``, ``*``, ``(``, ``)``, and so on are treated as
 
6579
-   literals inside ``[]``, and backreferences cannot be used inside
 
6580
-   ``[]``.
 
6581
+   * Ranges of characters can be indicated by giving two characters and separating
 
6582
+     them by a ``'-'``, for example ``[a-z]`` will match any lowercase ASCII letter,
 
6583
+     ``[0-5][0-9]`` will match all the two-digits numbers from ``00`` to ``59``, and
 
6584
+     ``[0-9A-Fa-f]`` will match any hexadecimal digit.  If ``-`` is escaped (e.g.
 
6585
+     ``[a\-z]``) or if it's placed as the first or last character (e.g. ``[a-]``),
 
6586
+     it will match a literal ``'-'``.
 
6587
+
 
6588
+   * Special characters lose their special meaning inside sets.  For example,
 
6589
+     ``[(+*)]`` will match any of the literal characters ``'('``, ``'+'``,
 
6590
+     ``'*'``, or ``')'``.
 
6591
+
 
6592
+   * Character classes such as ``\w`` or ``\S`` (defined below) are also accepted
 
6593
+     inside a set, although the characters they match depends on whether
 
6594
+     :const:`LOCALE` or  :const:`UNICODE` mode is in force.
 
6595
+
 
6596
+   * Characters that are not within a range can be matched by :dfn:`complementing`
 
6597
+     the set.  If the first character of the set is ``'^'``, all the characters
 
6598
+     that are *not* in the set will be matched.  For example, ``[^5]`` will match
 
6599
+     any character except ``'5'``, and ``[^^]`` will match any character except
 
6600
+     ``'^'``.  ``^`` has no special meaning if it's not the first character in
 
6601
+     the set.
 
6602
+
 
6603
+   * To match a literal ``']'`` inside a set, precede it with a backslash, or
 
6604
+     place it at the beginning of the set.  For example, both ``[()[\]{}]`` and
 
6605
+     ``[]()[{}]`` will both match a parenthesis.
 
6606
 
 
6607
 ``'|'``
 
6608
    ``A|B``, where A and B can be arbitrary REs, creates a regular expression that
 
6609
@@ -425,7 +431,7 @@
 
6610
 form.
 
6611
 
 
6612
 
 
6613
-.. function:: compile(pattern[, flags])
 
6614
+.. function:: compile(pattern, flags=0)
 
6615
 
 
6616
    Compile a regular expression pattern into a regular expression object, which
 
6617
    can be used for matching using its :func:`match` and :func:`search` methods,
 
6618
@@ -515,7 +521,7 @@
 
6619
       b = re.compile(r"\d+\.\d*")
 
6620
 
 
6621
 
 
6622
-.. function:: search(pattern, string[, flags])
 
6623
+.. function:: search(pattern, string, flags=0)
 
6624
 
 
6625
    Scan through *string* looking for a location where the regular expression
 
6626
    *pattern* produces a match, and return a corresponding :class:`MatchObject`
 
6627
@@ -524,7 +530,7 @@
 
6628
    string.
 
6629
 
 
6630
 
 
6631
-.. function:: match(pattern, string[, flags])
 
6632
+.. function:: match(pattern, string, flags=0)
 
6633
 
 
6634
    If zero or more characters at the beginning of *string* match the regular
 
6635
    expression *pattern*, return a corresponding :class:`MatchObject` instance.
 
6636
@@ -537,7 +543,7 @@
 
6637
       instead.
 
6638
 
 
6639
 
 
6640
-.. function:: split(pattern, string[, maxsplit=0, flags=0])
 
6641
+.. function:: split(pattern, string, maxsplit=0, flags=0)
 
6642
 
 
6643
    Split *string* by the occurrences of *pattern*.  If capturing parentheses are
 
6644
    used in *pattern*, then the text of all groups in the pattern are also returned
 
6645
@@ -578,7 +584,7 @@
 
6646
       Added the optional flags argument.
 
6647
 
 
6648
 
 
6649
-.. function:: findall(pattern, string[, flags])
 
6650
+.. function:: findall(pattern, string, flags=0)
 
6651
 
 
6652
    Return all non-overlapping matches of *pattern* in *string*, as a list of
 
6653
    strings.  The *string* is scanned left-to-right, and matches are returned in
 
6654
@@ -593,7 +599,7 @@
 
6655
       Added the optional flags argument.
 
6656
 
 
6657
 
 
6658
-.. function:: finditer(pattern, string[, flags])
 
6659
+.. function:: finditer(pattern, string, flags=0)
 
6660
 
 
6661
    Return an :term:`iterator` yielding :class:`MatchObject` instances over all
 
6662
    non-overlapping matches for the RE *pattern* in *string*.  The *string* is
 
6663
@@ -607,13 +613,13 @@
 
6664
       Added the optional flags argument.
 
6665
 
 
6666
 
 
6667
-.. function:: sub(pattern, repl, string[, count, flags])
 
6668
+.. function:: sub(pattern, repl, string, count=0, flags=0)
 
6669
 
 
6670
    Return the string obtained by replacing the leftmost non-overlapping occurrences
 
6671
    of *pattern* in *string* by the replacement *repl*.  If the pattern isn't found,
 
6672
    *string* is returned unchanged.  *repl* can be a string or a function; if it is
 
6673
    a string, any backslash escapes in it are processed.  That is, ``\n`` is
 
6674
-   converted to a single newline character, ``\r`` is converted to a linefeed, and
 
6675
+   converted to a single newline character, ``\r`` is converted to a carriage return, and
 
6676
    so forth.  Unknown escapes such as ``\j`` are left alone.  Backreferences, such
 
6677
    as ``\6``, are replaced with the substring matched by group 6 in the pattern.
 
6678
    For example:
 
6679
@@ -656,7 +662,7 @@
 
6680
       Added the optional flags argument.
 
6681
 
 
6682
 
 
6683
-.. function:: subn(pattern, repl, string[, count, flags])
 
6684
+.. function:: subn(pattern, repl, string, count=0, flags=0)
 
6685
 
 
6686
    Perform the same operation as :func:`sub`, but return a tuple ``(new_string,
 
6687
    number_of_subs_made)``.
 
6688
@@ -741,7 +747,7 @@
 
6689
       <_sre.SRE_Match object at ...>
 
6690
 
 
6691
 
 
6692
-   .. method:: RegexObject.split(string[, maxsplit=0])
 
6693
+   .. method:: RegexObject.split(string, maxsplit=0)
 
6694
 
 
6695
       Identical to the :func:`split` function, using the compiled pattern.
 
6696
 
 
6697
@@ -760,12 +766,12 @@
 
6698
       region like for :meth:`match`.
 
6699
 
 
6700
 
 
6701
-   .. method:: RegexObject.sub(repl, string[, count=0])
 
6702
+   .. method:: RegexObject.sub(repl, string, count=0)
 
6703
 
 
6704
       Identical to the :func:`sub` function, using the compiled pattern.
 
6705
 
 
6706
 
 
6707
-   .. method:: RegexObject.subn(repl, string[, count=0])
 
6708
+   .. method:: RegexObject.subn(repl, string, count=0)
 
6709
 
 
6710
       Identical to the :func:`subn` function, using the compiled pattern.
 
6711
 
2360
6712
diff -r 8527427914a2 Doc/library/repr.rst
2361
6713
--- a/Doc/library/repr.rst
2362
6714
+++ b/Doc/library/repr.rst
2363
 
@@ -49,7 +49,7 @@
 
6715
@@ -1,4 +1,3 @@
 
6716
-
 
6717
 :mod:`repr` --- Alternate :func:`repr` implementation
 
6718
 =====================================================
 
6719
 
 
6720
@@ -11,15 +10,14 @@
 
6721
    :term:`2to3` tool will automatically adapt imports when converting your
 
6722
    sources to 3.0.
 
6723
 
 
6724
+**Source code:** :source:`Lib/repr.py`
 
6725
+
 
6726
+--------------
 
6727
+
 
6728
 The :mod:`repr` module provides a means for producing object representations
 
6729
 with limits on the size of the resulting strings. This is used in the Python
 
6730
 debugger and may be useful in other contexts as well.
 
6731
 
 
6732
-.. seealso::
 
6733
-
 
6734
-   Latest version of the `repr module Python source code
 
6735
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/repr.py?view=markup>`_
 
6736
-
 
6737
 This module provides a class, an instance, and a function:
 
6738
 
 
6739
 
 
6740
@@ -49,7 +47,7 @@
2364
6741
 Repr Objects
2365
6742
 ------------
2366
6743
 
2369
6746
 size limits for the representations of different object types,  and methods
2370
6747
 which format specific object types.
2371
6748
 
 
6749
diff -r 8527427914a2 Doc/library/rlcompleter.rst
 
6750
--- a/Doc/library/rlcompleter.rst
 
6751
+++ b/Doc/library/rlcompleter.rst
 
6752
@@ -1,4 +1,3 @@
 
6753
-
 
6754
 :mod:`rlcompleter` --- Completion function for GNU readline
 
6755
 ===========================================================
 
6756
 
 
6757
@@ -6,6 +5,9 @@
 
6758
    :synopsis: Python identifier completion, suitable for the GNU readline library.
 
6759
 .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
 
6760
 
 
6761
+**Source code:** :source:`Lib/rlcompleter.py`
 
6762
+
 
6763
+--------------
 
6764
 
 
6765
 The :mod:`rlcompleter` module defines a completion function suitable for the
 
6766
 :mod:`readline` module by completing valid Python identifiers and keywords.
 
6767
diff -r 8527427914a2 Doc/library/runpy.rst
 
6768
--- a/Doc/library/runpy.rst
 
6769
+++ b/Doc/library/runpy.rst
 
6770
@@ -8,6 +8,10 @@
 
6771
 
 
6772
 .. versionadded:: 2.5
 
6773
 
 
6774
+**Source code:** :source:`Lib/runpy.py`
 
6775
+
 
6776
+--------------
 
6777
+
 
6778
 The :mod:`runpy` module is used to locate and run Python modules without
 
6779
 importing them first. Its main use is to implement the :option:`-m` command
 
6780
 line switch that allows scripts to be located using the Python module
 
6781
diff -r 8527427914a2 Doc/library/sched.rst
 
6782
--- a/Doc/library/sched.rst
 
6783
+++ b/Doc/library/sched.rst
 
6784
@@ -7,14 +7,13 @@
 
6785
 
 
6786
 .. index:: single: event scheduling
 
6787
 
 
6788
+**Source code:** :source:`Lib/sched.py`
 
6789
+
 
6790
+--------------
 
6791
+
 
6792
 The :mod:`sched` module defines a class which implements a general purpose event
 
6793
 scheduler:
 
6794
 
 
6795
-.. seealso::
 
6796
-
 
6797
-   Latest version of the `sched module Python source code
 
6798
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/sched.py?view=markup>`_
 
6799
-
 
6800
 .. class:: scheduler(timefunc, delayfunc)
 
6801
 
 
6802
    The :class:`scheduler` class defines a generic interface to scheduling events.
 
6803
@@ -96,7 +95,7 @@
 
6804
 
 
6805
 .. method:: scheduler.enter(delay, priority, action, argument)
 
6806
 
 
6807
-   Schedule an event for *delay* more time units. Other then the relative time, the
 
6808
+   Schedule an event for *delay* more time units. Other than the relative time, the
 
6809
    other arguments, the effect and the return value are the same as those for
 
6810
    :meth:`enterabs`.
 
6811
 
 
6812
diff -r 8527427914a2 Doc/library/shelve.rst
 
6813
--- a/Doc/library/shelve.rst
 
6814
+++ b/Doc/library/shelve.rst
 
6815
@@ -7,16 +7,16 @@
 
6816
 
 
6817
 .. index:: module: pickle
 
6818
 
 
6819
+**Source code:** :source:`Lib/shelve.py`
 
6820
+
 
6821
+--------------
 
6822
+
 
6823
 A "shelf" is a persistent, dictionary-like object.  The difference with "dbm"
 
6824
 databases is that the values (not the keys!) in a shelf can be essentially
 
6825
 arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
 
6826
 This includes most class instances, recursive data types, and objects containing
 
6827
 lots of shared  sub-objects.  The keys are ordinary strings.
 
6828
 
 
6829
-.. seealso::
 
6830
-
 
6831
-   Latest version of the `shelve module Python source code
 
6832
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/shelve.py?view=markup>`_
 
6833
 
 
6834
 .. function:: open(filename[, flag='c'[, protocol=None[, writeback=False]]])
 
6835
 
 
6836
@@ -44,17 +44,12 @@
 
6837
    determine which accessed entries are mutable, nor which ones were actually
 
6838
    mutated).
 
6839
 
 
6840
-   .. note::
 
6841
+   Like file objects, shelve objects should be closed explicitly to ensure
 
6842
+   that the persistent data is flushed to disk.
 
6843
 
 
6844
-      Do not rely on the shelf being closed automatically; always call
 
6845
-      :meth:`close` explicitly when you don't need it any more, or use a
 
6846
-      :keyword:`with` statement with :func:`contextlib.closing`.
 
6847
-
 
6848
-.. warning::
 
6849
-
 
6850
-   Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure
 
6851
-   to load a shelf from an untrusted source.  Like with pickle, loading a shelf
 
6852
-   can execute arbitrary code.
 
6853
+   Since the :mod:`shelve` module stores objects using :mod:`pickle`, the same
 
6854
+   security precautions apply.  Accordingly, you should avoid loading a shelf
 
6855
+   from an untrusted source.
 
6856
 
 
6857
 Shelf objects support all methods supported by dictionaries.  This eases the
 
6858
 transition from dictionary based scripts to those requiring persistent storage.
2372
6859
diff -r 8527427914a2 Doc/library/shlex.rst
2373
6860
--- a/Doc/library/shlex.rst
2374
6861
+++ b/Doc/library/shlex.rst
2375
 
@@ -28,8 +28,8 @@
 
6862
@@ -1,4 +1,3 @@
 
6863
-
 
6864
 :mod:`shlex` --- Simple lexical analysis
 
6865
 ========================================
 
6866
 
 
6867
@@ -12,14 +11,17 @@
 
6868
 
 
6869
 .. versionadded:: 1.5.2
 
6870
 
 
6871
+**Source code:** :source:`Lib/shlex.py`
 
6872
+
 
6873
+--------------
 
6874
+
 
6875
+
 
6876
 The :class:`shlex` class makes it easy to write lexical analyzers for simple
 
6877
 syntaxes resembling that of the Unix shell.  This will often be useful for
 
6878
 writing minilanguages, (for example, in run control files for Python
 
6879
 applications) or for parsing quoted strings.
 
6880
 
 
6881
-.. note::
 
6882
-
 
6883
-   The :mod:`shlex` module currently does not support Unicode input.
 
6884
+Prior to Python 2.7.3, this module did not support Unicode input.
 
6885
 
 
6886
 The :mod:`shlex` module defines the following functions:
 
6887
 
 
6888
@@ -28,8 +30,8 @@
2376
6889
 
2377
6890
    Split the string *s* using shell-like syntax. If *comments* is :const:`False`
2378
6891
    (the default), the parsing of comments in the given string will be disabled
2383
6896
    non-POSIX mode if the *posix* argument is false.
2384
6897
 
2385
6898
    .. versionadded:: 2.3
2386
 
@@ -53,7 +53,7 @@
 
6899
@@ -53,7 +55,7 @@
2387
6900
    :meth:`readline` methods, or a string (strings are accepted since Python 2.3).
2388
6901
    If no argument is given, input will be taken from ``sys.stdin``.  The second
2389
6902
    optional argument is a filename string, which sets the initial value of the
2392
6905
    ``sys.stdin``, this second argument defaults to "stdin".  The *posix* argument
2393
6906
    was introduced in Python 2.3, and defines the operational mode.  When *posix* is
2394
6907
    not true (default), the :class:`shlex` instance will operate in compatibility
2395
 
@@ -221,8 +221,8 @@
 
6908
@@ -221,8 +223,8 @@
2396
6909
 
2397
6910
 .. attribute:: shlex.source
2398
6911
 
2403
6916
    ``source`` keyword in various shells.  That is, the immediately following token
2404
6917
    will opened as a filename and input taken from that stream until EOF, at which
2405
6918
    point the :meth:`close` method of that stream will be called and the input
2406
 
@@ -232,7 +232,7 @@
 
6919
@@ -232,7 +234,7 @@
2407
6920
 
2408
6921
 .. attribute:: shlex.debug
2409
6922
 
2415
6928
diff -r 8527427914a2 Doc/library/shutil.rst
2416
6929
--- a/Doc/library/shutil.rst
2417
6930
+++ b/Doc/library/shutil.rst
2418
 
@@ -105,8 +105,9 @@
 
6931
@@ -1,4 +1,3 @@
 
6932
-
 
6933
 :mod:`shutil` --- High-level file operations
 
6934
 ============================================
 
6935
 
 
6936
@@ -11,16 +10,15 @@
 
6937
    single: file; copying
 
6938
    single: copying files
 
6939
 
 
6940
+**Source code:** :source:`Lib/shutil.py`
 
6941
+
 
6942
+--------------
 
6943
+
 
6944
 The :mod:`shutil` module offers a number of high-level operations on files and
 
6945
 collections of files.  In particular, functions are provided  which support file
 
6946
 copying and removal. For operations on individual files, see also the
 
6947
 :mod:`os` module.
 
6948
 
 
6949
-.. seealso::
 
6950
-
 
6951
-   Latest version of the `shutil module Python source code
 
6952
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/shutil.py?view=markup>`_
 
6953
-
 
6954
 .. warning::
 
6955
 
 
6956
    Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
 
6957
@@ -105,8 +103,9 @@
2419
6958
    :func:`copy2`.
2420
6959
 
2421
6960
    If *symlinks* is true, symbolic links in the source tree are represented as
2427
6966
 
2428
6967
    If *ignore* is given, it must be a callable that will receive as its
2429
6968
    arguments the directory being visited by :func:`copytree`, and a list of its
2430
 
@@ -161,22 +162,31 @@
 
6969
@@ -161,22 +160,31 @@
2431
6970
 
2432
6971
 .. function:: move(src, dst)
2433
6972
 
2465
7004
 .. _shutil-example:
2466
7005
 
2467
7006
 copytree example
2468
 
@@ -275,7 +285,7 @@
 
7007
@@ -270,12 +278,14 @@
 
7008
    *owner* and *group* are used when creating a tar archive. By default,
 
7009
    uses the current owner and group.
 
7010
 
 
7011
+   *logger* is an instance of :class:`logging.Logger`.
 
7012
+
 
7013
    .. versionadded:: 2.7
 
7014
 
2469
7015
 
2470
7016
 .. function:: get_archive_formats()
2471
7017
 
2483
7029
    will be used to invoke the archiver.
2484
7030
 
2485
7031
    If given, *extra_args* is a sequence of ``(name, value)`` that will be
 
7032
diff -r 8527427914a2 Doc/library/simplexmlrpcserver.rst
 
7033
--- a/Doc/library/simplexmlrpcserver.rst
 
7034
+++ b/Doc/library/simplexmlrpcserver.rst
 
7035
@@ -14,6 +14,10 @@
 
7036
 
 
7037
 .. versionadded:: 2.2
 
7038
 
 
7039
+**Source code:** :source:`Lib/SimpleXMLRPCServer.py`
 
7040
+
 
7041
+--------------
 
7042
+
 
7043
 The :mod:`SimpleXMLRPCServer` module provides a basic server framework for
 
7044
 XML-RPC servers written in Python.  Servers can either be free standing, using
 
7045
 :class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using
 
7046
diff -r 8527427914a2 Doc/library/site.rst
 
7047
--- a/Doc/library/site.rst
 
7048
+++ b/Doc/library/site.rst
 
7049
@@ -1,17 +1,22 @@
 
7050
-
 
7051
 :mod:`site` --- Site-specific configuration hook
 
7052
 ================================================
 
7053
 
 
7054
 .. module:: site
 
7055
-   :synopsis: A standard way to reference site-specific modules.
 
7056
+   :synopsis: Module responsible for site-specific configuration.
 
7057
 
 
7058
+**Source code:** :source:`Lib/site.py`
 
7059
+
 
7060
+--------------
 
7061
+
 
7062
+.. highlightlang:: none
 
7063
 
 
7064
 **This module is automatically imported during initialization.** The automatic
 
7065
 import can be suppressed using the interpreter's :option:`-S` option.
 
7066
 
 
7067
 .. index:: triple: module; search; path
 
7068
 
 
7069
-Importing this module will append site-specific paths to the module search path.
 
7070
+Importing this module will append site-specific paths to the module search path
 
7071
+and add a few builtins.
 
7072
 
 
7073
 .. index::
 
7074
    pair: site-python; directory
 
7075
@@ -26,11 +31,11 @@
 
7076
 if it refers to an existing directory, and if so, adds it to ``sys.path`` and
 
7077
 also inspects the newly added path for configuration files.
 
7078
 
 
7079
-A path configuration file is a file whose name has the form :file:`package.pth`
 
7080
+A path configuration file is a file whose name has the form :file:`{name}.pth`
 
7081
 and exists in one of the four directories mentioned above; its contents are
 
7082
 additional items (one per line) to be added to ``sys.path``.  Non-existing items
 
7083
-are never added to ``sys.path``, but no check is made that the item refers to a
 
7084
-directory (rather than a file).  No item is added to ``sys.path`` more than
 
7085
+are never added to ``sys.path``, and no check is made that the item refers to a
 
7086
+directory rather than a file.  No item is added to ``sys.path`` more than
 
7087
 once.  Blank lines and lines beginning with ``#`` are skipped.  Lines starting
 
7088
 with ``import`` (followed by space or tab) are executed.
 
7089
 
 
7090
@@ -43,8 +48,7 @@
 
7091
 
 
7092
 For example, suppose ``sys.prefix`` and ``sys.exec_prefix`` are set to
 
7093
 :file:`/usr/local`.  The Python X.Y library is then installed in
 
7094
-:file:`/usr/local/lib/python{X.Y}` (where only the first three characters of
 
7095
-``sys.version`` are used to form the installation path name).  Suppose this has
 
7096
+:file:`/usr/local/lib/python{X.Y}`.  Suppose this has
 
7097
 a subdirectory :file:`/usr/local/lib/python{X.Y}/site-packages` with three
 
7098
 subsubdirectories, :file:`foo`, :file:`bar` and :file:`spam`, and two path
 
7099
 configuration files, :file:`foo.pth` and :file:`bar.pth`.  Assume
 
7100
@@ -77,86 +81,132 @@
 
7101
 
 
7102
 After these path manipulations, an attempt is made to import a module named
 
7103
 :mod:`sitecustomize`, which can perform arbitrary site-specific customizations.
 
7104
-If this import fails with an :exc:`ImportError` exception, it is silently
 
7105
-ignored.
 
7106
+It is typically created by a system administrator in the site-packages
 
7107
+directory.  If this import fails with an :exc:`ImportError` exception, it is
 
7108
+silently ignored.
 
7109
 
 
7110
-.. index:: module: sitecustomize
 
7111
+.. index:: module: usercustomize
 
7112
+
 
7113
+After this, an attempt is made to import a module named :mod:`usercustomize`,
 
7114
+which can perform arbitrary user-specific customizations, if
 
7115
+:data:`ENABLE_USER_SITE` is true.  This file is intended to be created in the
 
7116
+user site-packages directory (see below), which is part of ``sys.path`` unless
 
7117
+disabled by :option:`-s`.  An :exc:`ImportError` will be silently ignored.
 
7118
 
 
7119
 Note that for some non-Unix systems, ``sys.prefix`` and ``sys.exec_prefix`` are
 
7120
 empty, and the path manipulations are skipped; however the import of
 
7121
-:mod:`sitecustomize` is still attempted.
 
7122
+:mod:`sitecustomize` and :mod:`usercustomize` is still attempted.
 
7123
 
 
7124
 
 
7125
 .. data:: PREFIXES
 
7126
 
 
7127
-   A list of prefixes for site package directories
 
7128
+   A list of prefixes for site-packages directories.
 
7129
 
 
7130
    .. versionadded:: 2.6
 
7131
 
 
7132
 
 
7133
 .. data:: ENABLE_USER_SITE
 
7134
 
 
7135
-   Flag showing the status of the user site directory. True means the
 
7136
-   user site directory is enabled and added to sys.path. When the flag
 
7137
-   is None the user site directory is disabled for security reasons.
 
7138
+   Flag showing the status of the user site-packages directory.  ``True`` means
 
7139
+   that it is enabled and was added to ``sys.path``.  ``False`` means that it
 
7140
+   was disabled by user request (with :option:`-s` or
 
7141
+   :envvar:`PYTHONNOUSERSITE`).  ``None`` means it was disabled for security
 
7142
+   reasons (mismatch between user or group id and effective id) or by an
 
7143
+   administrator.
 
7144
 
 
7145
    .. versionadded:: 2.6
 
7146
 
 
7147
 
 
7148
 .. data:: USER_SITE
 
7149
 
 
7150
-   Path to the user site directory for the current Python version or None
 
7151
+   Path to the user site-packages for the running Python.  Can be ``None`` if
 
7152
+   :func:`getusersitepackages` hasn't been called yet.  Default value is
 
7153
+   :file:`~/.local/lib/python{X.Y}/site-packages` for UNIX and non-framework Mac
 
7154
+   OS X builds, :file:`~/Library/Python/{X.Y}/lib/python/site-packages` for Mac
 
7155
+   framework builds, and :file:`{%APPDATA%}\\Python\\Python{XY}\\site-packages`
 
7156
+   on Windows.  This directory is a site directory, which means that
 
7157
+   :file:`.pth` files in it will be processed.
 
7158
 
 
7159
    .. versionadded:: 2.6
 
7160
 
 
7161
 
 
7162
 .. data:: USER_BASE
 
7163
 
 
7164
-   Path to the base directory for user site directories
 
7165
+   Path to the base directory for the user site-packages.  Can be ``None`` if
 
7166
+   :func:`getuserbase` hasn't been called yet.  Default value is
 
7167
+   :file:`~/.local` for UNIX and Mac OS X non-framework builds,
 
7168
+   :file:`~/Library/Python/{X.Y}` for Mac framework builds, and
 
7169
+   :file:`{%APPDATA%}\\Python` for Windows.  This value is used by Distutils to
 
7170
+   compute the installation directories for scripts, data files, Python modules,
 
7171
+   etc. for the :ref:`user installation scheme <inst-alt-install-user>`.  See
 
7172
+   also :envvar:`PYTHONUSERBASE`.
 
7173
 
 
7174
    .. versionadded:: 2.6
 
7175
 
 
7176
 
 
7177
-.. envvar:: PYTHONNOUSERSITE
 
7178
-
 
7179
-   .. versionadded:: 2.6
 
7180
-
 
7181
-
 
7182
-.. envvar:: PYTHONUSERBASE
 
7183
-
 
7184
-   .. versionadded:: 2.6
 
7185
-
 
7186
-
 
7187
 .. function:: addsitedir(sitedir, known_paths=None)
 
7188
 
 
7189
-   Adds a directory to sys.path and processes its pth files.
 
7190
+   Add a directory to sys.path and process its :file:`.pth` files.  Typically
 
7191
+   used in :mod:`sitecustomize` or :mod:`usercustomize` (see above).
 
7192
+
 
7193
 
 
7194
 .. function:: getsitepackages()
 
7195
 
 
7196
-   Returns a list containing all global site-packages directories
 
7197
-   (and possibly site-python).
 
7198
+   Return a list containing all global site-packages directories (and possibly
 
7199
+   site-python).
 
7200
 
 
7201
    .. versionadded:: 2.7
 
7202
 
 
7203
+
 
7204
 .. function:: getuserbase()
 
7205
 
 
7206
-   Returns the "user base" directory path.
 
7207
-
 
7208
-   The "user base" directory can be used to store data. If the global
 
7209
-   variable ``USER_BASE`` is not initialized yet, this function will also set
 
7210
-   it.
 
7211
+   Return the path of the user base directory, :data:`USER_BASE`.  If it is not
 
7212
+   initialized yet, this function will also set it, respecting
 
7213
+   :envvar:`PYTHONUSERBASE`.
 
7214
 
 
7215
    .. versionadded:: 2.7
 
7216
 
 
7217
+
 
7218
 .. function:: getusersitepackages()
 
7219
 
 
7220
-   Returns the user-specific site-packages directory path.
 
7221
-
 
7222
-   If the global variable ``USER_SITE`` is not initialized yet, this
 
7223
-   function will also set it.
 
7224
+   Return the path of the user-specific site-packages directory,
 
7225
+   :data:`USER_SITE`.  If it is not initialized yet, this function will also set
 
7226
+   it, respecting :envvar:`PYTHONNOUSERSITE` and :data:`USER_BASE`.
 
7227
 
 
7228
    .. versionadded:: 2.7
 
7229
 
 
7230
-.. XXX Update documentation
 
7231
-.. XXX document python -m site --user-base --user-site
 
7232
 
 
7233
+The :mod:`site` module also provides a way to get the user directories from the
 
7234
+command line:
 
7235
+
 
7236
+.. code-block:: sh
 
7237
+
 
7238
+   $ python3 -m site --user-site
 
7239
+   /home/user/.local/lib/python3.3/site-packages
 
7240
+
 
7241
+.. program:: site
 
7242
+
 
7243
+If it is called without arguments, it will print the contents of
 
7244
+:data:`sys.path` on the standard output, followed by the value of
 
7245
+:data:`USER_BASE` and whether the directory exists, then the same thing for
 
7246
+:data:`USER_SITE`, and finally the value of :data:`ENABLE_USER_SITE`.
 
7247
+
 
7248
+.. cmdoption:: --user-base
 
7249
+
 
7250
+   Print the path to the user base directory.
 
7251
+
 
7252
+.. cmdoption:: --user-site
 
7253
+
 
7254
+   Print the path to the user site-packages directory.
 
7255
+
 
7256
+If both options are given, user base and user site will be printed (always in
 
7257
+this order), separated by :data:`os.pathsep`.
 
7258
+
 
7259
+If any option is given, the script will exit with one of these values: ``O`` if
 
7260
+the user site-packages directory is enabled, ``1`` if it was disabled by the
 
7261
+user, ``2`` if it is disabled for security reasons or by an administrator, and a
 
7262
+value greater than 2 if there is an error.
 
7263
+
 
7264
+.. seealso::
 
7265
+
 
7266
+   :pep:`370` -- Per user site-packages directory
 
7267
diff -r 8527427914a2 Doc/library/smtpd.rst
 
7268
--- a/Doc/library/smtpd.rst
 
7269
+++ b/Doc/library/smtpd.rst
 
7270
@@ -7,8 +7,9 @@
 
7271
 .. moduleauthor:: Barry Warsaw <barry@zope.com>
 
7272
 .. sectionauthor:: Moshe Zadka <moshez@moshez.org>
 
7273
 
 
7274
+**Source code:** :source:`Lib/smtpd.py`
 
7275
 
 
7276
-
 
7277
+--------------
 
7278
 
 
7279
 This module offers several classes to implement SMTP servers.  One is a generic
 
7280
 do-nothing implementation, which can be overridden, while the other two offer
 
7281
diff -r 8527427914a2 Doc/library/smtplib.rst
 
7282
--- a/Doc/library/smtplib.rst
 
7283
+++ b/Doc/library/smtplib.rst
 
7284
@@ -1,4 +1,3 @@
 
7285
-
 
7286
 :mod:`smtplib` --- SMTP protocol client
 
7287
 =======================================
 
7288
 
 
7289
@@ -11,6 +10,10 @@
 
7290
    pair: SMTP; protocol
 
7291
    single: Simple Mail Transfer Protocol
 
7292
 
 
7293
+**Source code:** :source:`Lib/smtplib.py`
 
7294
+
 
7295
+--------------
 
7296
+
 
7297
 The :mod:`smtplib` module defines an SMTP client session object that can be used
 
7298
 to send mail to any Internet machine with an SMTP or ESMTP listener daemon.  For
 
7299
 details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
 
7300
diff -r 8527427914a2 Doc/library/sndhdr.rst
 
7301
--- a/Doc/library/sndhdr.rst
 
7302
+++ b/Doc/library/sndhdr.rst
 
7303
@@ -1,4 +1,3 @@
 
7304
-
 
7305
 :mod:`sndhdr` --- Determine type of sound file
 
7306
 ==============================================
 
7307
 
 
7308
@@ -11,6 +10,10 @@
 
7309
    single: A-LAW
 
7310
    single: u-LAW
 
7311
 
 
7312
+**Source code:** :source:`Lib/sndhdr.py`
 
7313
+
 
7314
+--------------
 
7315
+
 
7316
 The :mod:`sndhdr` provides utility functions which attempt to determine the type
 
7317
 of sound data which is in a file.  When these functions are able to determine
 
7318
 what type of sound data is stored in a file, they return a tuple ``(type,
2486
7319
diff -r 8527427914a2 Doc/library/socket.rst
2487
7320
--- a/Doc/library/socket.rst
2488
7321
+++ b/Doc/library/socket.rst
2513
7346
    ``None`` if no timeout is set.  This reflects the last call to
2514
7347
    :meth:`setblocking` or :meth:`settimeout`.
2515
7348
 
 
7349
@@ -989,3 +989,22 @@
 
7350
 
 
7351
    # disabled promiscuous mode
 
7352
    s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
 
7353
+
 
7354
+
 
7355
+Running an example several times with too small delay between executions, could
 
7356
+lead to this error::
 
7357
+
 
7358
+   socket.error: [Errno 98] Address already in use
 
7359
+
 
7360
+This is because the previous execution has left the socket in a ``TIME_WAIT``
 
7361
+state, and can't be immediately reused.
 
7362
+
 
7363
+There is a :mod:`socket` flag to set, in order to prevent this,
 
7364
+:data:`socket.SO_REUSEADDR`::
 
7365
+
 
7366
+   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
7367
+   s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 
7368
+   s.bind((HOST, PORT))
 
7369
+
 
7370
+the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in
 
7371
+``TIME_WAIT`` state, without waiting for its natural timeout to expire.
2516
7372
diff -r 8527427914a2 Doc/library/socketserver.rst
2517
7373
--- a/Doc/library/socketserver.rst
2518
7374
+++ b/Doc/library/socketserver.rst
2519
 
@@ -85,7 +85,7 @@
 
7375
@@ -1,4 +1,3 @@
 
7376
-
 
7377
 :mod:`SocketServer` --- A framework for network servers
 
7378
 =======================================================
 
7379
 
 
7380
@@ -11,6 +10,9 @@
 
7381
    Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
 
7382
    converting your sources to 3.0.
 
7383
 
 
7384
+**Source code:** :source:`Lib/SocketServer.py`
 
7385
+
 
7386
+--------------
 
7387
 
 
7388
 The :mod:`SocketServer` module simplifies the task of writing network servers.
 
7389
 
 
7390
@@ -85,7 +87,7 @@
2520
7391
    class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
2521
7392
 
2522
7393
 The mix-in class must come first, since it overrides a method defined in
2525
7396
 behavior of the underlying server mechanism.
2526
7397
 
2527
7398
 To implement a service, you must derive a class from :class:`BaseRequestHandler`
 
7399
@@ -223,6 +225,7 @@
 
7400
    desired.  If :meth:`handle_request` receives no incoming requests within the
 
7401
    timeout period, the :meth:`handle_timeout` method is called.
 
7402
 
 
7403
+
 
7404
 There are various server methods that can be overridden by subclasses of base
 
7405
 server classes like :class:`TCPServer`; these methods aren't useful to external
 
7406
 users of the server object.
 
7407
@@ -353,7 +356,7 @@
 
7408
        def handle(self):
 
7409
            # self.request is the TCP socket connected to the client
 
7410
            self.data = self.request.recv(1024).strip()
 
7411
-           print "%s wrote:" % self.client_address[0]
 
7412
+           print "{} wrote:".format(self.client_address[0])
 
7413
            print self.data
 
7414
            # just send back the same data, but upper-cased
 
7415
            self.request.send(self.data.upper())
 
7416
@@ -377,7 +380,7 @@
 
7417
            # self.rfile is a file-like object created by the handler;
 
7418
            # we can now use e.g. readline() instead of raw recv() calls
 
7419
            self.data = self.rfile.readline().strip()
 
7420
-           print "%s wrote:" % self.client_address[0]
 
7421
+           print "{} wrote:".format(self.client_address[0])
 
7422
            print self.data
 
7423
            # Likewise, self.wfile is a file-like object used to write back
 
7424
            # to the client
 
7425
@@ -400,16 +403,18 @@
 
7426
    # Create a socket (SOCK_STREAM means a TCP socket)
 
7427
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
7428
 
 
7429
-   # Connect to server and send data
 
7430
-   sock.connect((HOST, PORT))
 
7431
-   sock.send(data + "\n")
 
7432
+   try:
 
7433
+       # Connect to server and send data
 
7434
+       sock.connect((HOST, PORT))
 
7435
+       sock.send(data + "\n")
 
7436
 
 
7437
-   # Receive data from the server and shut down
 
7438
-   received = sock.recv(1024)
 
7439
-   sock.close()
 
7440
+       # Receive data from the server and shut down
 
7441
+       received = sock.recv(1024)
 
7442
+   finally:
 
7443
+       sock.close()
 
7444
 
 
7445
-   print "Sent:     %s" % data
 
7446
-   print "Received: %s" % received
 
7447
+   print "Sent:     {}".format(data)
 
7448
+   print "Received: {}".format(received)
 
7449
 
 
7450
 
 
7451
 The output of the example should look something like this:
 
7452
@@ -450,7 +455,7 @@
 
7453
        def handle(self):
 
7454
            data = self.request[0].strip()
 
7455
            socket = self.request[1]
 
7456
-           print "%s wrote:" % self.client_address[0]
 
7457
+           print "{} wrote:".format(self.client_address[0])
 
7458
            print data
 
7459
            socket.sendto(data.upper(), self.client_address)
 
7460
 
 
7461
@@ -475,8 +480,8 @@
 
7462
    sock.sendto(data + "\n", (HOST, PORT))
 
7463
    received = sock.recv(1024)
 
7464
 
 
7465
-   print "Sent:     %s" % data
 
7466
-   print "Received: %s" % received
 
7467
+   print "Sent:     {}".format(data)
 
7468
+   print "Received: {}".format(received)
 
7469
 
 
7470
 The output of the example should look exactly like for the TCP server example.
 
7471
 
 
7472
@@ -497,8 +502,8 @@
 
7473
 
 
7474
        def handle(self):
 
7475
            data = self.request.recv(1024)
 
7476
-           cur_thread = threading.currentThread()
 
7477
-           response = "%s: %s" % (cur_thread.getName(), data)
 
7478
+           cur_thread = threading.current_thread()
 
7479
+           response = "{}: {}".format(cur_thread.name, data)
 
7480
            self.request.send(response)
 
7481
 
 
7482
    class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
 
7483
@@ -507,10 +512,12 @@
 
7484
    def client(ip, port, message):
 
7485
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
7486
        sock.connect((ip, port))
 
7487
-       sock.send(message)
 
7488
-       response = sock.recv(1024)
 
7489
-       print "Received: %s" % response
 
7490
-       sock.close()
 
7491
+       try:
 
7492
+           sock.send(message)
 
7493
+           response = sock.recv(1024)
 
7494
+           print "Received: {}".format(response)
 
7495
+       finally:
 
7496
+           sock.close()
 
7497
 
 
7498
    if __name__ == "__main__":
 
7499
        # Port 0 means to select an arbitrary unused port
 
7500
@@ -523,9 +530,9 @@
 
7501
        # more thread for each request
 
7502
        server_thread = threading.Thread(target=server.serve_forever)
 
7503
        # Exit the server thread when the main thread terminates
 
7504
-       server_thread.setDaemon(True)
 
7505
+       server_thread.daemon = True
 
7506
        server_thread.start()
 
7507
-       print "Server loop running in thread:", server_thread.getName()
 
7508
+       print "Server loop running in thread:", server_thread.name
 
7509
 
 
7510
        client(ip, port, "Hello World 1")
 
7511
        client(ip, port, "Hello World 2")
 
7512
@@ -533,6 +540,7 @@
 
7513
 
 
7514
        server.shutdown()
 
7515
 
 
7516
+
 
7517
 The output of the example should look something like this::
 
7518
 
 
7519
    $ python ThreadedTCPServer.py
2528
7520
diff -r 8527427914a2 Doc/library/sqlite3.rst
2529
7521
--- a/Doc/library/sqlite3.rst
2530
7522
+++ b/Doc/library/sqlite3.rst
 
7523
@@ -240,7 +240,7 @@
 
7524
 .. method:: Connection.commit()
 
7525
 
 
7526
    This method commits the current transaction. If you don't call this method,
 
7527
-   anything you did since the last call to ``commit()`` is not visible from from
 
7528
+   anything you did since the last call to ``commit()`` is not visible from
 
7529
    other database connections. If you wonder why you don't see the data you've
 
7530
    written to the database, please check you didn't forget to call this method.
 
7531
 
2531
7532
@@ -378,6 +378,8 @@
2532
7533
 
2533
7534
    .. literalinclude:: ../includes/sqlite3/load_extension.py
2635
7636
+   you must modify setup.py and remove the line that sets
2636
7637
+   SQLITE_OMIT_LOAD_EXTENSION.
2637
7638
+
 
7639
diff -r 8527427914a2 Doc/library/ssl.rst
 
7640
--- a/Doc/library/ssl.rst
 
7641
+++ b/Doc/library/ssl.rst
 
7642
@@ -5,9 +5,6 @@
 
7643
    :synopsis: TLS/SSL wrapper for socket objects
 
7644
 
 
7645
 .. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
 
7646
-
 
7647
-.. versionadded:: 2.6
 
7648
-
 
7649
 .. sectionauthor::  Bill Janssen <bill.janssen@gmail.com>
 
7650
 
 
7651
 
 
7652
@@ -15,6 +12,12 @@
 
7653
 
 
7654
 .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
 
7655
 
 
7656
+.. versionadded:: 2.6
 
7657
+
 
7658
+**Source code:** :source:`Lib/ssl.py`
 
7659
+
 
7660
+--------------
 
7661
+
 
7662
 This module provides access to Transport Layer Security (often known as "Secure
 
7663
 Sockets Layer") encryption and peer authentication facilities for network
 
7664
 sockets, both client-side and server-side.  This module uses the OpenSSL
 
7665
@@ -619,8 +622,8 @@
 
7666
    Class :class:`socket.socket`
 
7667
             Documentation of underlying :mod:`socket` class
 
7668
 
 
7669
-   `Introducing SSL and Certificates using OpenSSL <http://old.pseudonym.org/ssl/wwwj-index.html>`_
 
7670
-       Frederick J. Hirsch
 
7671
+   `TLS (Transport Layer Security) and SSL (Secure Socket Layer) <http://www3.rad.com/networks/applications/secure/tls.htm>`_
 
7672
+      Debby Koren
 
7673
 
 
7674
    `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <http://www.ietf.org/rfc/rfc1422>`_
 
7675
        Steve Kent
2638
7676
diff -r 8527427914a2 Doc/library/stat.rst
2639
7677
--- a/Doc/library/stat.rst
2640
7678
+++ b/Doc/library/stat.rst
2641
 
@@ -84,7 +84,7 @@
 
7679
@@ -1,4 +1,3 @@
 
7680
-
 
7681
 :mod:`stat` --- Interpreting :func:`stat` results
 
7682
 =================================================
 
7683
 
 
7684
@@ -6,6 +5,9 @@
 
7685
    :synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
 
7686
 .. sectionauthor:: Skip Montanaro <skip@automatrix.com>
 
7687
 
 
7688
+**Source code:** :source:`Lib/stat.py`
 
7689
+
 
7690
+--------------
 
7691
 
 
7692
 The :mod:`stat` module defines constants and functions for interpreting the
 
7693
 results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they
 
7694
@@ -84,7 +86,7 @@
2642
7695
 
2643
7696
        for f in os.listdir(top):
2644
7697
            pathname = os.path.join(top, f)
2647
7700
            if S_ISDIR(mode):
2648
7701
                # It's a directory, recurse into it
2649
7702
                walktree(pathname, callback)
2650
 
@@ -306,11 +306,19 @@
 
7703
@@ -306,11 +308,19 @@
2651
7704
 
2652
7705
 .. data:: UF_OPAQUE
2653
7706
 
2739
7792
 
2740
7793
    For 8-bit strings, this method is locale-dependent.
2741
7794
 
 
7795
@@ -1307,7 +1311,7 @@
 
7796
 
 
7797
    Return ``True`` if there are only decimal characters in S, ``False``
 
7798
    otherwise. Decimal characters include digit characters, and all characters
 
7799
-   that that can be used to form decimal-radix numbers, e.g. U+0660,
 
7800
+   that can be used to form decimal-radix numbers, e.g. U+0660,
 
7801
    ARABIC-INDIC DIGIT ZERO.
 
7802
 
 
7803
 
2742
7804
@@ -1336,7 +1340,7 @@
2743
7805
 the result will also be a Unicode object.
2744
7806
 
2748
7810
 items specified by the format string, or a single mapping object (for example, a
2749
7811
 dictionary).
2750
7812
 
 
7813
@@ -2402,7 +2406,7 @@
 
7814
 .. method:: file.readline([size])
 
7815
 
 
7816
    Read one entire line from the file.  A trailing newline character is kept in
 
7817
-   the string (but may be absent when a file ends with an incomplete line). [#]_
 
7818
+   the string (but may be absent when a file ends with an incomplete line). [6]_
 
7819
    If the *size* argument is present and non-negative, it is a maximum byte
 
7820
    count (including the trailing newline) and an incomplete line may be
 
7821
    returned. When *size* is not 0, an empty string is returned *only* when EOF
2751
7822
@@ -2787,7 +2791,7 @@
2752
7823
 foo`` does not require a module object named *foo* to exist, rather it requires
2753
7824
 an (external) *definition* for a module named *foo* somewhere.)
2777
7848
 
2778
7849
 
2779
7850
 Boolean Values
2780
 
@@ -3033,15 +3048,18 @@
 
7851
@@ -3033,18 +3048,21 @@
2781
7852
 
2782
7853
 .. rubric:: Footnotes
2783
7854
 
2800
7871
+.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
2801
7872
    element is the tuple to be formatted.
2802
7873
 
2803
 
 .. [#] The advantage of leaving the newline on is that returning an empty string is
 
7874
-.. [#] The advantage of leaving the newline on is that returning an empty string is
 
7875
+.. [6] The advantage of leaving the newline on is that returning an empty string is
 
7876
    then an unambiguous EOF indication.  It is also possible (in cases where it
 
7877
    might matter, for example, if you want to make an exact copy of a file while
 
7878
    scanning its lines) to tell whether the last line of a file ended in a newline
2804
7879
diff -r 8527427914a2 Doc/library/string.rst
2805
7880
--- a/Doc/library/string.rst
2806
7881
+++ b/Doc/library/string.rst
 
7882
@@ -7,6 +7,10 @@
 
7883
 
 
7884
 .. index:: module: re
 
7885
 
 
7886
+**Source code:** :source:`Lib/string.py`
 
7887
+
 
7888
+--------------
 
7889
+
 
7890
 The :mod:`string` module contains a number of useful constants and
 
7891
 classes, as well as some deprecated legacy functions that are also
 
7892
 available as methods on strings. In addition, Python's built-in string
 
7893
@@ -17,12 +21,6 @@
 
7894
 :ref:`string-formatting` section. Also, see the :mod:`re` module for
 
7895
 string functions based on regular expressions.
 
7896
 
 
7897
-.. seealso::
 
7898
-
 
7899
-   Latest version of the `string module Python source code
 
7900
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/string.py?view=markup>`_
 
7901
-
 
7902
-
 
7903
 String constants
 
7904
 ----------------
 
7905
 
 
7906
@@ -245,11 +243,13 @@
 
7907
 
 
7908
 See also the :ref:`formatspec` section.
 
7909
 
 
7910
-The *field_name* itself begins with an *arg_name* that is either either a number or a
 
7911
+The *field_name* itself begins with an *arg_name* that is either a number or a
 
7912
 keyword.  If it's a number, it refers to a positional argument, and if it's a keyword,
 
7913
 it refers to a named keyword argument.  If the numerical arg_names in a format string
 
7914
 are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
 
7915
 and the numbers 0, 1, 2, ... will be automatically inserted in that order.
 
7916
+Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary
 
7917
+dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string.
 
7918
 The *arg_name* can be followed by any number of index or
 
7919
 attribute expressions. An expression of the form ``'.name'`` selects the named
 
7920
 attribute using :func:`getattr`, while an expression of the form ``'[index]'``
2807
7921
@@ -729,9 +729,9 @@
2808
7922
 to parse template strings.  To do this, you can override these class attributes:
2809
7923
 
2817
7931
 
2818
7932
 * *idpattern* -- This is the regular expression describing the pattern for
2819
7933
   non-braced placeholders (the braces will be added automatically as
 
7934
diff -r 8527427914a2 Doc/library/stringio.rst
 
7935
--- a/Doc/library/stringio.rst
 
7936
+++ b/Doc/library/stringio.rst
 
7937
@@ -82,10 +82,7 @@
 
7938
    those cases.
 
7939
 
 
7940
    Unlike the :mod:`StringIO` module, this module is not able to accept Unicode
 
7941
-   strings that cannot be encoded as plain ASCII strings.  Calling
 
7942
-   :func:`StringIO` with a Unicode string parameter populates the object with
 
7943
-   the buffer representation of the Unicode string instead of encoding the
 
7944
-   string.
 
7945
+   strings that cannot be encoded as plain ASCII strings.
 
7946
 
 
7947
    Another difference from the :mod:`StringIO` module is that calling
 
7948
    :func:`StringIO` with a string parameter creates a read-only object. Unlike an
2820
7949
diff -r 8527427914a2 Doc/library/struct.rst
2821
7950
--- a/Doc/library/struct.rst
2822
7951
+++ b/Doc/library/struct.rst
 
7952
@@ -22,8 +22,8 @@
 
7953
    alignment is taken into account when unpacking.  This behavior is chosen so
 
7954
    that the bytes of a packed struct correspond exactly to the layout in memory
 
7955
    of the corresponding C struct.  To handle platform-independent data formats
 
7956
-   or omit implicit pad bytes, use `standard` size and alignment instead of
 
7957
-   `native` size and alignment: see :ref:`struct-alignment` for details.
 
7958
+   or omit implicit pad bytes, use ``standard`` size and alignment instead of
 
7959
+   ``native`` size and alignment: see :ref:`struct-alignment` for details.
 
7960
 
 
7961
 Functions and Exceptions
 
7962
 ------------------------
2823
7963
@@ -257,10 +257,11 @@
2824
7964
 For the ``'s'`` format character, the count is interpreted as the size of the
2825
7965
 string, not a repeat count like for the other format characters; for example,
2839
7979
diff -r 8527427914a2 Doc/library/subprocess.rst
2840
7980
--- a/Doc/library/subprocess.rst
2841
7981
+++ b/Doc/library/subprocess.rst
2842
 
@@ -428,38 +428,39 @@
 
7982
@@ -31,7 +31,215 @@
 
7983
 Using the subprocess Module
 
7984
 ---------------------------
 
7985
 
 
7986
-This module defines one class called :class:`Popen`:
 
7987
+The recommended approach to invoking subprocesses is to use the following
 
7988
+convenience functions for all use cases they can handle. For more advanced
 
7989
+use cases, the underlying :class:`Popen` interface can be used directly.
 
7990
+
 
7991
+
 
7992
+.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
 
7993
+
 
7994
+   Run the command described by *args*.  Wait for command to complete, then
 
7995
+   return the :attr:`returncode` attribute.
 
7996
+
 
7997
+   The arguments shown above are merely the most common ones, described below
 
7998
+   in :ref:`frequently-used-arguments` (hence the slightly odd notation in
 
7999
+   the abbreviated signature). The full function signature is the same as
 
8000
+   that of the :class:`Popen` constructor - this functions passes all
 
8001
+   supplied arguments directly through to that interface.
 
8002
+
 
8003
+   Examples::
 
8004
+
 
8005
+      >>> subprocess.call(["ls", "-l"])
 
8006
+      0
 
8007
+
 
8008
+      >>> subprocess.call("exit 1", shell=True)
 
8009
+      1
 
8010
+
 
8011
+   .. warning::
 
8012
+
 
8013
+      Invoking the system shell with ``shell=True`` can be a security hazard
 
8014
+      if combined with untrusted input. See the warning under
 
8015
+      :ref:`frequently-used-arguments` for details.
 
8016
+
 
8017
+   .. note::
 
8018
+
 
8019
+      Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
 
8020
+      the pipes are not being read in the current process, the child
 
8021
+      process may block if it generates enough output to a pipe to fill up
 
8022
+      the OS pipe buffer.
 
8023
+
 
8024
+
 
8025
+.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
 
8026
+
 
8027
+   Run command with arguments.  Wait for command to complete. If the return
 
8028
+   code was zero then return, otherwise raise :exc:`CalledProcessError`. The
 
8029
+   :exc:`CalledProcessError` object will have the return code in the
 
8030
+   :attr:`returncode` attribute.
 
8031
+
 
8032
+   The arguments shown above are merely the most common ones, described below
 
8033
+   in :ref:`frequently-used-arguments` (hence the slightly odd notation in
 
8034
+   the abbreviated signature). The full function signature is the same as
 
8035
+   that of the :class:`Popen` constructor - this functions passes all
 
8036
+   supplied arguments directly through to that interface.
 
8037
+
 
8038
+   Examples::
 
8039
+
 
8040
+      >>> subprocess.check_call(["ls", "-l"])
 
8041
+      0
 
8042
+
 
8043
+      >>> subprocess.check_call("exit 1", shell=True)
 
8044
+      Traceback (most recent call last):
 
8045
+         ...
 
8046
+      subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
 
8047
+
 
8048
+   .. versionadded:: 2.5
 
8049
+
 
8050
+   .. warning::
 
8051
+
 
8052
+      Invoking the system shell with ``shell=True`` can be a security hazard
 
8053
+      if combined with untrusted input. See the warning under
 
8054
+      :ref:`frequently-used-arguments` for details.
 
8055
+
 
8056
+   .. note::
 
8057
+
 
8058
+      Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function. As
 
8059
+      the pipes are not being read in the current process, the child
 
8060
+      process may block if it generates enough output to a pipe to fill up
 
8061
+      the OS pipe buffer.
 
8062
+
 
8063
+
 
8064
+.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
 
8065
+
 
8066
+   Run command with arguments and return its output as a byte string.
 
8067
+
 
8068
+   If the return code was non-zero it raises a :exc:`CalledProcessError`. The
 
8069
+   :exc:`CalledProcessError` object will have the return code in the
 
8070
+   :attr:`returncode` attribute and any output in the :attr:`output`
 
8071
+   attribute.
 
8072
+
 
8073
+   The arguments shown above are merely the most common ones, described below
 
8074
+   in :ref:`frequently-used-arguments` (hence the slightly odd notation in
 
8075
+   the abbreviated signature). The full function signature is largely the
 
8076
+   same as that of the :class:`Popen` constructor, except that *stdout* is
 
8077
+   not permitted as it is used internally. All other supplied arguments are
 
8078
+   passed directly through to the :class:`Popen` constructor.
 
8079
+
 
8080
+   Examples::
 
8081
+
 
8082
+      >>> subprocess.check_output(["echo", "Hello World!"])
 
8083
+      'Hello World!\n'
 
8084
+
 
8085
+      >>> subprocess.check_output("exit 1", shell=True)
 
8086
+      Traceback (most recent call last):
 
8087
+         ...
 
8088
+      subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
 
8089
+
 
8090
+   To also capture standard error in the result, use
 
8091
+   ``stderr=subprocess.STDOUT``::
 
8092
+
 
8093
+      >>> subprocess.check_output(
 
8094
+      ...     "ls non_existent_file; exit 0",
 
8095
+      ...     stderr=subprocess.STDOUT,
 
8096
+      ...     shell=True)
 
8097
+      'ls: non_existent_file: No such file or directory\n'
 
8098
+
 
8099
+   .. versionadded:: 2.7
 
8100
+
 
8101
+   .. warning::
 
8102
+
 
8103
+      Invoking the system shell with ``shell=True`` can be a security hazard
 
8104
+      if combined with untrusted input. See the warning under
 
8105
+      :ref:`frequently-used-arguments` for details.
 
8106
+
 
8107
+   .. note::
 
8108
+
 
8109
+      Do not use ``stderr=PIPE`` with this function. As the pipe is not being
 
8110
+      read in the current process, the child process may block if it
 
8111
+      generates enough output to the pipe to fill up the OS pipe buffer.
 
8112
+
 
8113
+
 
8114
+.. data:: PIPE
 
8115
+
 
8116
+   Special value that can be used as the *stdin*, *stdout* or *stderr* argument
 
8117
+   to :class:`Popen` and indicates that a pipe to the standard stream should be
 
8118
+   opened.
 
8119
+
 
8120
+
 
8121
+.. data:: STDOUT
 
8122
+
 
8123
+   Special value that can be used as the *stderr* argument to :class:`Popen` and
 
8124
+   indicates that standard error should go into the same handle as standard
 
8125
+   output.
 
8126
+
 
8127
+
 
8128
+.. _frequently-used-arguments:
 
8129
+
 
8130
+Frequently Used Arguments
 
8131
+^^^^^^^^^^^^^^^^^^^^^^^^^
 
8132
+
 
8133
+To support a wide variety of use cases, the :class:`Popen` constructor (and
 
8134
+the convenience functions) accept a large number of optional arguments. For
 
8135
+most typical use cases, many of these arguments can be safely left at their
 
8136
+default values. The arguments that are most commonly needed are:
 
8137
+
 
8138
+   *args* is required for all calls and should be a string, or a sequence of
 
8139
+   program arguments. Providing a sequence of arguments is generally
 
8140
+   preferred, as it allows the module to take care of any required escaping
 
8141
+   and quoting of arguments (e.g. to permit spaces in file names). If passing
 
8142
+   a single string, either *shell* must be :const:`True` (see below) or else
 
8143
+   the string must simply name the program to be executed without specifying
 
8144
+   any arguments.
 
8145
+
 
8146
+   *stdin*, *stdout* and *stderr* specify the executed program's standard input,
 
8147
+   standard output and standard error file handles, respectively.  Valid values
 
8148
+   are :data:`PIPE`, an existing file descriptor (a positive integer), an
 
8149
+   existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
 
8150
+   to the child should be created.  With the default settings of ``None``, no
 
8151
+   redirection will occur; the child's file handles will be inherited from the
 
8152
+   parent.  Additionally, *stderr* can be :data:`STDOUT`, which indicates that
 
8153
+   the stderr data from the child process should be captured into the same file
 
8154
+   handle as for stdout.
 
8155
+
 
8156
+   When *stdout* or *stderr* are pipes and *universal_newlines* is
 
8157
+   :const:`True` then all line endings will be converted to ``'\n'`` as
 
8158
+   described for the universal newlines `'U'`` mode argument to :func:`open`.
 
8159
+
 
8160
+   If *shell* is :const:`True`, the specified command will be executed through
 
8161
+   the shell. This can be useful if you are using Python primarily for the
 
8162
+   enhanced control flow it offers over most system shells and still want
 
8163
+   access to other shell features such as filename wildcards, shell pipes and
 
8164
+   environment variable expansion.
 
8165
+
 
8166
+   .. warning::
 
8167
+
 
8168
+      Executing shell commands that incorporate unsanitized input from an
 
8169
+      untrusted source makes a program vulnerable to `shell injection
 
8170
+      <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
 
8171
+      a serious security flaw which can result in arbitrary command execution.
 
8172
+      For this reason, the use of *shell=True* is **strongly discouraged** in cases
 
8173
+      where the command string is constructed from external input::
 
8174
+
 
8175
+         >>> from subprocess import call
 
8176
+         >>> filename = input("What file would you like to display?\n")
 
8177
+         What file would you like to display?
 
8178
+         non_existent; rm -rf / #
 
8179
+         >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
 
8180
+
 
8181
+      ``shell=False`` disables all shell based features, but does not suffer
 
8182
+      from this vulnerability; see the Note in the :class:`Popen` constructor
 
8183
+      documentation for helpful hints in getting ``shell=False`` to work.
 
8184
+
 
8185
+These options, along with all of the other options, are described in more
 
8186
+detail in the :class:`Popen` constructor documentation.
 
8187
+
 
8188
+
 
8189
+Popen Constuctor
 
8190
+^^^^^^^^^^^^^^^^
 
8191
+
 
8192
+The underlying process creation and management in this module is handled by
 
8193
+the :class:`Popen` class. It offers a lot of flexibility so that developers
 
8194
+are able to handle the less common cases not covered by the convenience
 
8195
+functions.
 
8196
 
 
8197
 
 
8198
 .. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
 
8199
@@ -81,24 +289,6 @@
 
8200
 
 
8201
       Popen(['/bin/sh', '-c', args[0], args[1], ...])
 
8202
 
 
8203
-   .. warning::
 
8204
-
 
8205
-      Executing shell commands that incorporate unsanitized input from an
 
8206
-      untrusted source makes a program vulnerable to `shell injection
 
8207
-      <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
 
8208
-      a serious security flaw which can result in arbitrary command execution.
 
8209
-      For this reason, the use of *shell=True* is **strongly discouraged** in cases
 
8210
-      where the command string is constructed from external input::
 
8211
-
 
8212
-         >>> from subprocess import call
 
8213
-         >>> filename = input("What file would you like to display?\n")
 
8214
-         What file would you like to display?
 
8215
-         non_existent; rm -rf / #
 
8216
-         >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
 
8217
-
 
8218
-      *shell=False* does not suffer from this vulnerability; the above Note may be
 
8219
-      helpful in getting code using *shell=False* to work.
 
8220
-
 
8221
    On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
 
8222
    child program, which operates on strings.  If *args* is a sequence, it will
 
8223
    be converted to a string in a manner described in
 
8224
@@ -126,14 +316,15 @@
 
8225
    You don't need ``shell=True`` to run a batch file, nor to run a console-based
 
8226
    executable.
 
8227
 
 
8228
-   *stdin*, *stdout* and *stderr* specify the executed programs' standard input,
 
8229
+   *stdin*, *stdout* and *stderr* specify the executed program's standard input,
 
8230
    standard output and standard error file handles, respectively.  Valid values
 
8231
    are :data:`PIPE`, an existing file descriptor (a positive integer), an
 
8232
    existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
 
8233
-   to the child should be created.  With ``None``, no redirection will occur;
 
8234
-   the child's file handles will be inherited from the parent.  Additionally,
 
8235
-   *stderr* can be :data:`STDOUT`, which indicates that the stderr data from the
 
8236
-   applications should be captured into the same file handle as for stdout.
 
8237
+   to the child should be created.  With the default settings of ``None``, no
 
8238
+   redirection will occur; the child's file handles will be inherited from the
 
8239
+   parent.  Additionally, *stderr* can be :data:`STDOUT`, which indicates that
 
8240
+   the stderr data from the child process should be captured into the same file
 
8241
+   handle as for stdout.
 
8242
 
 
8243
    If *preexec_fn* is set to a callable object, this object will be called in the
 
8244
    child process just before the child is executed. (Unix only)
 
8245
@@ -147,6 +338,12 @@
 
8246
    If *shell* is :const:`True`, the specified command will be executed through the
 
8247
    shell.
 
8248
 
 
8249
+   .. warning::
 
8250
+
 
8251
+      Enabling this option can be a security hazard if combined with untrusted
 
8252
+      input. See the warning under :ref:`frequently-used-arguments`
 
8253
+      for details.
 
8254
+
 
8255
    If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
 
8256
    before it is executed.  Note that this directory is not considered when
 
8257
    searching the executable, so you can't specify the program's path relative to
 
8258
@@ -184,87 +381,6 @@
 
8259
    :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)
 
8260
 
 
8261
 
 
8262
-.. data:: PIPE
 
8263
-
 
8264
-   Special value that can be used as the *stdin*, *stdout* or *stderr* argument
 
8265
-   to :class:`Popen` and indicates that a pipe to the standard stream should be
 
8266
-   opened.
 
8267
-
 
8268
-
 
8269
-.. data:: STDOUT
 
8270
-
 
8271
-   Special value that can be used as the *stderr* argument to :class:`Popen` and
 
8272
-   indicates that standard error should go into the same handle as standard
 
8273
-   output.
 
8274
-
 
8275
-
 
8276
-Convenience Functions
 
8277
-^^^^^^^^^^^^^^^^^^^^^
 
8278
-
 
8279
-This module also defines the following shortcut functions:
 
8280
-
 
8281
-
 
8282
-.. function:: call(*popenargs, **kwargs)
 
8283
-
 
8284
-   Run command with arguments.  Wait for command to complete, then return the
 
8285
-   :attr:`returncode` attribute.
 
8286
-
 
8287
-   The arguments are the same as for the :class:`Popen` constructor.  Example::
 
8288
-
 
8289
-      >>> retcode = subprocess.call(["ls", "-l"])
 
8290
-
 
8291
-   .. warning::
 
8292
-
 
8293
-      Like :meth:`Popen.wait`, this will deadlock when using
 
8294
-      ``stdout=PIPE`` and/or ``stderr=PIPE`` and the child process
 
8295
-      generates enough output to a pipe such that it blocks waiting
 
8296
-      for the OS pipe buffer to accept more data.
 
8297
-
 
8298
-
 
8299
-.. function:: check_call(*popenargs, **kwargs)
 
8300
-
 
8301
-   Run command with arguments.  Wait for command to complete. If the exit code was
 
8302
-   zero then return, otherwise raise :exc:`CalledProcessError`. The
 
8303
-   :exc:`CalledProcessError` object will have the return code in the
 
8304
-   :attr:`returncode` attribute.
 
8305
-
 
8306
-   The arguments are the same as for the :class:`Popen` constructor.  Example::
 
8307
-
 
8308
-      >>> subprocess.check_call(["ls", "-l"])
 
8309
-      0
 
8310
-
 
8311
-   .. versionadded:: 2.5
 
8312
-
 
8313
-   .. warning::
 
8314
-
 
8315
-      See the warning for :func:`call`.
 
8316
-
 
8317
-
 
8318
-.. function:: check_output(*popenargs, **kwargs)
 
8319
-
 
8320
-   Run command with arguments and return its output as a byte string.
 
8321
-
 
8322
-   If the exit code was non-zero it raises a :exc:`CalledProcessError`.  The
 
8323
-   :exc:`CalledProcessError` object will have the return code in the
 
8324
-   :attr:`returncode`
 
8325
-   attribute and output in the :attr:`output` attribute.
 
8326
-
 
8327
-   The arguments are the same as for the :class:`Popen` constructor.  Example::
 
8328
-
 
8329
-      >>> subprocess.check_output(["ls", "-l", "/dev/null"])
 
8330
-      'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
 
8331
-
 
8332
-   The stdout argument is not allowed as it is used internally.
 
8333
-   To capture standard error in the result, use ``stderr=subprocess.STDOUT``::
 
8334
-
 
8335
-      >>> subprocess.check_output(
 
8336
-      ...     ["/bin/sh", "-c", "ls non_existent_file; exit 0"],
 
8337
-      ...     stderr=subprocess.STDOUT)
 
8338
-      'ls: non_existent_file: No such file or directory\n'
 
8339
-
 
8340
-   .. versionadded:: 2.7
 
8341
-
 
8342
-
 
8343
 Exceptions
 
8344
 ^^^^^^^^^^
 
8345
 
 
8346
@@ -280,16 +396,19 @@
 
8347
 A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
 
8348
 arguments.
 
8349
 
 
8350
-check_call() will raise :exc:`CalledProcessError`, if the called process returns
 
8351
-a non-zero return code.
 
8352
+:func:`check_call` and :func:`check_output` will raise
 
8353
+:exc:`CalledProcessError` if the called process returns a non-zero return
 
8354
+code.
 
8355
 
 
8356
 
 
8357
 Security
 
8358
 ^^^^^^^^
 
8359
 
 
8360
-Unlike some other popen functions, this implementation will never call /bin/sh
 
8361
-implicitly.  This means that all characters, including shell metacharacters, can
 
8362
-safely be passed to child processes.
 
8363
+Unlike some other popen functions, this implementation will never call a
 
8364
+system shell implicitly.  This means that all characters, including shell
 
8365
+metacharacters, can safely be passed to child processes. Obviously, if the
 
8366
+shell is invoked explicitly, then it is the application's responsibility to
 
8367
+ensure that all whitespace and metacharacters are quoted appropriately.
 
8368
 
 
8369
 
 
8370
 Popen Objects
 
8371
@@ -428,38 +547,39 @@
2843
8372
 
2844
8373
    .. attribute:: dwFlags
2845
8374
 
2891
8420
       ignored.
2892
8421
 
2893
8422
       :data:`SW_HIDE` is provided for this attribute. It is used when
2894
 
@@ -493,12 +494,12 @@
 
8423
@@ -493,12 +613,12 @@
2895
8424
 .. data:: STARTF_USESTDHANDLES
2896
8425
 
2897
8426
    Specifies that the :attr:`STARTUPINFO.hStdInput`,
2906
8435
    additional information.
2907
8436
 
2908
8437
 .. data:: CREATE_NEW_CONSOLE
 
8438
@@ -522,15 +642,21 @@
 
8439
 Replacing Older Functions with the subprocess Module
 
8440
 ----------------------------------------------------
 
8441
 
 
8442
-In this section, "a ==> b" means that b can be used as a replacement for a.
 
8443
+In this section, "a becomes b" means that b can be used as a replacement for a.
 
8444
 
 
8445
 .. note::
 
8446
 
 
8447
-   All functions in this section fail (more or less) silently if the executed
 
8448
-   program cannot be found; this module raises an :exc:`OSError` exception.
 
8449
+   All "a" functions in this section fail (more or less) silently if the
 
8450
+   executed program cannot be found; the "b" replacements raise :exc:`OSError`
 
8451
+   instead.
 
8452
 
 
8453
-In the following examples, we assume that the subprocess module is imported with
 
8454
-"from subprocess import \*".
 
8455
+   In addition, the replacements using :func:`check_output` will fail with a
 
8456
+   :exc:`CalledProcessError` if the requested operation produces a non-zero
 
8457
+   return code. The output is still available as the ``output`` attribute of
 
8458
+   the raised exception.
 
8459
+
 
8460
+In the following examples, we assume that the relevant functions have already
 
8461
+been imported from the subprocess module.
 
8462
 
 
8463
 
 
8464
 Replacing /bin/sh shell backquote
 
8465
@@ -539,8 +665,8 @@
 
8466
 ::
 
8467
 
 
8468
    output=`mycmd myarg`
 
8469
-   ==>
 
8470
-   output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
 
8471
+   # becomes
 
8472
+   output = check_output(["mycmd", "myarg"])
 
8473
 
 
8474
 
 
8475
 Replacing shell pipeline
 
8476
@@ -549,7 +675,7 @@
 
8477
 ::
 
8478
 
 
8479
    output=`dmesg | grep hda`
 
8480
-   ==>
 
8481
+   # becomes
 
8482
    p1 = Popen(["dmesg"], stdout=PIPE)
 
8483
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
 
8484
    p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
 
8485
@@ -558,22 +684,27 @@
 
8486
 The p1.stdout.close() call after starting the p2 is important in order for p1
 
8487
 to receive a SIGPIPE if p2 exits before p1.
 
8488
 
 
8489
+Alternatively, for trusted input, the shell's own pipeline support may still
 
8490
+be used directly:
 
8491
+
 
8492
+   output=`dmesg | grep hda`
 
8493
+   # becomes
 
8494
+   output=check_output("dmesg | grep hda", shell=True)
 
8495
+
 
8496
+
 
8497
 Replacing :func:`os.system`
 
8498
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
8499
 
 
8500
 ::
 
8501
 
 
8502
    sts = os.system("mycmd" + " myarg")
 
8503
-   ==>
 
8504
-   p = Popen("mycmd" + " myarg", shell=True)
 
8505
-   sts = os.waitpid(p.pid, 0)[1]
 
8506
+   # becomes
 
8507
+   sts = call("mycmd" + " myarg", shell=True)
 
8508
 
 
8509
 Notes:
 
8510
 
 
8511
 * Calling the program through the shell is usually not required.
 
8512
 
 
8513
-* It's easier to look at the :attr:`returncode` attribute than the exit status.
 
8514
-
 
8515
 A more realistic example would look like this::
 
8516
 
 
8517
    try:
 
8518
@@ -718,6 +849,7 @@
 
8519
 * popen2 closes all file descriptors by default, but you have to specify
 
8520
   ``close_fds=True`` with :class:`Popen`.
 
8521
 
 
8522
+
 
8523
 Notes
 
8524
 -----
 
8525
 
 
8526
diff -r 8527427914a2 Doc/library/sunau.rst
 
8527
--- a/Doc/library/sunau.rst
 
8528
+++ b/Doc/library/sunau.rst
 
8529
@@ -1,4 +1,3 @@
 
8530
-
 
8531
 :mod:`sunau` --- Read and write Sun AU files
 
8532
 ============================================
 
8533
 
 
8534
@@ -6,6 +5,9 @@
 
8535
    :synopsis: Provide an interface to the Sun AU sound format.
 
8536
 .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
 
8537
 
 
8538
+**Source code:** :source:`Lib/sunau.py`
 
8539
+
 
8540
+--------------
 
8541
 
 
8542
 The :mod:`sunau` module provides a convenient interface to the Sun AU sound
 
8543
 format.  Note that this module is interface-compatible with the modules
 
8544
diff -r 8527427914a2 Doc/library/symbol.rst
 
8545
--- a/Doc/library/symbol.rst
 
8546
+++ b/Doc/library/symbol.rst
 
8547
@@ -1,4 +1,3 @@
 
8548
-
 
8549
 :mod:`symbol` --- Constants used with Python parse trees
 
8550
 ========================================================
 
8551
 
 
8552
@@ -6,6 +5,9 @@
 
8553
    :synopsis: Constants representing internal nodes of the parse tree.
 
8554
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
8555
 
 
8556
+**Source code:** :source:`Lib/symbol.py`
 
8557
+
 
8558
+--------------
 
8559
 
 
8560
 This module provides constants which represent the numeric values of internal
 
8561
 nodes of the parse tree.  Unlike most Python constants, these use lower-case
2909
8562
diff -r 8527427914a2 Doc/library/sys.rst
2910
8563
--- a/Doc/library/sys.rst
2911
8564
+++ b/Doc/library/sys.rst
2930
8583
 .. data:: builtin_module_names
2931
8584
 
2932
8585
    A tuple of strings giving the names of all modules that are compiled into this
2933
 
@@ -726,6 +712,12 @@
2934
 
    For Unix systems, this is the lowercased OS name as returned by ``uname -s``
2935
 
    with the first part of the version as returned by ``uname -r`` appended,
2936
 
    e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
2937
 
+   Unless you want to test for a specific system version, it is therefore
2938
 
+   recommended to use the following idiom::
2939
 
+
2940
 
+      if sys.platform.startswith('linux'):
 
8586
@@ -109,6 +95,17 @@
 
8587
    customized by assigning another one-argument function to ``sys.displayhook``.
 
8588
 
 
8589
 
 
8590
+.. data:: dont_write_bytecode
 
8591
+
 
8592
+   If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
 
8593
+   import of source modules.  This value is initially set to ``True`` or
 
8594
+   ``False`` depending on the :option:`-B` command line option and the
 
8595
+   :envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it
 
8596
+   yourself to control bytecode file generation.
 
8597
+
 
8598
+   .. versionadded:: 2.6
 
8599
+
 
8600
+
 
8601
 .. function:: excepthook(type, value, traceback)
 
8602
 
 
8603
    This function prints out a given traceback and exception to ``sys.stderr``.
 
8604
@@ -210,10 +207,10 @@
 
8605
    Python files are installed; by default, this is also ``'/usr/local'``.  This can
 
8606
    be set at build time with the ``--exec-prefix`` argument to the
 
8607
    :program:`configure` script.  Specifically, all configuration files (e.g. the
 
8608
-   :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
 
8609
-   '/lib/pythonversion/config'``, and shared library modules are installed in
 
8610
-   ``exec_prefix + '/lib/pythonversion/lib-dynload'``, where *version* is equal to
 
8611
-   ``version[:3]``.
 
8612
+   :file:`pyconfig.h` header file) are installed in the directory
 
8613
+   :file:`{exec_prefix}/lib/python{X.Y}/config', and shared library modules are
 
8614
+   installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y*
 
8615
+   is the version number of Python, for example ``2.7``.
 
8616
 
 
8617
 
 
8618
 .. data:: executable
 
8619
@@ -331,8 +328,12 @@
 
8620
    +---------------------+----------------+--------------------------------------------------+
 
8621
    | :const:`radix`      | FLT_RADIX      | radix of exponent representation                 |
 
8622
    +---------------------+----------------+--------------------------------------------------+
 
8623
-   | :const:`rounds`     | FLT_ROUNDS     | constant representing rounding mode              |
 
8624
-   |                     |                | used for arithmetic operations                   |
 
8625
+   | :const:`rounds`     | FLT_ROUNDS     | integer constant representing the rounding mode  |
 
8626
+   |                     |                | used for arithmetic operations.  This reflects   |
 
8627
+   |                     |                | the value of the system FLT_ROUNDS macro at      |
 
8628
+   |                     |                | interpreter startup time.  See section 5.2.4.2.2 |
 
8629
+   |                     |                | of the C99 standard for an explanation of the    |
 
8630
+   |                     |                | possible values and their meanings.              |
 
8631
    +---------------------+----------------+--------------------------------------------------+
 
8632
 
 
8633
    The attribute :attr:`sys.float_info.dig` needs further explanation.  If
 
8634
@@ -723,23 +724,45 @@
 
8635
    This string contains a platform identifier that can be used to append
 
8636
    platform-specific components to :data:`sys.path`, for instance.
 
8637
 
 
8638
-   For Unix systems, this is the lowercased OS name as returned by ``uname -s``
 
8639
-   with the first part of the version as returned by ``uname -r`` appended,
 
8640
-   e.g. ``'sunos5'`` or ``'linux2'``, *at the time when Python was built*.
 
8641
+   For most Unix systems, this is the lowercased OS name as returned by ``uname
 
8642
+   -s`` with the first part of the version as returned by ``uname -r`` appended,
 
8643
+   e.g. ``'sunos5'``, *at the time when Python was built*.  Unless you want to
 
8644
+   test for a specific system version, it is therefore recommended to use the
 
8645
+   following idiom::
 
8646
+
 
8647
+      if sys.platform.startswith('freebsd'):
 
8648
+          # FreeBSD-specific code here...
 
8649
+      elif sys.platform.startswith('linux'):
2941
8650
+          # Linux-specific code here...
2942
8651
+
 
8652
+   .. versionchanged:: 2.7.3
 
8653
+      Since lots of code check for ``sys.platform == 'linux2'``, and there is
 
8654
+      no essential change between Linux 2.x and 3.x, ``sys.platform`` is always
 
8655
+      set to ``'linux2'``, even on Linux 3.x.  In Python 3.3 and later, the
 
8656
+      value will always be set to ``'linux'``, so it is recommended to always
 
8657
+      use the ``startswith`` idiom presented above.
 
8658
+
2943
8659
    For other systems, the values are:
2944
8660
 
2945
 
    ================ ===========================
2946
 
@@ -740,6 +732,12 @@
2947
 
    AtheOS           ``'atheos'``
2948
 
    ================ ===========================
 
8661
-   ================ ===========================
 
8662
-   System           :data:`platform` value
 
8663
-   ================ ===========================
 
8664
-   Windows          ``'win32'``
 
8665
-   Windows/Cygwin   ``'cygwin'``
 
8666
-   Mac OS X         ``'darwin'``
 
8667
-   OS/2             ``'os2'``
 
8668
-   OS/2 EMX         ``'os2emx'``
 
8669
-   RiscOS           ``'riscos'``
 
8670
-   AtheOS           ``'atheos'``
 
8671
-   ================ ===========================
 
8672
+   ===================== ===========================
 
8673
+   System                :data:`platform` value
 
8674
+   ===================== ===========================
 
8675
+   Linux (2.x *and* 3.x) ``'linux2'``
 
8676
+   Windows               ``'win32'``
 
8677
+   Windows/Cygwin        ``'cygwin'``
 
8678
+   Mac OS X              ``'darwin'``
 
8679
+   OS/2                  ``'os2'``
 
8680
+   OS/2 EMX              ``'os2emx'``
 
8681
+   RiscOS                ``'riscos'``
 
8682
+   AtheOS                ``'atheos'``
 
8683
+   ===================== ===========================
2949
8684
 
2950
8685
+   .. seealso::
2951
8686
+      :attr:`os.name` has a coarser granularity.  :func:`os.uname` gives
2956
8691
 
2957
8692
 .. data:: prefix
2958
8693
 
2959
 
@@ -980,6 +978,26 @@
 
8694
@@ -747,10 +770,10 @@
 
8695
    independent Python files are installed; by default, this is the string
 
8696
    ``'/usr/local'``.  This can be set at build time with the ``--prefix``
 
8697
    argument to the :program:`configure` script.  The main collection of Python
 
8698
-   library modules is installed in the directory ``prefix + '/lib/pythonversion'``
 
8699
+   library modules is installed in the directory :file:`{prefix}/lib/python{X.Y}``
 
8700
    while the platform independent header files (all except :file:`pyconfig.h`) are
 
8701
-   stored in ``prefix + '/include/pythonversion'``, where *version* is equal to
 
8702
-   ``version[:3]``.
 
8703
+   stored in :file:`{prefix}/include/python{X.Y}``, where *X.Y* is the version
 
8704
+   number of Python, for example ``2.7``.
 
8705
 
 
8706
 
 
8707
 .. data:: ps1
 
8708
@@ -778,17 +801,6 @@
 
8709
    .. versionadded:: 2.6
 
8710
 
 
8711
 
 
8712
-.. data:: dont_write_bytecode
 
8713
-
 
8714
-   If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
 
8715
-   import of source modules.  This value is initially set to ``True`` or ``False``
 
8716
-   depending on the ``-B`` command line option and the ``PYTHONDONTWRITEBYTECODE``
 
8717
-   environment variable, but you can set it yourself to control bytecode file
 
8718
-   generation.
 
8719
-
 
8720
-   .. versionadded:: 2.6
 
8721
-
 
8722
-
 
8723
 .. function:: setcheckinterval(interval)
 
8724
 
 
8725
    Set the interpreter's "check interval".  This integer value determines how often
 
8726
@@ -980,6 +992,26 @@
2960
8727
    replacing it, and restore the saved object.
2961
8728
 
2962
8729
 
2983
8750
 .. data:: tracebacklimit
2984
8751
 
2985
8752
    When this variable is set to an integer value, it determines the maximum number
 
8753
diff -r 8527427914a2 Doc/library/sysconfig.rst
 
8754
--- a/Doc/library/sysconfig.rst
 
8755
+++ b/Doc/library/sysconfig.rst
 
8756
@@ -5,10 +5,15 @@
 
8757
    :synopsis: Python's configuration information
 
8758
 .. moduleauthor:: Tarek Ziade <tarek@ziade.org>
 
8759
 .. sectionauthor:: Tarek Ziade <tarek@ziade.org>
 
8760
-.. versionadded:: 2.7
 
8761
 .. index::
 
8762
    single: configuration information
 
8763
 
 
8764
+.. versionadded:: 2.7
 
8765
+
 
8766
+**Source code:** :source:`Lib/sysconfig.py`
 
8767
+
 
8768
+--------------
 
8769
+
 
8770
 The :mod:`sysconfig` module provides access to Python's configuration
 
8771
 information like the list of installation paths and the configuration variables
 
8772
 relevant for the current platform.
 
8773
diff -r 8527427914a2 Doc/library/tabnanny.rst
 
8774
--- a/Doc/library/tabnanny.rst
 
8775
+++ b/Doc/library/tabnanny.rst
 
8776
@@ -9,6 +9,10 @@
 
8777
 
 
8778
 .. rudimentary documentation based on module comments
 
8779
 
 
8780
+**Source code:** :source:`Lib/tabnanny.py`
 
8781
+
 
8782
+--------------
 
8783
+
 
8784
 For the time being this module is intended to be called as a script. However it
 
8785
 is possible to import it into an IDE and use the function :func:`check`
 
8786
 described below.
 
8787
diff -r 8527427914a2 Doc/library/tarfile.rst
 
8788
--- a/Doc/library/tarfile.rst
 
8789
+++ b/Doc/library/tarfile.rst
 
8790
@@ -1,5 +1,3 @@
 
8791
-.. _tarfile-mod:
 
8792
-
 
8793
 :mod:`tarfile` --- Read and write tar archive files
 
8794
 ===================================================
 
8795
 
 
8796
@@ -12,6 +10,9 @@
 
8797
 .. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
 
8798
 .. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
 
8799
 
 
8800
+**Source code:** :source:`Lib/tarfile.py`
 
8801
+
 
8802
+--------------
 
8803
 
 
8804
 The :mod:`tarfile` module makes it possible to read and write tar
 
8805
 archives, including those using gzip or bz2 compression.
 
8806
diff -r 8527427914a2 Doc/library/telnetlib.rst
 
8807
--- a/Doc/library/telnetlib.rst
 
8808
+++ b/Doc/library/telnetlib.rst
 
8809
@@ -1,4 +1,3 @@
 
8810
-
 
8811
 :mod:`telnetlib` --- Telnet client
 
8812
 ==================================
 
8813
 
 
8814
@@ -9,6 +8,10 @@
 
8815
 
 
8816
 .. index:: single: protocol; Telnet
 
8817
 
 
8818
+**Source code:** :source:`Lib/telnetlib.py`
 
8819
+
 
8820
+--------------
 
8821
+
 
8822
 The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the
 
8823
 Telnet protocol.  See :rfc:`854` for details about the protocol. In addition, it
 
8824
 provides symbolic constants for the protocol characters (see below), and for the
2986
8825
diff -r 8527427914a2 Doc/library/tempfile.rst
2987
8826
--- a/Doc/library/tempfile.rst
2988
8827
+++ b/Doc/library/tempfile.rst
2989
 
@@ -61,7 +61,7 @@
 
8828
@@ -1,4 +1,3 @@
 
8829
-
 
8830
 :mod:`tempfile` --- Generate temporary files and directories
 
8831
 ============================================================
 
8832
 
 
8833
@@ -13,6 +12,10 @@
 
8834
    pair: temporary; file name
 
8835
    pair: temporary; file
 
8836
 
 
8837
+**Source code:** :source:`Lib/tempfile.py`
 
8838
+
 
8839
+--------------
 
8840
+
 
8841
 This module generates temporary files and directories.  It works on all
 
8842
 supported platforms.
 
8843
 
 
8844
@@ -61,7 +64,7 @@
2990
8845
    This function operates exactly as :func:`TemporaryFile` does, except that
2991
8846
    the file is guaranteed to have a visible name in the file system (on
2992
8847
    Unix, the directory entry is not unlinked).  That name can be retrieved
2995
8850
    used to open the file a second time, while the named temporary file is
2996
8851
    still open, varies across platforms (it can be so used on Unix; it cannot
2997
8852
    on Windows NT or later).  If *delete* is true (the default), the file is
 
8853
diff -r 8527427914a2 Doc/library/textwrap.rst
 
8854
--- a/Doc/library/textwrap.rst
 
8855
+++ b/Doc/library/textwrap.rst
 
8856
@@ -1,4 +1,3 @@
 
8857
-
 
8858
 :mod:`textwrap` --- Text wrapping and filling
 
8859
 =============================================
 
8860
 
 
8861
@@ -7,8 +6,11 @@
 
8862
 .. moduleauthor:: Greg Ward <gward@python.net>
 
8863
 .. sectionauthor:: Greg Ward <gward@python.net>
 
8864
 
 
8865
+.. versionadded:: 2.3
 
8866
 
 
8867
-.. versionadded:: 2.3
 
8868
+**Source code:** :source:`Lib/textwrap.py`
 
8869
+
 
8870
+--------------
 
8871
 
 
8872
 The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and
 
8873
 :func:`fill`, as well as :class:`TextWrapper`, the class that does all the work,
 
8874
@@ -16,11 +18,6 @@
 
8875
 or two  text strings, the convenience functions should be good enough;
 
8876
 otherwise,  you should use an instance of :class:`TextWrapper` for efficiency.
 
8877
 
 
8878
-.. seealso::
 
8879
-
 
8880
-   Latest version of the `textwrap module Python source code
 
8881
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/textwrap.py?view=markup>`_
 
8882
-
 
8883
 .. function:: wrap(text[, width[, ...]])
 
8884
 
 
8885
    Wraps the single paragraph in *text* (a string) so every line is at most *width*
 
8886
diff -r 8527427914a2 Doc/library/threading.rst
 
8887
--- a/Doc/library/threading.rst
 
8888
+++ b/Doc/library/threading.rst
 
8889
@@ -4,6 +4,9 @@
 
8890
 .. module:: threading
 
8891
    :synopsis: Higher-level threading interface.
 
8892
 
 
8893
+**Source code:** :source:`Lib/threading.py`
 
8894
+
 
8895
+--------------
 
8896
 
 
8897
 This module constructs higher-level threading interfaces on top of the  lower
 
8898
 level :mod:`thread` module.
 
8899
@@ -36,11 +39,6 @@
 
8900
    :mod:`multiprocessing`. However, threading is still an appropriate model
 
8901
    if you want to run multiple I/O-bound tasks simultaneously.
 
8902
 
 
8903
-.. seealso::
 
8904
-
 
8905
-   Latest version of the `threading module Python source code
 
8906
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/threading.py?view=markup>`_
 
8907
-
 
8908
 
 
8909
 This module defines the following functions and objects:
 
8910
 
 
8911
@@ -575,20 +573,21 @@
 
8912
       interface is then used to restore the recursion level when the lock is
 
8913
       reacquired.
 
8914
 
 
8915
-   .. method:: notify()
 
8916
+   .. method:: notify(n=1)
 
8917
 
 
8918
-      Wake up a thread waiting on this condition, if any.  If the calling thread
 
8919
-      has not acquired the lock when this method is called, a
 
8920
+      By default, wake up one thread waiting on this condition, if any.  If the
 
8921
+      calling thread has not acquired the lock when this method is called, a
 
8922
       :exc:`RuntimeError` is raised.
 
8923
 
 
8924
-      This method wakes up one of the threads waiting for the condition
 
8925
-      variable, if any are waiting; it is a no-op if no threads are waiting.
 
8926
+      This method wakes up at most *n* of the threads waiting for the condition
 
8927
+      variable; it is a no-op if no threads are waiting.
 
8928
 
 
8929
-      The current implementation wakes up exactly one thread, if any are
 
8930
-      waiting.  However, it's not safe to rely on this behavior.  A future,
 
8931
-      optimized implementation may occasionally wake up more than one thread.
 
8932
+      The current implementation wakes up exactly *n* threads, if at least *n*
 
8933
+      threads are waiting.  However, it's not safe to rely on this behavior.
 
8934
+      A future, optimized implementation may occasionally wake up more than
 
8935
+      *n* threads.
 
8936
 
 
8937
-      Note: the awakened thread does not actually return from its :meth:`wait`
 
8938
+      Note: an awakened thread does not actually return from its :meth:`wait`
 
8939
       call until it can reacquire the lock.  Since :meth:`notify` does not
 
8940
       release the lock, its caller should.
 
8941
 
 
8942
diff -r 8527427914a2 Doc/library/time.rst
 
8943
--- a/Doc/library/time.rst
 
8944
+++ b/Doc/library/time.rst
 
8945
@@ -560,6 +560,6 @@
 
8946
    preferred  hour/minute offset is not supported by all ANSI C libraries. Also, a
 
8947
    strict reading of the original 1982 :rfc:`822` standard calls for a two-digit
 
8948
    year (%y rather than %Y), but practice moved to 4-digit years long before the
 
8949
-   year 2000.  The 4-digit year has been mandated by :rfc:`2822`, which obsoletes
 
8950
-   :rfc:`822`.
 
8951
+   year 2000.  After that, :rfc:`822` became obsolete and the 4-digit year has
 
8952
+   been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`.
 
8953
 
2998
8954
diff -r 8527427914a2 Doc/library/timeit.rst
2999
8955
--- a/Doc/library/timeit.rst
3000
8956
+++ b/Doc/library/timeit.rst
3001
 
@@ -195,13 +195,13 @@
 
8957
@@ -1,4 +1,3 @@
 
8958
-
 
8959
 :mod:`timeit` --- Measure execution time of small code snippets
 
8960
 ===============================================================
 
8961
 
 
8962
@@ -12,6 +11,10 @@
 
8963
    single: Benchmarking
 
8964
    single: Performance
 
8965
 
 
8966
+**Source code:** :source:`Lib/timeit.py`
 
8967
+
 
8968
+--------------
 
8969
+
 
8970
 This module provides a simple way to time small bits of Python code. It has both
 
8971
 command line as well as callable interfaces.  It avoids a number of common traps
 
8972
 for measuring execution times.  See also Tim Peters' introduction to the
 
8973
@@ -195,13 +198,13 @@
3002
8974
 :keyword:`try`/:keyword:`except` to test for missing and present object
3003
8975
 attributes. ::
3004
8976
 
3016
8988
    100000 loops, best of 3: 2.23 usec per loop
3017
8989
 
3018
8990
 ::
3019
 
@@ -242,12 +242,12 @@
 
8991
@@ -242,12 +245,12 @@
3020
8992
 ``setup`` parameter which contains an import statement::
3021
8993
 
3022
8994
    def test():
3031
9003
        from timeit import Timer
3032
9004
        t = Timer("test()", "from __main__ import test")
3033
9005
        print t.timeit()
 
9006
diff -r 8527427914a2 Doc/library/token.rst
 
9007
--- a/Doc/library/token.rst
 
9008
+++ b/Doc/library/token.rst
 
9009
@@ -1,4 +1,3 @@
 
9010
-
 
9011
 :mod:`token` --- Constants used with Python parse trees
 
9012
 =======================================================
 
9013
 
 
9014
@@ -6,6 +5,9 @@
 
9015
    :synopsis: Constants representing terminal nodes of the parse tree.
 
9016
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
9017
 
 
9018
+**Source code:** :source:`Lib/token.py`
 
9019
+
 
9020
+--------------
 
9021
 
 
9022
 This module provides constants which represent the numeric values of leaf nodes
 
9023
 of the parse tree (terminal tokens).  Refer to the file :file:`Grammar/Grammar`
 
9024
diff -r 8527427914a2 Doc/library/tokenize.rst
 
9025
--- a/Doc/library/tokenize.rst
 
9026
+++ b/Doc/library/tokenize.rst
 
9027
@@ -1,4 +1,3 @@
 
9028
-
 
9029
 :mod:`tokenize` --- Tokenizer for Python source
 
9030
 ===============================================
 
9031
 
 
9032
@@ -7,17 +6,15 @@
 
9033
 .. moduleauthor:: Ka Ping Yee
 
9034
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
9035
 
 
9036
+**Source code:** :source:`Lib/tokenize.py`
 
9037
+
 
9038
+--------------
 
9039
 
 
9040
 The :mod:`tokenize` module provides a lexical scanner for Python source code,
 
9041
 implemented in Python.  The scanner in this module returns comments as tokens as
 
9042
 well, making it useful for implementing "pretty-printers," including colorizers
 
9043
 for on-screen displays.
 
9044
 
 
9045
-.. seealso::
 
9046
-
 
9047
-   Latest version of the `tokenize module Python source code
 
9048
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/tokenize.py?view=markup>`_
 
9049
-
 
9050
 The primary entry point is a :term:`generator`:
 
9051
 
 
9052
 .. function:: generate_tokens(readline)
 
9053
diff -r 8527427914a2 Doc/library/trace.rst
 
9054
--- a/Doc/library/trace.rst
 
9055
+++ b/Doc/library/trace.rst
 
9056
@@ -1,21 +1,18 @@
 
9057
-
 
9058
 :mod:`trace` --- Trace or track Python statement execution
 
9059
 ==========================================================
 
9060
 
 
9061
 .. module:: trace
 
9062
    :synopsis: Trace or track Python statement execution.
 
9063
 
 
9064
+**Source code:** :source:`Lib/trace.py`
 
9065
+
 
9066
+--------------
 
9067
 
 
9068
 The :mod:`trace` module allows you to trace program execution, generate
 
9069
 annotated statement coverage listings, print caller/callee relationships and
 
9070
 list functions executed during a program run.  It can be used in another program
 
9071
 or from the command line.
 
9072
 
 
9073
-.. seealso::
 
9074
-
 
9075
-   Latest version of the `trace module Python source code
 
9076
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/trace.py?view=markup>`_
 
9077
-
 
9078
 .. _trace-cli:
 
9079
 
 
9080
 Command-Line Usage
 
9081
diff -r 8527427914a2 Doc/library/ttk.rst
 
9082
--- a/Doc/library/ttk.rst
 
9083
+++ b/Doc/library/ttk.rst
 
9084
@@ -1243,7 +1243,7 @@
 
9085
       *layoutspec*, if specified, is expected to be a list or some other
 
9086
       sequence type (excluding strings), where each item should be a tuple and
 
9087
       the first item is the layout name and the second item should have the
 
9088
-      format described described in `Layouts`_.
 
9089
+      format described in `Layouts`_.
 
9090
 
 
9091
       To understand the format, see the following example (it is not
 
9092
       intended to do anything useful)::
3034
9093
diff -r 8527427914a2 Doc/library/turtle.rst
3035
9094
--- a/Doc/library/turtle.rst
3036
9095
+++ b/Doc/library/turtle.rst
3047
9106
 
3048
9107
 By combining together these and similar commands, intricate shapes and pictures
3049
9108
 can easily be drawn.
 
9109
@@ -157,6 +157,7 @@
 
9110
    | :func:`onclick`
 
9111
    | :func:`onrelease`
 
9112
    | :func:`ondrag`
 
9113
+   | :func:`mainloop` | :func:`done`
 
9114
 
 
9115
 Special Turtle methods
 
9116
    | :func:`begin_poly`
 
9117
@@ -1291,6 +1292,15 @@
 
9118
    the screen thereby producing handdrawings (if pen is down).
 
9119
 
 
9120
 
 
9121
+.. function:: mainloop()
 
9122
+              done()
 
9123
+
 
9124
+   Starts event loop - calling Tkinter's mainloop function. Must be the last
 
9125
+   statement in a turtle graphics program.
 
9126
+
 
9127
+      >>> turtle.mainloop()
 
9128
+
 
9129
+
 
9130
 Special Turtle methods
 
9131
 ----------------------
 
9132
 
 
9133
diff -r 8527427914a2 Doc/library/types.rst
 
9134
--- a/Doc/library/types.rst
 
9135
+++ b/Doc/library/types.rst
 
9136
@@ -4,6 +4,9 @@
 
9137
 .. module:: types
 
9138
    :synopsis: Names for built-in types.
 
9139
 
 
9140
+**Source code:** :source:`Lib/types.py`
 
9141
+
 
9142
+--------------
 
9143
 
 
9144
 This module defines names for some object types that are used by the standard
 
9145
 Python interpreter, but not for the types defined by various extension modules.
 
9146
diff -r 8527427914a2 Doc/library/unittest.rst
 
9147
--- a/Doc/library/unittest.rst
 
9148
+++ b/Doc/library/unittest.rst
 
9149
@@ -307,7 +307,7 @@
 
9150
 
 
9151
     Test discovery loads tests by importing them. Once test discovery has
 
9152
     found all the test files from the start directory you specify it turns the
 
9153
-    paths into package names to import. For example `foo/bar/baz.py` will be
 
9154
+    paths into package names to import. For example :file:`foo/bar/baz.py` will be
 
9155
     imported as ``foo.bar.baz``.
 
9156
 
 
9157
     If you have a package installed globally and attempt test discovery on
 
9158
@@ -895,6 +895,8 @@
 
9159
 
 
9160
       Test that *obj* is (or is not) an instance of *cls* (which can be a
 
9161
       class or a tuple of classes, as supported by :func:`isinstance`).
 
9162
+      To check for a specific type (without including superclasses) use
 
9163
+      :func:`assertIs(type(obj), cls) <assertIs>`.
 
9164
 
 
9165
       .. versionadded:: 2.7
 
9166
 
 
9167
@@ -905,11 +907,11 @@
 
9168
    +---------------------------------------------------------+--------------------------------------+------------+
 
9169
    | Method                                                  | Checks that                          | New in     |
 
9170
    +=========================================================+======================================+============+
 
9171
-   | :meth:`assertRaises(exc, fun, *args, **kwds)            | ``fun(*args, **kwds)`` raises `exc`  |            |
 
9172
+   | :meth:`assertRaises(exc, fun, *args, **kwds)            | ``fun(*args, **kwds)`` raises *exc*  |            |
 
9173
    | <TestCase.assertRaises>`                                |                                      |            |
 
9174
    +---------------------------------------------------------+--------------------------------------+------------+
 
9175
-   | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds)  | ``fun(*args, **kwds)`` raises `exc`  | 2.7        |
 
9176
-   | <TestCase.assertRaisesRegexp>`                          | and the message matches `re`         |            |
 
9177
+   | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds)  | ``fun(*args, **kwds)`` raises *exc*  | 2.7        |
 
9178
+   | <TestCase.assertRaisesRegexp>`                          | and the message matches *re*         |            |
 
9179
    +---------------------------------------------------------+--------------------------------------+------------+
 
9180
 
 
9181
    .. method:: assertRaises(exception, callable, *args, **kwds)
 
9182
@@ -995,7 +997,7 @@
 
9183
    | <TestCase.assertItemsEqual>`          | works with unhashable objs     |              |
 
9184
    +---------------------------------------+--------------------------------+--------------+
 
9185
    | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs        | 2.7          |
 
9186
-   | <TestCase.assertDictContainsSubset>`  | in `a` exist in `b`            |              |
 
9187
+   | <TestCase.assertDictContainsSubset>`  | in *a* exist in *b*            |              |
 
9188
    +---------------------------------------+--------------------------------+--------------+
 
9189
 
 
9190
 
3050
9191
diff -r 8527427914a2 Doc/library/urllib.rst
3051
9192
--- a/Doc/library/urllib.rst
3052
9193
+++ b/Doc/library/urllib.rst
3071
9212
diff -r 8527427914a2 Doc/library/urllib2.rst
3072
9213
--- a/Doc/library/urllib2.rst
3073
9214
+++ b/Doc/library/urllib2.rst
 
9215
@@ -36,7 +36,7 @@
 
9216
    :mimetype:`application/x-www-form-urlencoded` format.  The
 
9217
    :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
 
9218
    returns a string in this format. urllib2 module sends HTTP/1.1 requests with
 
9219
-   `Connection:close` header included.
 
9220
+   ``Connection:close`` header included.
 
9221
 
 
9222
    The optional *timeout* parameter specifies a timeout in seconds for blocking
 
9223
    operations like the connection attempt (if not specified, the global default
3074
9224
@@ -90,7 +90,7 @@
3075
9225
    :class:`HTTPSHandler` will also be added.
3076
9226
 
3123
9273
 
3124
9274
 .. _urllib2-examples:
3125
9275
 
 
9276
diff -r 8527427914a2 Doc/library/urlparse.rst
 
9277
--- a/Doc/library/urlparse.rst
 
9278
+++ b/Doc/library/urlparse.rst
 
9279
@@ -17,6 +17,9 @@
 
9280
    The :term:`2to3` tool will automatically adapt imports when converting
 
9281
    your sources to 3.0.
 
9282
 
 
9283
+**Source code:** :source:`Lib/urlparse.py`
 
9284
+
 
9285
+--------------
 
9286
 
 
9287
 This module defines a standard interface to break Uniform Resource Locator (URL)
 
9288
 strings up in components (addressing scheme, network location, path etc.), to
 
9289
@@ -33,11 +36,6 @@
 
9290
 .. versionadded:: 2.5
 
9291
    Support for the ``sftp`` and ``sips`` schemes.
 
9292
 
 
9293
-.. seealso::
 
9294
-
 
9295
-   Latest version of the `urlparse module Python source code
 
9296
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/urlparse.py?view=markup>`_
 
9297
-
 
9298
 The :mod:`urlparse` module defines the following functions:
 
9299
 
 
9300
 
 
9301
diff -r 8527427914a2 Doc/library/userdict.rst
 
9302
--- a/Doc/library/userdict.rst
 
9303
+++ b/Doc/library/userdict.rst
 
9304
@@ -1,4 +1,3 @@
 
9305
-
 
9306
 :mod:`UserDict` --- Class wrapper for dictionary objects
 
9307
 ========================================================
 
9308
 
 
9309
@@ -6,6 +5,10 @@
 
9310
    :synopsis: Class wrapper for dictionary objects.
 
9311
 
 
9312
 
 
9313
+**Source code:** :source:`Lib/UserDict.py`
 
9314
+
 
9315
+--------------
 
9316
+
 
9317
 The module defines a mixin,  :class:`DictMixin`, defining all dictionary methods
 
9318
 for classes that already have a minimum mapping interface.  This greatly
 
9319
 simplifies writing classes that need to be substitutable for dictionaries (such
 
9320
@@ -19,11 +22,6 @@
 
9321
 sub-classes that obtained new behaviors by overriding existing methods or adding
 
9322
 new ones.
 
9323
 
 
9324
-.. seealso::
 
9325
-
 
9326
-   Latest version of the `UserDict Python source code
 
9327
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/UserDict.py?view=markup>`_
 
9328
-
 
9329
 The :mod:`UserDict` module defines the :class:`UserDict` class and
 
9330
 :class:`DictMixin`:
 
9331
 
 
9332
diff -r 8527427914a2 Doc/library/uu.rst
 
9333
--- a/Doc/library/uu.rst
 
9334
+++ b/Doc/library/uu.rst
 
9335
@@ -1,4 +1,3 @@
 
9336
-
 
9337
 :mod:`uu` --- Encode and decode uuencode files
 
9338
 ==============================================
 
9339
 
 
9340
@@ -6,6 +5,9 @@
 
9341
    :synopsis: Encode and decode files in uuencode format.
 
9342
 .. moduleauthor:: Lance Ellinghouse
 
9343
 
 
9344
+**Source code:** :source:`Lib/uu.py`
 
9345
+
 
9346
+--------------
 
9347
 
 
9348
 This module encodes and decodes files in uuencode format, allowing arbitrary
 
9349
 binary data to be transferred over ASCII-only connections. Wherever a file
 
9350
@@ -22,11 +24,6 @@
 
9351
 
 
9352
 This code was contributed by Lance Ellinghouse, and modified by Jack Jansen.
 
9353
 
 
9354
-.. seealso::
 
9355
-
 
9356
-   Latest version of the `uu module Python source code
 
9357
-   <http://svn.python.org/view/python/branches/release27-maint/Lib/uu.py?view=markup>`_
 
9358
-
 
9359
 The :mod:`uu` module defines the following functions:
 
9360
 
 
9361
 
 
9362
@@ -62,4 +59,3 @@
 
9363
 
 
9364
    Module :mod:`binascii`
 
9365
       Support module containing ASCII-to-binary and binary-to-ASCII conversions.
 
9366
-
3126
9367
diff -r 8527427914a2 Doc/library/warnings.rst
3127
9368
--- a/Doc/library/warnings.rst
3128
9369
+++ b/Doc/library/warnings.rst
3129
 
@@ -39,6 +39,10 @@
 
9370
@@ -9,6 +9,10 @@
 
9371
 
 
9372
 .. versionadded:: 2.1
 
9373
 
 
9374
+**Source code:** :source:`Lib/warnings.py`
 
9375
+
 
9376
+--------------
 
9377
+
 
9378
 Warning messages are typically issued in situations where it is useful to alert
 
9379
 the user of some condition in a program, where that condition (normally) doesn't
 
9380
 warrant raising an exception and terminating the program.  For example, one
 
9381
@@ -39,6 +43,10 @@
3130
9382
 message by calling :func:`formatwarning`, which is also available for use by
3131
9383
 custom implementations.
3132
9384
 
3137
9389
 
3138
9390
 .. _warning-categories:
3139
9391
 
 
9392
diff -r 8527427914a2 Doc/library/wave.rst
 
9393
--- a/Doc/library/wave.rst
 
9394
+++ b/Doc/library/wave.rst
 
9395
@@ -6,6 +6,10 @@
 
9396
 .. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
 
9397
 .. Documentations stolen from comments in file.
 
9398
 
 
9399
+**Source code:** :source:`Lib/wave.py`
 
9400
+
 
9401
+--------------
 
9402
+
 
9403
 The :mod:`wave` module provides a convenient interface to the WAV sound format.
 
9404
 It does not support compression/decompression, but it does support mono/stereo.
 
9405
 
 
9406
diff -r 8527427914a2 Doc/library/weakref.rst
 
9407
--- a/Doc/library/weakref.rst
 
9408
+++ b/Doc/library/weakref.rst
 
9409
@@ -11,6 +11,10 @@
 
9410
 
 
9411
 .. versionadded:: 2.1
 
9412
 
 
9413
+**Source code:** :source:`Lib/weakref.py`
 
9414
+
 
9415
+--------------
 
9416
+
 
9417
 The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
 
9418
 references` to objects.
 
9419
 
 
9420
diff -r 8527427914a2 Doc/library/webbrowser.rst
 
9421
--- a/Doc/library/webbrowser.rst
 
9422
+++ b/Doc/library/webbrowser.rst
 
9423
@@ -1,4 +1,3 @@
 
9424
-
 
9425
 :mod:`webbrowser` --- Convenient Web-browser controller
 
9426
 =======================================================
 
9427
 
 
9428
@@ -7,6 +6,9 @@
 
9429
 .. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
9430
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
 
9431
 
 
9432
+**Source code:** :source:`Lib/webbrowser.py`
 
9433
+
 
9434
+--------------
 
9435
 
 
9436
 The :mod:`webbrowser` module provides a high-level interface to allow displaying
 
9437
 Web-based documents to users. Under most circumstances, simply calling the
3140
9438
diff -r 8527427914a2 Doc/library/xdrlib.rst
3141
9439
--- a/Doc/library/xdrlib.rst
3142
9440
+++ b/Doc/library/xdrlib.rst
3143
 
@@ -257,7 +257,7 @@
 
9441
@@ -1,4 +1,3 @@
 
9442
-
 
9443
 :mod:`xdrlib` --- Encode and decode XDR data
 
9444
 ============================================
 
9445
 
 
9446
@@ -10,6 +9,10 @@
 
9447
    single: XDR
 
9448
    single: External Data Representation
 
9449
 
 
9450
+**Source code:** :source:`Lib/xdrlib.py`
 
9451
+
 
9452
+--------------
 
9453
+
 
9454
 The :mod:`xdrlib` module supports the External Data Representation Standard as
 
9455
 described in :rfc:`1014`, written by Sun Microsystems, Inc. June 1987.  It
 
9456
 supports most of the data types described in the RFC.
 
9457
@@ -257,7 +260,7 @@
3144
9458
 
3145
9459
 .. exception:: Error
3146
9460
 
3149
9463
    :attr:`msg` containing the description of the error.
3150
9464
 
3151
9465
 
 
9466
diff -r 8527427914a2 Doc/library/xml.dom.minidom.rst
 
9467
--- a/Doc/library/xml.dom.minidom.rst
 
9468
+++ b/Doc/library/xml.dom.minidom.rst
 
9469
@@ -1,4 +1,3 @@
 
9470
-
 
9471
 :mod:`xml.dom.minidom` --- Lightweight DOM implementation
 
9472
 =========================================================
 
9473
 
 
9474
@@ -11,6 +10,10 @@
 
9475
 
 
9476
 .. versionadded:: 2.0
 
9477
 
 
9478
+**Source code:** :source:`Lib/xml/dom/minidom.py`
 
9479
+
 
9480
+--------------
 
9481
+
 
9482
 :mod:`xml.dom.minidom` is a light-weight implementation of the Document Object
 
9483
 Model interface.  It is intended to be simpler than the full DOM and also
 
9484
 significantly smaller.
 
9485
diff -r 8527427914a2 Doc/library/xml.dom.pulldom.rst
 
9486
--- a/Doc/library/xml.dom.pulldom.rst
 
9487
+++ b/Doc/library/xml.dom.pulldom.rst
 
9488
@@ -1,4 +1,3 @@
 
9489
-
 
9490
 :mod:`xml.dom.pulldom` --- Support for building partial DOM trees
 
9491
 =================================================================
 
9492
 
 
9493
@@ -9,6 +8,10 @@
 
9494
 
 
9495
 .. versionadded:: 2.0
 
9496
 
 
9497
+**Source code:** :source:`Lib/xml/dom/pulldom.py`
 
9498
+
 
9499
+--------------
 
9500
+
 
9501
 :mod:`xml.dom.pulldom` allows building only selected portions of a Document
 
9502
 Object Model representation of a document from SAX events.
 
9503
 
 
9504
diff -r 8527427914a2 Doc/library/xml.etree.elementtree.rst
 
9505
--- a/Doc/library/xml.etree.elementtree.rst
 
9506
+++ b/Doc/library/xml.etree.elementtree.rst
 
9507
@@ -1,4 +1,3 @@
 
9508
-
 
9509
 :mod:`xml.etree.ElementTree` --- The ElementTree XML API
 
9510
 ========================================================
 
9511
 
 
9512
@@ -9,6 +8,10 @@
 
9513
 
 
9514
 .. versionadded:: 2.5
 
9515
 
 
9516
+**Source code:** :source:`Lib/xml/etree/ElementTree.py`
 
9517
+
 
9518
+--------------
 
9519
+
 
9520
 The :class:`Element` type is a flexible container object, designed to store
 
9521
 hierarchical data structures in memory.  The type can be described as a cross
 
9522
 between a list and a dictionary.
 
9523
@@ -333,6 +336,8 @@
 
9524
       elements whose tag equals *tag* are returned from the iterator.  If the
 
9525
       tree structure is modified during iteration, the result is undefined.
 
9526
 
 
9527
+      .. versionadded:: 2.7
 
9528
+
 
9529
 
 
9530
    .. method:: iterfind(match)
 
9531
 
3152
9532
diff -r 8527427914a2 Doc/library/xmlrpclib.rst
3153
9533
--- a/Doc/library/xmlrpclib.rst
3154
9534
+++ b/Doc/library/xmlrpclib.rst
3155
 
@@ -148,7 +148,7 @@
 
9535
@@ -17,6 +17,10 @@
 
9536
 
 
9537
 .. versionadded:: 2.2
 
9538
 
 
9539
+**Source code:** :source:`Lib/xmlrpclib.py`
 
9540
+
 
9541
+--------------
 
9542
+
 
9543
 XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
 
9544
 transport.  With it, a client can call methods with parameters on a remote
 
9545
 server (the server is named by a URI) and get back structured data.  This module
 
9546
@@ -148,7 +152,7 @@
3156
9547
 :class:`Fault` or :class:`ProtocolError` object indicating an error.
3157
9548
 
3158
9549
 Servers that support the XML introspection API support some common methods
3161
9552
 
3162
9553
 
3163
9554
 .. method:: ServerProxy.system.listMethods()
3164
 
@@ -341,7 +341,7 @@
 
9555
@@ -341,7 +345,7 @@
3165
9556
 -------------
3166
9557
 
3167
9558
 A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
3170
9561
 
3171
9562
 
3172
9563
 .. attribute:: Fault.faultCode
3173
 
@@ -390,7 +390,7 @@
 
9564
@@ -390,7 +394,7 @@
3174
9565
 
3175
9566
 A :class:`ProtocolError` object describes a protocol error in the underlying
3176
9567
 transport layer (such as a 404 'not found' error if the server named by the URI
3179
9570
 
3180
9571
 
3181
9572
 .. attribute:: ProtocolError.url
 
9573
@@ -435,8 +439,8 @@
 
9574
 
 
9575
 .. versionadded:: 2.4
 
9576
 
 
9577
-In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to
 
9578
-encapsulate multiple calls to a remote server into a single request.
 
9579
+The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
 
9580
+remote server into a single request [#]_.
 
9581
 
 
9582
 
 
9583
 .. class:: MultiCall(server)
 
9584
@@ -577,3 +581,10 @@
 
9585
 See :ref:`simplexmlrpcserver-example`.
 
9586
 
 
9587
 
 
9588
+.. rubric:: Footnotes
 
9589
+
 
9590
+.. [#] This approach has been first presented in `a discussion on xmlrpc.com
 
9591
+   <http://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
 
9592
+.. the link now points to webarchive since the one at
 
9593
+.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
 
9594
+.. doesn't reply)
 
9595
diff -r 8527427914a2 Doc/library/zipfile.rst
 
9596
--- a/Doc/library/zipfile.rst
 
9597
+++ b/Doc/library/zipfile.rst
 
9598
@@ -1,4 +1,3 @@
 
9599
-
 
9600
 :mod:`zipfile` --- Work with ZIP archives
 
9601
 =========================================
 
9602
 
 
9603
@@ -9,6 +8,10 @@
 
9604
 
 
9605
 .. versionadded:: 1.6
 
9606
 
 
9607
+**Source code:** :source:`Lib/zipfile.py`
 
9608
+
 
9609
+--------------
 
9610
+
 
9611
 The ZIP file format is a common archive and compression standard. This module
 
9612
 provides tools to create, read, write, append, and list a ZIP file.  Any
 
9613
 advanced use of this module will require an understanding of the format, as
 
9614
@@ -385,7 +388,7 @@
 
9615
    +-------+--------------------------+
 
9616
    | Index | Value                    |
 
9617
    +=======+==========================+
 
9618
-   | ``0`` | Year                     |
 
9619
+   | ``0`` | Year (>= 1980)           |
 
9620
    +-------+--------------------------+
 
9621
    | ``1`` | Month (one-based)        |
 
9622
    +-------+--------------------------+
 
9623
@@ -398,6 +401,10 @@
 
9624
    | ``5`` | Seconds (zero-based)     |
 
9625
    +-------+--------------------------+
 
9626
 
 
9627
+   .. note::
 
9628
+
 
9629
+      The ZIP file format does not support timestamps before 1980.
 
9630
+
 
9631
 
 
9632
 .. attribute:: ZipInfo.compress_type
 
9633
 
3182
9634
diff -r 8527427914a2 Doc/library/zipimport.rst
3183
9635
--- a/Doc/library/zipimport.rst
3184
9636
+++ b/Doc/library/zipimport.rst
3255
9707
 
3256
9708
    Copyright (c) 1996-2008  Red Hat, Inc and others.
3257
9709
 
 
9710
@@ -947,7 +917,7 @@
 
9711
 ----
 
9712
 
 
9713
 The :mod:`zlib` extension is built using an included copy of the zlib
 
9714
-sources unless the zlib version found on the system is too old to be
 
9715
+sources if the zlib version found on the system is too old to be
 
9716
 used for the build::
 
9717
 
 
9718
   Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
3258
9719
diff -r 8527427914a2 Doc/reference/compound_stmts.rst
3259
9720
--- a/Doc/reference/compound_stmts.rst
3260
9721
+++ b/Doc/reference/compound_stmts.rst
 
9722
@@ -470,7 +470,7 @@
 
9723
 
 
9724
 **Default parameter values are evaluated when the function definition is
 
9725
 executed.**  This means that the expression is evaluated once, when the function
 
9726
-is defined, and that that same "pre-computed" value is used for each call.  This
 
9727
+is defined, and that the same "pre-computed" value is used for each call.  This
 
9728
 is especially important to understand when a default parameter is a mutable
 
9729
 object, such as a list or a dictionary: if the function modifies the object
 
9730
 (e.g. by appending an item to a list), the default value is in effect modified.
3261
9731
@@ -562,8 +562,9 @@
3262
9732
 
3263
9733
 .. rubric:: Footnotes
3285
9755
diff -r 8527427914a2 Doc/reference/expressions.rst
3286
9756
--- a/Doc/reference/expressions.rst
3287
9757
+++ b/Doc/reference/expressions.rst
 
9758
@@ -347,7 +347,7 @@
 
9759
 quotes:
 
9760
 
 
9761
 .. productionlist::
 
9762
-   string_conversion: "'" `expression_list` "'"
 
9763
+   string_conversion: "`" `expression_list` "`"
 
9764
 
 
9765
 A string conversion evaluates the contained expression list and converts the
 
9766
 resulting object into a string according to rules specific to its type.
3288
9767
@@ -735,12 +735,15 @@
3289
9768
 and the argument values as corresponding values), or a (new) empty dictionary if
3290
9769
 there were no excess keyword arguments.
3316
9795
 If the syntax ``**expression`` appears in the function call, ``expression`` must
3317
9796
 evaluate to a mapping, the contents of which are treated as additional keyword
3318
9797
 arguments.  In the case of a keyword appearing in both ``expression`` and as an
 
9798
diff -r 8527427914a2 Doc/tools/sphinxext/layout.html
 
9799
--- a/Doc/tools/sphinxext/layout.html
 
9800
+++ b/Doc/tools/sphinxext/layout.html
 
9801
@@ -6,6 +6,7 @@
 
9802
 {% endblock %}
 
9803
 {% block extrahead %}
 
9804
     <link rel="shortcut icon" type="image/png" href="{{ pathto('_static/py.png', 1) }}" />
 
9805
+    <script type="text/javascript" src="{{ pathto('_static/copybutton.js', 1) }}"></script>
 
9806
 {{ super() }}
 
9807
 {% endblock %}
 
9808
 {% block footer %}
 
9809
diff -r 8527427914a2 Doc/tools/sphinxext/pyspecific.py
 
9810
--- a/Doc/tools/sphinxext/pyspecific.py
 
9811
+++ b/Doc/tools/sphinxext/pyspecific.py
 
9812
@@ -5,11 +5,12 @@
 
9813
 
 
9814
     Sphinx extension with Python doc-specific markup.
 
9815
 
 
9816
-    :copyright: 2008, 2009 by Georg Brandl.
 
9817
+    :copyright: 2008-2011 by Georg Brandl.
 
9818
     :license: Python license.
 
9819
 """
 
9820
 
 
9821
 ISSUE_URI = 'http://bugs.python.org/issue%s'
 
9822
+SOURCE_URI = 'http://hg.python.org/cpython/file/2.7/%s'
 
9823
 
 
9824
 from docutils import nodes, utils
 
9825
 
 
9826
@@ -44,6 +45,14 @@
 
9827
     return [refnode], []
 
9828
 
 
9829
 
 
9830
+# Support for linking to Python source files easily
 
9831
+
 
9832
+def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
 
9833
+    path = utils.unescape(text)
 
9834
+    refnode = nodes.reference(path, path, refuri=SOURCE_URI % path)
 
9835
+    return [refnode], []
 
9836
+
 
9837
+
 
9838
 # Support for marking up implementation details
 
9839
 
 
9840
 from sphinx.util.compat import Directive
 
9841
@@ -168,6 +177,7 @@
 
9842
 
 
9843
 def setup(app):
 
9844
     app.add_role('issue', issue_role)
 
9845
+    app.add_role('source', source_role)
 
9846
     app.add_directive('impl-detail', ImplementationDetail)
 
9847
     app.add_builder(PydocTopicsBuilder)
 
9848
     app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
 
9849
diff -r 8527427914a2 Doc/tools/sphinxext/static/copybutton.js
 
9850
--- /dev/null
 
9851
+++ b/Doc/tools/sphinxext/static/copybutton.js
 
9852
@@ -0,0 +1,56 @@
 
9853
+$(document).ready(function() {
 
9854
+    /* Add a [>>>] button on the top-right corner of code samples to hide
 
9855
+     * the >>> and ... prompts and the output and thus make the code
 
9856
+     * copyable. */
 
9857
+    var div = $('.highlight-python .highlight,' +
 
9858
+                '.highlight-python3 .highlight')
 
9859
+    var pre = div.find('pre');
 
9860
+
 
9861
+    // get the styles from the current theme
 
9862
+    pre.parent().parent().css('position', 'relative');
 
9863
+    var hide_text = 'Hide the prompts and ouput';
 
9864
+    var show_text = 'Show the prompts and ouput';
 
9865
+    var border_width = pre.css('border-top-width');
 
9866
+    var border_style = pre.css('border-top-style');
 
9867
+    var border_color = pre.css('border-top-color');
 
9868
+    var button_styles = {
 
9869
+        'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0',
 
9870
+        'border-color': border_color, 'border-style': border_style,
 
9871
+        'border-width': border_width, 'color': border_color, 'text-size': '75%',
 
9872
+        'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em'
 
9873
+    }
 
9874
+
 
9875
+    // create and add the button to all the code blocks that contain >>>
 
9876
+    div.each(function(index) {
 
9877
+        var jthis = $(this);
 
9878
+        if (jthis.find('.gp').length > 0) {
 
9879
+            var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
 
9880
+            button.css(button_styles)
 
9881
+            button.attr('title', hide_text);
 
9882
+            jthis.prepend(button);
 
9883
+        }
 
9884
+        // tracebacks (.gt) contain bare text elements that need to be
 
9885
+        // wrapped in a span to work with .nextUntil() (see later)
 
9886
+        jthis.find('pre:has(.gt)').contents().filter(function() {
 
9887
+            return ((this.nodeType == 3) && (this.data.trim().length > 0));
 
9888
+        }).wrap('<span>');
 
9889
+    });
 
9890
+
 
9891
+    // define the behavior of the button when it's clicked
 
9892
+    $('.copybutton').toggle(
 
9893
+        function() {
 
9894
+            var button = $(this);
 
9895
+            button.parent().find('.go, .gp, .gt').hide();
 
9896
+            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
 
9897
+            button.css('text-decoration', 'line-through');
 
9898
+            button.attr('title', show_text);
 
9899
+        },
 
9900
+        function() {
 
9901
+            var button = $(this);
 
9902
+            button.parent().find('.go, .gp, .gt').show();
 
9903
+            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
 
9904
+            button.css('text-decoration', 'none');
 
9905
+            button.attr('title', hide_text);
 
9906
+        });
 
9907
+});
 
9908
+
3319
9909
diff -r 8527427914a2 Doc/tools/sphinxext/susp-ignored.csv
3320
9910
--- a/Doc/tools/sphinxext/susp-ignored.csv
3321
9911
+++ b/Doc/tools/sphinxext/susp-ignored.csv
3327
9917
 distutils/setupscript,,::,
3328
9918
 extending/embedding,,:numargs,"if(!PyArg_ParseTuple(args, "":numargs""))"
3329
9919
 extending/extending,,:set,"if (PyArg_ParseTuple(args, ""O:set_callback"", &temp)) {"
 
9920
@@ -222,6 +221,9 @@
 
9921
 whatsnew/2.7,862,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0"
 
9922
 whatsnew/2.7,,::,>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
 
9923
 whatsnew/2.7,,::,"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',"
 
9924
+howto/pyporting,75,::,# make sure to use :: Python *and* :: Python :: 3 so
 
9925
+howto/pyporting,75,::,"'Programming Language :: Python',"
 
9926
+howto/pyporting,75,::,'Programming Language :: Python :: 3'
 
9927
 documenting/markup,33,.. sectionauthor:,.. sectionauthor:: Guido van Rossum <guido@python.org>
 
9928
 documenting/markup,42,:mod,:mod:`parrot` -- Dead parrot access
 
9929
 documenting/markup,42,`,:mod:`parrot` -- Dead parrot access
3330
9930
diff -r 8527427914a2 Doc/tutorial/classes.rst
3331
9931
--- a/Doc/tutorial/classes.rst
3332
9932
+++ b/Doc/tutorial/classes.rst
3372
9972
 
3373
9973
 .. _tut-pass:
3374
9974
 
 
9975
diff -r 8527427914a2 Doc/tutorial/datastructures.rst
 
9976
--- a/Doc/tutorial/datastructures.rst
 
9977
+++ b/Doc/tutorial/datastructures.rst
 
9978
@@ -170,8 +170,8 @@
 
9979
 ``filter(function, sequence)`` returns a sequence consisting of those items from
 
9980
 the sequence for which ``function(item)`` is true. If *sequence* is a
 
9981
 :class:`string` or :class:`tuple`, the result will be of the same type;
 
9982
-otherwise, it is always a :class:`list`. For example, to compute primes up
 
9983
-to 25::
 
9984
+otherwise, it is always a :class:`list`. For example, to compute a sequence of
 
9985
+numbers not divisible by 2 and 3::
 
9986
 
 
9987
    >>> def f(x): return x % 2 != 0 and x % 3 != 0
 
9988
    ...
 
9989
diff -r 8527427914a2 Doc/tutorial/interactive.rst
 
9990
--- a/Doc/tutorial/interactive.rst
 
9991
+++ b/Doc/tutorial/interactive.rst
 
9992
@@ -156,17 +156,18 @@
 
9993
 quotes, etc., would also be useful.
 
9994
 
 
9995
 One alternative enhanced interactive interpreter that has been around for quite
 
9996
-some time is `IPython`_, which features tab completion, object exploration and
 
9997
+some time is IPython_, which features tab completion, object exploration and
 
9998
 advanced history management.  It can also be thoroughly customized and embedded
 
9999
 into other applications.  Another similar enhanced interactive environment is
 
10000
-`bpython`_.
 
10001
+bpython_.
 
10002
 
 
10003
 
 
10004
 .. rubric:: Footnotes
 
10005
 
 
10006
 .. [#] Python will execute the contents of a file identified by the
 
10007
    :envvar:`PYTHONSTARTUP` environment variable when you start an interactive
 
10008
-   interpreter.
 
10009
+   interpreter.  To customize Python even for non-interactive mode, see
 
10010
+   :ref:`tut-customize`.
 
10011
 
 
10012
 
 
10013
 .. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
3375
10014
diff -r 8527427914a2 Doc/tutorial/interpreter.rst
3376
10015
--- a/Doc/tutorial/interpreter.rst
3377
10016
+++ b/Doc/tutorial/interpreter.rst
3378
 
@@ -166,6 +166,8 @@
 
10017
@@ -60,8 +60,7 @@
 
10018
 
 
10019
 When a script file is used, it is sometimes useful to be able to run the script
 
10020
 and enter interactive mode afterwards.  This can be done by passing :option:`-i`
 
10021
-before the script.  (This does not work if the script is read from standard
 
10022
-input, for the same reason as explained in the previous paragraph.)
 
10023
+before the script.
 
10024
 
 
10025
 
 
10026
 .. _tut-argpassing:
 
10027
@@ -166,6 +165,8 @@
3379
10028
 suppressed.
3380
10029
 
3381
10030
 
3384
10033
 Source Code Encoding
3385
10034
 --------------------
3386
10035
 
 
10036
@@ -240,7 +241,29 @@
 
10037
        execfile(filename)
 
10038
 
 
10039
 
 
10040
+.. _tut-customize:
 
10041
+
 
10042
+The Customization Modules
 
10043
+-------------------------
 
10044
+
 
10045
+Python provides two hooks to let you customize it: :mod:`sitecustomize` and
 
10046
+:mod:`usercustomize`.  To see how it works, you need first to find the location
 
10047
+of your user site-packages directory.  Start Python and run this code:
 
10048
+
 
10049
+   >>> import site
 
10050
+   >>> site.getusersitepackages()
 
10051
+   '/home/user/.local/lib/python3.2/site-packages'
 
10052
+
 
10053
+Now you can create a file named :file:`usercustomize.py` in that directory and
 
10054
+put anything you want in it.  It will affect every invocation of Python, unless
 
10055
+it is started with the :option:`-s` option to disable the automatic import.
 
10056
+
 
10057
+:mod:`sitecustomize` works in the same way, but is typically created by an
 
10058
+administrator of the computer in the global site-packages directory, and is
 
10059
+imported before :mod:`usercustomize`.  See the documentation of the :mod:`site`
 
10060
+module for more details.
 
10061
+
 
10062
+
 
10063
 .. rubric:: Footnotes
 
10064
 
 
10065
 .. [#] A problem with the GNU Readline package may prevent this.
 
10066
-
 
10067
diff -r 8527427914a2 Doc/tutorial/introduction.rst
 
10068
--- a/Doc/tutorial/introduction.rst
 
10069
+++ b/Doc/tutorial/introduction.rst
 
10070
@@ -240,13 +240,6 @@
 
10071
    This is a rather long string containing\n\
 
10072
    several lines of text much as you would do in C.
 
10073
 
 
10074
-The interpreter prints the result of string operations in the same way as they
 
10075
-are typed for input: inside quotes, and with quotes and other funny characters
 
10076
-escaped by backslashes, to show the precise value.  The string is enclosed in
 
10077
-double quotes if the string contains a single quote and no double quotes, else
 
10078
-it's enclosed in single quotes.  (The :keyword:`print` statement, described
 
10079
-later, can be used to write strings without quotes or escapes.)
 
10080
-
 
10081
 Strings can be concatenated (glued together) with the ``+`` operator, and
 
10082
 repeated with ``*``::
 
10083
 
3387
10084
diff -r 8527427914a2 Doc/tutorial/modules.rst
3388
10085
--- a/Doc/tutorial/modules.rst
3389
10086
+++ b/Doc/tutorial/modules.rst
3412
10109
diff -r 8527427914a2 Doc/using/cmdline.rst
3413
10110
--- a/Doc/using/cmdline.rst
3414
10111
+++ b/Doc/using/cmdline.rst
3415
 
@@ -569,7 +569,7 @@
 
10112
@@ -255,7 +255,8 @@
 
10113
 
 
10114
 .. cmdoption:: -s
 
10115
 
 
10116
-   Don't add user site directory to sys.path
 
10117
+   Don't add the :data:`user site-packages directory <site.USER_SITE>` to
 
10118
+   :data:`sys.path`.
 
10119
 
 
10120
    .. versionadded:: 2.6
 
10121
 
 
10122
@@ -532,7 +533,8 @@
 
10123
 
 
10124
 .. envvar:: PYTHONNOUSERSITE
 
10125
 
 
10126
-   If this is set, Python won't add the user site directory to sys.path
 
10127
+   If this is set, Python won't add the :data:`user site-packages directory
 
10128
+   <site.USER_SITE>` to :data:`sys.path`.
 
10129
 
 
10130
    .. versionadded:: 2.6
 
10131
 
 
10132
@@ -543,7 +545,10 @@
 
10133
 
 
10134
 .. envvar:: PYTHONUSERBASE
 
10135
 
 
10136
-   Sets the base directory for the user site directory
 
10137
+   Defines the :data:`user base directory <site.USER_BASE>`, which is used to
 
10138
+   compute the path of the :data:`user site-packages directory <site.USER_SITE>`
 
10139
+   and :ref:`Distutils installation paths <inst-alt-install-user>` for ``python
 
10140
+   setup.py install --user``.
 
10141
 
 
10142
    .. versionadded:: 2.6
 
10143
 
 
10144
@@ -569,7 +574,7 @@
3416
10145
 ~~~~~~~~~~~~~~~~~~~~
3417
10146
 
3418
10147
 Setting these variables only has an effect in a debug build of Python, that is,
3421
10150
 
3422
10151
 .. envvar:: PYTHONTHREADDEBUG
3423
10152
 
 
10153
diff -r 8527427914a2 Doc/using/unix.rst
 
10154
--- a/Doc/using/unix.rst
 
10155
+++ b/Doc/using/unix.rst
 
10156
@@ -1,4 +1,4 @@
 
10157
-.. highlightlang:: none
 
10158
+.. highlightlang:: sh
 
10159
 
 
10160
 .. _using-on-unix:
 
10161
 
 
10162
@@ -55,8 +55,8 @@
 
10163
 On OpenSolaris
 
10164
 --------------
 
10165
 
 
10166
-To install the newest Python versions on OpenSolaris, install blastwave
 
10167
-(http://www.blastwave.org/howto.html) and type "pkg_get -i python" at the
 
10168
+To install the newest Python versions on OpenSolaris, install `blastwave
 
10169
+<http://www.blastwave.org/howto.html>`_ and type ``pkg_get -i python`` at the
 
10170
 prompt.
 
10171
 
 
10172
 
 
10173
@@ -65,17 +65,18 @@
 
10174
 
 
10175
 If you want to compile CPython yourself, first thing you should do is get the
 
10176
 `source <http://python.org/download/source/>`_. You can download either the
 
10177
-latest release's source or just grab a fresh `checkout
 
10178
-<http://www.python.org/dev/faq/#how-do-i-get-a-checkout-of-the-repository-read-only-and-read-write>`_.
 
10179
+latest release's source or just grab a fresh `clone
 
10180
+<http://docs.python.org/devguide/setup#getting-the-source-code>`_.  (If you want
 
10181
+to contribute patches, you will need a clone.)
 
10182
 
 
10183
-The build process consists the usual ::
 
10184
+The build process consists in the usual ::
 
10185
 
 
10186
    ./configure
 
10187
    make
 
10188
    make install
 
10189
 
 
10190
 invocations. Configuration options and caveats for specific Unix platforms are
 
10191
-extensively documented in the :file:`README` file in the root of the Python
 
10192
+extensively documented in the :source:`README` file in the root of the Python
 
10193
 source tree.
 
10194
 
 
10195
 .. warning::
 
10196
diff -r 8527427914a2 Doc/using/windows.rst
 
10197
--- a/Doc/using/windows.rst
 
10198
+++ b/Doc/using/windows.rst
 
10199
@@ -47,9 +47,9 @@
 
10200
       "7 Minutes to "Hello World!""
 
10201
       by Richard Dooling, 2006
 
10202
 
 
10203
-   `Installing on Windows <http://diveintopython.org/installing_python/windows.html>`_
 
10204
+   `Installing on Windows <http://diveintopython.net/installing_python/windows.html>`_
 
10205
       in "`Dive into Python: Python from novice to pro
 
10206
-      <http://diveintopython.org/index.html>`_"
 
10207
+      <http://diveintopython.net/index.html>`_"
 
10208
       by Mark Pilgrim, 2004,
 
10209
       ISBN 1-59059-356-1
 
10210
 
 
10211
@@ -292,7 +292,7 @@
 
10212
 If you want to compile CPython yourself, first thing you should do is get the
 
10213
 `source <http://python.org/download/source/>`_. You can download either the
 
10214
 latest release's source or just grab a fresh `checkout
 
10215
-<http://www.python.org/dev/faq/#how-do-i-get-a-checkout-of-the-repository-read-only-and-read-write>`_.
 
10216
+<http://docs.python.org/devguide/setup#checking-out-the-code>`_.
 
10217
 
 
10218
 For Microsoft Visual C++, which is the compiler with which official Python
 
10219
 releases are built, the source tree contains solutions/project files.  View the
 
10220
diff -r 8527427914a2 Doc/whatsnew/2.4.rst
 
10221
--- a/Doc/whatsnew/2.4.rst
 
10222
+++ b/Doc/whatsnew/2.4.rst
 
10223
@@ -947,7 +947,7 @@
 
10224
   :meth:`__len__` method.  (Contributed by Raymond Hettinger.)
 
10225
 
 
10226
 * The methods :meth:`list.__getitem__`, :meth:`dict.__getitem__`, and
 
10227
-  :meth:`dict.__contains__` are are now implemented as :class:`method_descriptor`
 
10228
+  :meth:`dict.__contains__` are now implemented as :class:`method_descriptor`
 
10229
   objects rather than :class:`wrapper_descriptor` objects.  This form of  access
 
10230
   doubles their performance and makes them more suitable for use as arguments to
 
10231
   functionals: ``map(mydict.__getitem__, keylist)``. (Contributed by Raymond
3424
10232
diff -r 8527427914a2 Doc/whatsnew/2.5.rst
3425
10233
--- a/Doc/whatsnew/2.5.rst
3426
10234
+++ b/Doc/whatsnew/2.5.rst
3447
10255
   fixes a bug, but could possibly break certain :keyword:`import`
3448
10256
   statements that were only working by accident.  (Fixed by Meador Inge;
3449
10257
   :issue:`7902`.)
 
10258
@@ -1946,7 +1946,7 @@
 
10259
 version 1.3.  Some of the new features are:
 
10260
 
 
10261
 * The various parsing functions now take a *parser* keyword argument
 
10262
-  giving an :class:`XMLParser` instance that will
 
10263
+  giving an :class:`~xml.etree.ElementTree.XMLParser` instance that will
 
10264
   be used.  This makes it possible to override the file's internal encoding::
 
10265
 
 
10266
     p = ET.XMLParser(encoding='utf-8')
 
10267
@@ -1958,8 +1958,8 @@
 
10268
 
 
10269
 * ElementTree's code for converting trees to a string has been
 
10270
   significantly reworked, making it roughly twice as fast in many
 
10271
-  cases.  The :class:`ElementTree` :meth:`write` and :class:`Element`
 
10272
-  :meth:`write` methods now have a *method* parameter that can be
 
10273
+  cases.  The :meth:`ElementTree.write() <xml.etree.ElementTree.ElementTree.write>`
 
10274
+  and :meth:`Element.write` methods now have a *method* parameter that can be
 
10275
   "xml" (the default), "html", or "text".  HTML mode will output empty
 
10276
   elements as ``<empty></empty>`` instead of ``<empty/>``, and text
 
10277
   mode will skip over elements and only output the text chunks.  If
 
10278
@@ -1972,11 +1972,12 @@
 
10279
   declarations are now output on the root element, not scattered throughout
 
10280
   the resulting XML.  You can set the default namespace for a tree
 
10281
   by setting the :attr:`default_namespace` attribute and can
 
10282
-  register new prefixes with :meth:`register_namespace`.  In XML mode,
 
10283
+  register new prefixes with :meth:`~xml.etree.ElementTree.register_namespace`.  In XML mode,
 
10284
   you can use the true/false *xml_declaration* parameter to suppress the
 
10285
   XML declaration.
 
10286
 
 
10287
-* New :class:`Element` method: :meth:`extend` appends the items from a
 
10288
+* New :class:`~xml.etree.ElementTree.Element` method:
 
10289
+  :meth:`~xml.etree.ElementTree.Element.extend` appends the items from a
 
10290
   sequence to the element's children.  Elements themselves behave like
 
10291
   sequences, so it's easy to move children from one element to
 
10292
   another::
 
10293
@@ -1992,13 +1993,15 @@
 
10294
     # Outputs <root><item>1</item>...</root>
 
10295
     print ET.tostring(new)
 
10296
 
 
10297
-* New :class:`Element` method: :meth:`iter` yields the children of the
 
10298
+* New :class:`Element` method:
 
10299
+  :meth:`~xml.etree.ElementTree.Element.iter` yields the children of the
 
10300
   element as a generator.  It's also possible to write ``for child in
 
10301
   elem:`` to loop over an element's children.  The existing method
 
10302
   :meth:`getiterator` is now deprecated, as is :meth:`getchildren`
 
10303
   which constructs and returns a list of children.
 
10304
 
 
10305
-* New :class:`Element` method: :meth:`itertext` yields all chunks of
 
10306
+* New :class:`Element` method:
 
10307
+  :meth:`~xml.etree.ElementTree.Element.itertext` yields all chunks of
 
10308
   text that are descendants of the element.  For example::
 
10309
 
 
10310
     t = ET.XML("""<list>
 
10311
diff -r 8527427914a2 Include/fileobject.h
 
10312
--- a/Include/fileobject.h
 
10313
+++ b/Include/fileobject.h
 
10314
@@ -84,6 +84,13 @@
 
10315
 #define _PyVerify_fd(A) (1) /* dummy */
 
10316
 #endif
 
10317
 
 
10318
+/* A routine to check if a file descriptor can be select()-ed. */
 
10319
+#ifdef HAVE_SELECT
 
10320
+ #define _PyIsSelectable_fd(FD) (((FD) >= 0) && ((FD) < FD_SETSIZE))
 
10321
+#else
 
10322
+ #define _PyIsSelectable_fd(FD) (1)
 
10323
+#endif /* HAVE_SELECT */
 
10324
+
 
10325
 #ifdef __cplusplus
 
10326
 }
 
10327
 #endif
3450
10328
diff -r 8527427914a2 Include/patchlevel.h
3451
10329
--- a/Include/patchlevel.h
3452
10330
+++ b/Include/patchlevel.h
3459
10337
 /*--end constants--*/
3460
10338
 
3461
10339
 /* Subversion Revision number of this file (not of the repository). Empty
 
10340
diff -r 8527427914a2 Include/pyctype.h
 
10341
--- a/Include/pyctype.h
 
10342
+++ b/Include/pyctype.h
 
10343
@@ -9,7 +9,7 @@
 
10344
 #define PY_CTF_SPACE  0x08
 
10345
 #define PY_CTF_XDIGIT 0x10
 
10346
 
 
10347
-extern const unsigned int _Py_ctype_table[256];
 
10348
+PyAPI_DATA(const unsigned int) _Py_ctype_table[256];
 
10349
 
 
10350
 /* Unlike their C counterparts, the following macros are not meant to
 
10351
  * handle an int with any of the values [EOF, 0-UCHAR_MAX]. The argument
 
10352
@@ -22,8 +22,8 @@
 
10353
 #define Py_ISALNUM(c)  (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_ALNUM)
 
10354
 #define Py_ISSPACE(c)  (_Py_ctype_table[Py_CHARMASK(c)] & PY_CTF_SPACE)
 
10355
 
 
10356
-extern const unsigned char _Py_ctype_tolower[256];
 
10357
-extern const unsigned char _Py_ctype_toupper[256];
 
10358
+PyAPI_DATA(const unsigned char) _Py_ctype_tolower[256];
 
10359
+PyAPI_DATA(const unsigned char) _Py_ctype_toupper[256];
 
10360
 
 
10361
 #define Py_TOLOWER(c) (_Py_ctype_tolower[Py_CHARMASK(c)])
 
10362
 #define Py_TOUPPER(c) (_Py_ctype_toupper[Py_CHARMASK(c)])
3462
10363
diff -r 8527427914a2 Include/pystate.h
3463
10364
--- a/Include/pystate.h
3464
10365
+++ b/Include/pystate.h
3465
 
@@ -169,7 +169,7 @@
 
10366
@@ -111,7 +111,6 @@
 
10367
 PyAPI_FUNC(void) PyThreadState_Delete(PyThreadState *);
 
10368
 #ifdef WITH_THREAD
 
10369
 PyAPI_FUNC(void) PyThreadState_DeleteCurrent(void);
 
10370
-PyAPI_FUNC(void) _PyGILState_Reinit(void);
 
10371
 #endif
 
10372
 
 
10373
 PyAPI_FUNC(PyThreadState *) PyThreadState_Get(void);
 
10374
@@ -169,7 +168,7 @@
3466
10375
 
3467
10376
 /* Helper/diagnostic function - get the current thread state for
3468
10377
    this thread.  May return NULL if no GILState API has been used
3483
10392
             for key in mapping:
3484
10393
                 if key not in seen:
3485
10394
                     result.append(key)
 
10395
diff -r 8527427914a2 Lib/HTMLParser.py
 
10396
--- a/Lib/HTMLParser.py
 
10397
+++ b/Lib/HTMLParser.py
 
10398
@@ -14,7 +14,6 @@
 
10399
 # Regular expressions used for parsing
 
10400
 
 
10401
 interesting_normal = re.compile('[&<]')
 
10402
-interesting_cdata = re.compile(r'<(/|\Z)')
 
10403
 incomplete = re.compile('&[a-zA-Z#]')
 
10404
 
 
10405
 entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
 
10406
@@ -24,25 +23,28 @@
 
10407
 piclose = re.compile('>')
 
10408
 commentclose = re.compile(r'--\s*>')
 
10409
 tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
 
10410
+
 
10411
 attrfind = re.compile(
 
10412
-    r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
 
10413
-    r'(\'[^\']*\'|"[^"]*"|[^\s"\'=<>`]*))?')
 
10414
+    r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*'
 
10415
+    r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?')
 
10416
 
 
10417
 locatestarttagend = re.compile(r"""
 
10418
   <[a-zA-Z][-.a-zA-Z0-9:_]*          # tag name
 
10419
   (?:\s+                             # whitespace before attribute name
 
10420
-    (?:[a-zA-Z_][-.:a-zA-Z0-9_]*     # attribute name
 
10421
-      (?:\s*=\s*                     # value indicator
 
10422
+    (?:(?<=['"\s])[^\s/>][^\s/=>]*   # attribute name
 
10423
+      (?:\s*=+\s*                    # value indicator
 
10424
         (?:'[^']*'                   # LITA-enclosed value
 
10425
-          |\"[^\"]*\"                # LIT-enclosed value
 
10426
-          |[^'\">\s]+                # bare value
 
10427
+          |"[^"]*"                   # LIT-enclosed value
 
10428
+          |(?!['"])[^>\s]*           # bare value
 
10429
          )
 
10430
-       )?
 
10431
-     )
 
10432
-   )*
 
10433
+       )?\s*
 
10434
+     )*
 
10435
+   )?
 
10436
   \s*                                # trailing whitespace
 
10437
 """, re.VERBOSE)
 
10438
 endendtag = re.compile('>')
 
10439
+# the HTML 5 spec, section 8.1.2.2, doesn't allow spaces between
 
10440
+# </ and the tag name, so maybe this should be fixed
 
10441
 endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
 
10442
 
 
10443
 
 
10444
@@ -96,6 +98,7 @@
 
10445
         self.rawdata = ''
 
10446
         self.lasttag = '???'
 
10447
         self.interesting = interesting_normal
 
10448
+        self.cdata_elem = None
 
10449
         markupbase.ParserBase.reset(self)
 
10450
 
 
10451
     def feed(self, data):
 
10452
@@ -120,11 +123,13 @@
 
10453
         """Return full source of start tag: '<...>'."""
 
10454
         return self.__starttag_text
 
10455
 
 
10456
-    def set_cdata_mode(self):
 
10457
-        self.interesting = interesting_cdata
 
10458
+    def set_cdata_mode(self, elem):
 
10459
+        self.cdata_elem = elem.lower()
 
10460
+        self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
 
10461
 
 
10462
     def clear_cdata_mode(self):
 
10463
         self.interesting = interesting_normal
 
10464
+        self.cdata_elem = None
 
10465
 
 
10466
     # Internal -- handle data as far as reasonable.  May leave state
 
10467
     # and data to be processed by a subsequent call.  If 'end' is
 
10468
@@ -138,6 +143,8 @@
 
10469
             if match:
 
10470
                 j = match.start()
 
10471
             else:
 
10472
+                if self.cdata_elem:
 
10473
+                    break
 
10474
                 j = n
 
10475
             if i < j: self.handle_data(rawdata[i:j])
 
10476
             i = self.updatepos(i, j)
 
10477
@@ -206,7 +213,7 @@
 
10478
             else:
 
10479
                 assert 0, "interesting.search() lied"
 
10480
         # end while
 
10481
-        if end and i < n:
 
10482
+        if end and i < n and not self.cdata_elem:
 
10483
             self.handle_data(rawdata[i:n])
 
10484
             i = self.updatepos(i, n)
 
10485
         self.rawdata = rawdata[i:]
 
10486
@@ -249,6 +256,7 @@
 
10487
             elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
 
10488
                  attrvalue[:1] == '"' == attrvalue[-1:]:
 
10489
                 attrvalue = attrvalue[1:-1]
 
10490
+            if attrvalue:
 
10491
                 attrvalue = self.unescape(attrvalue)
 
10492
             attrs.append((attrname.lower(), attrvalue))
 
10493
             k = m.end()
 
10494
@@ -270,7 +278,7 @@
 
10495
         else:
 
10496
             self.handle_starttag(tag, attrs)
 
10497
             if tag in self.CDATA_CONTENT_ELEMENTS:
 
10498
-                self.set_cdata_mode()
 
10499
+                self.set_cdata_mode(tag)
 
10500
         return endpos
 
10501
 
 
10502
     # Internal -- check to see if we have a complete starttag; return end
 
10503
@@ -314,9 +322,18 @@
 
10504
         j = match.end()
 
10505
         match = endtagfind.match(rawdata, i) # </ + tag + >
 
10506
         if not match:
 
10507
+            if self.cdata_elem is not None:
 
10508
+                self.handle_data(rawdata[i:j])
 
10509
+                return j
 
10510
             self.error("bad end tag: %r" % (rawdata[i:j],))
 
10511
-        tag = match.group(1)
 
10512
-        self.handle_endtag(tag.lower())
 
10513
+
 
10514
+        elem = match.group(1).lower() # script or style
 
10515
+        if self.cdata_elem is not None:
 
10516
+            if elem != self.cdata_elem:
 
10517
+                self.handle_data(rawdata[i:j])
 
10518
+                return j
 
10519
+
 
10520
+        self.handle_endtag(elem)
 
10521
         self.clear_cdata_mode()
 
10522
         return j
 
10523
 
 
10524
diff -r 8527427914a2 Lib/SocketServer.py
 
10525
--- a/Lib/SocketServer.py
 
10526
+++ b/Lib/SocketServer.py
 
10527
@@ -82,7 +82,7 @@
 
10528
 data is stored externally (e.g. in the file system), a synchronous
 
10529
 class will essentially render the service "deaf" while one request is
 
10530
 being handled -- which may be for a very long time if a client is slow
 
10531
-to reqd all the data it has requested.  Here a threading or forking
 
10532
+to read all the data it has requested.  Here a threading or forking
 
10533
 server is appropriate.
 
10534
 
 
10535
 In some cases, it may be appropriate to process part of a request
 
10536
@@ -589,8 +589,7 @@
 
10537
         """Start a new thread to process the request."""
 
10538
         t = threading.Thread(target = self.process_request_thread,
 
10539
                              args = (request, client_address))
 
10540
-        if self.daemon_threads:
 
10541
-            t.setDaemon (1)
 
10542
+        t.daemon = self.daemon_threads
 
10543
         t.start()
 
10544
 
 
10545
 
 
10546
diff -r 8527427914a2 Lib/_pyio.py
 
10547
--- a/Lib/_pyio.py
 
10548
+++ b/Lib/_pyio.py
 
10549
@@ -8,6 +8,7 @@
 
10550
 import abc
 
10551
 import codecs
 
10552
 import warnings
 
10553
+import errno
 
10554
 # Import thread instead of threading to reduce startup cost
 
10555
 try:
 
10556
     from thread import allocate_lock as Lock
 
10557
@@ -720,8 +721,11 @@
 
10558
 
 
10559
     def close(self):
 
10560
         if self.raw is not None and not self.closed:
 
10561
-            self.flush()
 
10562
-            self.raw.close()
 
10563
+            try:
 
10564
+                # may raise BlockingIOError or BrokenPipeError etc
 
10565
+                self.flush()
 
10566
+            finally:
 
10567
+                self.raw.close()
 
10568
 
 
10569
     def detach(self):
 
10570
         if self.raw is None:
 
10571
@@ -1074,13 +1078,9 @@
 
10572
             # XXX we can implement some more tricks to try and avoid
 
10573
             # partial writes
 
10574
             if len(self._write_buf) > self.buffer_size:
 
10575
-                # We're full, so let's pre-flush the buffer
 
10576
-                try:
 
10577
-                    self._flush_unlocked()
 
10578
-                except BlockingIOError as e:
 
10579
-                    # We can't accept anything else.
 
10580
-                    # XXX Why not just let the exception pass through?
 
10581
-                    raise BlockingIOError(e.errno, e.strerror, 0)
 
10582
+                # We're full, so let's pre-flush the buffer.  (This may
 
10583
+                # raise BlockingIOError with characters_written == 0.)
 
10584
+                self._flush_unlocked()
 
10585
             before = len(self._write_buf)
 
10586
             self._write_buf.extend(b)
 
10587
             written = len(self._write_buf) - before
 
10588
@@ -1111,24 +1111,23 @@
 
10589
     def _flush_unlocked(self):
 
10590
         if self.closed:
 
10591
             raise ValueError("flush of closed file")
 
10592
-        written = 0
 
10593
-        try:
 
10594
-            while self._write_buf:
 
10595
-                try:
 
10596
-                    n = self.raw.write(self._write_buf)
 
10597
-                except IOError as e:
 
10598
-                    if e.errno != EINTR:
 
10599
-                        raise
 
10600
-                    continue
 
10601
-                if n > len(self._write_buf) or n < 0:
 
10602
-                    raise IOError("write() returned incorrect number of bytes")
 
10603
-                del self._write_buf[:n]
 
10604
-                written += n
 
10605
-        except BlockingIOError as e:
 
10606
-            n = e.characters_written
 
10607
+        while self._write_buf:
 
10608
+            try:
 
10609
+                n = self.raw.write(self._write_buf)
 
10610
+            except BlockingIOError:
 
10611
+                raise RuntimeError("self.raw should implement RawIOBase: it "
 
10612
+                                   "should not raise BlockingIOError")
 
10613
+            except IOError as e:
 
10614
+                if e.errno != EINTR:
 
10615
+                    raise
 
10616
+                continue
 
10617
+            if n is None:
 
10618
+                raise BlockingIOError(
 
10619
+                    errno.EAGAIN,
 
10620
+                    "write could not complete without blocking", 0)
 
10621
+            if n > len(self._write_buf) or n < 0:
 
10622
+                raise IOError("write() returned incorrect number of bytes")
 
10623
             del self._write_buf[:n]
 
10624
-            written += n
 
10625
-            raise BlockingIOError(e.errno, e.strerror, written)
 
10626
 
 
10627
     def tell(self):
 
10628
         return _BufferedIOMixin.tell(self) + len(self._write_buf)
3486
10629
diff -r 8527427914a2 Lib/asyncore.py
3487
10630
--- a/Lib/asyncore.py
3488
10631
+++ b/Lib/asyncore.py
3506
10649
                 flags |= select.POLLOUT
3507
10650
             if flags:
3508
10651
                 # Only check for exceptions if object was either readable
 
10652
diff -r 8527427914a2 Lib/cgi.py
 
10653
--- a/Lib/cgi.py
 
10654
+++ b/Lib/cgi.py
 
10655
@@ -293,7 +293,7 @@
 
10656
     while s[:1] == ';':
 
10657
         s = s[1:]
 
10658
         end = s.find(';')
 
10659
-        while end > 0 and s.count('"', 0, end) % 2:
 
10660
+        while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
 
10661
             end = s.find(';', end + 1)
 
10662
         if end < 0:
 
10663
             end = len(s)
3509
10664
diff -r 8527427914a2 Lib/collections.py
3510
10665
--- a/Lib/collections.py
3511
10666
+++ b/Lib/collections.py
3517
10672
         def _replace(_self, **kwds):
3518
10673
             'Return a new %(typename)s object replacing specified fields with new values'
3519
10674
             result = _self._make(map(kwds.pop, %(field_names)r, _self))
 
10675
diff -r 8527427914a2 Lib/compileall.py
 
10676
--- a/Lib/compileall.py
 
10677
+++ b/Lib/compileall.py
 
10678
@@ -1,4 +1,4 @@
 
10679
-"""Module/script to "compile" all .py files to .pyc (or .pyo) file.
 
10680
+"""Module/script to byte-compile all .py files to .pyc (or .pyo) files.
 
10681
 
 
10682
 When called as a script with arguments, this compiles the directories
 
10683
 given as arguments recursively; the -l option prevents it from
 
10684
@@ -26,8 +26,8 @@
 
10685
 
 
10686
     dir:       the directory to byte-compile
 
10687
     maxlevels: maximum recursion level (default 10)
 
10688
-    ddir:      if given, purported directory name (this is the
 
10689
-               directory name that will show up in error messages)
 
10690
+    ddir:      the directory that will be prepended to the path to the
 
10691
+               file as it is compiled into each byte-code file.
 
10692
     force:     if 1, force compilation, even if timestamps are up-to-date
 
10693
     quiet:     if 1, be quiet during compilation
 
10694
     """
 
10695
@@ -64,8 +64,8 @@
 
10696
     Arguments (only fullname is required):
 
10697
 
 
10698
     fullname:  the file to byte-compile
 
10699
-    ddir:      if given, purported directory name (this is the
 
10700
-               directory name that will show up in error messages)
 
10701
+    ddir:      if given, the directory name compiled in to the
 
10702
+               byte-code file.
 
10703
     force:     if 1, force compilation, even if timestamps are up-to-date
 
10704
     quiet:     if 1, be quiet during compilation
 
10705
     """
 
10706
@@ -157,14 +157,27 @@
 
10707
         print msg
 
10708
         print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
 
10709
               "[-x regexp] [-i list] [directory|file ...]"
 
10710
-        print "-l: don't recurse down"
 
10711
+        print
 
10712
+        print "arguments: zero or more file and directory names to compile; " \
 
10713
+              "if no arguments given, "
 
10714
+        print "           defaults to the equivalent of -l sys.path"
 
10715
+        print
 
10716
+        print "options:"
 
10717
+        print "-l: don't recurse into subdirectories"
 
10718
         print "-f: force rebuild even if timestamps are up-to-date"
 
10719
-        print "-q: quiet operation"
 
10720
-        print "-d destdir: purported directory name for error messages"
 
10721
-        print "   if no directory arguments, -l sys.path is assumed"
 
10722
-        print "-x regexp: skip files matching the regular expression regexp"
 
10723
-        print "   the regexp is searched for in the full path of the file"
 
10724
-        print "-i list: expand list with its content (file and directory names)"
 
10725
+        print "-q: output only error messages"
 
10726
+        print "-d destdir: directory to prepend to file paths for use in " \
 
10727
+              "compile-time tracebacks and in"
 
10728
+        print "            runtime tracebacks in cases where the source " \
 
10729
+              "file is unavailable"
 
10730
+        print "-x regexp: skip files matching the regular expression regexp; " \
 
10731
+              "the regexp is searched for"
 
10732
+        print "           in the full path of each file considered for " \
 
10733
+              "compilation"
 
10734
+        print "-i file: add all the files and directories listed in file to " \
 
10735
+              "the list considered for"
 
10736
+        print '         compilation; if "-", names are read from stdin'
 
10737
+
 
10738
         sys.exit(2)
 
10739
     maxlevels = 10
 
10740
     ddir = None
 
10741
@@ -205,7 +218,7 @@
 
10742
         else:
 
10743
             success = compile_path()
 
10744
     except KeyboardInterrupt:
 
10745
-        print "\n[interrupt]"
 
10746
+        print "\n[interrupted]"
 
10747
         success = 0
 
10748
     return success
 
10749
 
 
10750
diff -r 8527427914a2 Lib/cookielib.py
 
10751
--- a/Lib/cookielib.py
 
10752
+++ b/Lib/cookielib.py
 
10753
@@ -1014,7 +1014,7 @@
 
10754
                     (not erhn.startswith(".") and
 
10755
                      not ("."+erhn).endswith(domain))):
 
10756
                     _debug("   effective request-host %s (even with added "
 
10757
-                           "initial dot) does not end end with %s",
 
10758
+                           "initial dot) does not end with %s",
 
10759
                            erhn, domain)
 
10760
                     return False
 
10761
             if (cookie.version > 0 or
 
10762
diff -r 8527427914a2 Lib/ctypes/__init__.py
 
10763
--- a/Lib/ctypes/__init__.py
 
10764
+++ b/Lib/ctypes/__init__.py
 
10765
@@ -262,6 +262,22 @@
 
10766
 
 
10767
 from _ctypes import POINTER, pointer, _pointer_type_cache
 
10768
 
 
10769
+def _reset_cache():
 
10770
+    _pointer_type_cache.clear()
 
10771
+    _c_functype_cache.clear()
 
10772
+    if _os.name in ("nt", "ce"):
 
10773
+        _win_functype_cache.clear()
 
10774
+    # _SimpleCData.c_wchar_p_from_param
 
10775
+    POINTER(c_wchar).from_param = c_wchar_p.from_param
 
10776
+    # _SimpleCData.c_char_p_from_param
 
10777
+    POINTER(c_char).from_param = c_char_p.from_param
 
10778
+    _pointer_type_cache[None] = c_void_p
 
10779
+    # XXX for whatever reasons, creating the first instance of a callback
 
10780
+    # function is needed for the unittests on Win64 to succeed.  This MAY
 
10781
+    # be a compiler bug, since the problem occurs only when _ctypes is
 
10782
+    # compiled with the MS SDK compiler.  Or an uninitialized variable?
 
10783
+    CFUNCTYPE(c_int)(lambda: None)
 
10784
+
 
10785
 try:
 
10786
     from _ctypes import set_conversion_mode
 
10787
 except ImportError:
 
10788
@@ -278,8 +294,6 @@
 
10789
     class c_wchar(_SimpleCData):
 
10790
         _type_ = "u"
 
10791
 
 
10792
-    POINTER(c_wchar).from_param = c_wchar_p.from_param #_SimpleCData.c_wchar_p_from_param
 
10793
-
 
10794
     def create_unicode_buffer(init, size=None):
 
10795
         """create_unicode_buffer(aString) -> character array
 
10796
         create_unicode_buffer(anInteger) -> character array
 
10797
@@ -298,8 +312,6 @@
 
10798
             return buf
 
10799
         raise TypeError(init)
 
10800
 
 
10801
-POINTER(c_char).from_param = c_char_p.from_param #_SimpleCData.c_char_p_from_param
 
10802
-
 
10803
 # XXX Deprecated
 
10804
 def SetPointerType(pointer, cls):
 
10805
     if _pointer_type_cache.get(cls, None) is not None:
 
10806
@@ -458,8 +470,6 @@
 
10807
             descr = FormatError(code).strip()
 
10808
         return WindowsError(code, descr)
 
10809
 
 
10810
-_pointer_type_cache[None] = c_void_p
 
10811
-
 
10812
 if sizeof(c_uint) == sizeof(c_void_p):
 
10813
     c_size_t = c_uint
 
10814
     c_ssize_t = c_int
 
10815
@@ -542,8 +552,4 @@
 
10816
     elif sizeof(kind) == 8: c_uint64 = kind
 
10817
 del(kind)
 
10818
 
 
10819
-# XXX for whatever reasons, creating the first instance of a callback
 
10820
-# function is needed for the unittests on Win64 to succeed.  This MAY
 
10821
-# be a compiler bug, since the problem occurs only when _ctypes is
 
10822
-# compiled with the MS SDK compiler.  Or an uninitialized variable?
 
10823
-CFUNCTYPE(c_int)(lambda: None)
 
10824
+_reset_cache()
3520
10825
diff -r 8527427914a2 Lib/ctypes/_endian.py
3521
10826
--- a/Lib/ctypes/_endian.py
3522
10827
+++ b/Lib/ctypes/_endian.py
3545
10850
 
3546
10851
 class _swapped_meta(type(Structure)):
3547
10852
     def __setattr__(self, attrname, value):
 
10853
diff -r 8527427914a2 Lib/ctypes/test/test_as_parameter.py
 
10854
--- a/Lib/ctypes/test/test_as_parameter.py
 
10855
+++ b/Lib/ctypes/test/test_as_parameter.py
 
10856
@@ -74,6 +74,7 @@
 
10857
     def test_callbacks(self):
 
10858
         f = dll._testfunc_callback_i_if
 
10859
         f.restype = c_int
 
10860
+        f.argtypes = None
 
10861
 
 
10862
         MyCallback = CFUNCTYPE(c_int, c_int)
 
10863
 
 
10864
diff -r 8527427914a2 Lib/ctypes/test/test_buffers.py
 
10865
--- a/Lib/ctypes/test/test_buffers.py
 
10866
+++ b/Lib/ctypes/test/test_buffers.py
 
10867
@@ -20,6 +20,10 @@
 
10868
         self.assertEqual(b[::2], "ac")
 
10869
         self.assertEqual(b[::5], "a")
 
10870
 
 
10871
+    def test_buffer_interface(self):
 
10872
+        self.assertEqual(len(bytearray(create_string_buffer(0))), 0)
 
10873
+        self.assertEqual(len(bytearray(create_string_buffer(1))), 1)
 
10874
+
 
10875
     def test_string_conversion(self):
 
10876
         b = create_string_buffer(u"abc")
 
10877
         self.assertEqual(len(b), 4) # trailing nul char
3548
10878
diff -r 8527427914a2 Lib/ctypes/test/test_byteswap.py
3549
10879
--- a/Lib/ctypes/test/test_byteswap.py
3550
10880
+++ b/Lib/ctypes/test/test_byteswap.py
3598
10928
 
3599
10929
     def test_struct_fields_2(self):
3600
10930
         # standard packing in struct uses no alignment.
 
10931
diff -r 8527427914a2 Lib/ctypes/test/test_callbacks.py
 
10932
--- a/Lib/ctypes/test/test_callbacks.py
 
10933
+++ b/Lib/ctypes/test/test_callbacks.py
 
10934
@@ -140,6 +140,14 @@
 
10935
                 if isinstance(x, X)]
 
10936
         self.assertEqual(len(live), 0)
 
10937
 
 
10938
+    def test_issue12483(self):
 
10939
+        import gc
 
10940
+        class Nasty:
 
10941
+            def __del__(self):
 
10942
+                gc.collect()
 
10943
+        CFUNCTYPE(None)(lambda x=Nasty(): None)
 
10944
+
 
10945
+
 
10946
 try:
 
10947
     WINFUNCTYPE
 
10948
 except NameError:
 
10949
diff -r 8527427914a2 Lib/ctypes/test/test_functions.py
 
10950
--- a/Lib/ctypes/test/test_functions.py
 
10951
+++ b/Lib/ctypes/test/test_functions.py
 
10952
@@ -250,6 +250,7 @@
 
10953
     def test_callbacks(self):
 
10954
         f = dll._testfunc_callback_i_if
 
10955
         f.restype = c_int
 
10956
+        f.argtypes = None
 
10957
 
 
10958
         MyCallback = CFUNCTYPE(c_int, c_int)
 
10959
 
 
10960
diff -r 8527427914a2 Lib/ctypes/test/test_structures.py
 
10961
--- a/Lib/ctypes/test/test_structures.py
 
10962
+++ b/Lib/ctypes/test/test_structures.py
 
10963
@@ -239,6 +239,14 @@
 
10964
             pass
 
10965
         self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)])
 
10966
 
 
10967
+    def test_invalid_name(self):
 
10968
+        # field name must be string
 
10969
+        def declare_with_name(name):
 
10970
+            class S(Structure):
 
10971
+                _fields_ = [(name, c_int)]
 
10972
+
 
10973
+        self.assertRaises(TypeError, declare_with_name, u"x\xe9")
 
10974
+
 
10975
     def test_intarray_fields(self):
 
10976
         class SomeInts(Structure):
 
10977
             _fields_ = [("a", c_int * 4)]
 
10978
@@ -324,6 +332,18 @@
 
10979
         else:
 
10980
             self.assertEqual(msg, "(Phone) exceptions.TypeError: too many initializers")
 
10981
 
 
10982
+    def test_huge_field_name(self):
 
10983
+        # issue12881: segfault with large structure field names
 
10984
+        def create_class(length):
 
10985
+            class S(Structure):
 
10986
+                _fields_ = [('x' * length, c_int)]
 
10987
+
 
10988
+        for length in [10 ** i for i in range(0, 8)]:
 
10989
+            try:
 
10990
+                create_class(length)
 
10991
+            except MemoryError:
 
10992
+                # MemoryErrors are OK, we just don't want to segfault
 
10993
+                pass
 
10994
 
 
10995
     def get_except(self, func, *args):
 
10996
         try:
3601
10997
diff -r 8527427914a2 Lib/decimal.py
3602
10998
--- a/Lib/decimal.py
3603
10999
+++ b/Lib/decimal.py
 
11000
@@ -21,7 +21,7 @@
 
11001
 This is a Py2.3 implementation of decimal floating point arithmetic based on
 
11002
 the General Decimal Arithmetic Specification:
 
11003
 
 
11004
-    www2.hursley.ibm.com/decimal/decarith.html
 
11005
+    http://speleotrove.com/decimal/decarith.html
 
11006
 
 
11007
 and IEEE standard 854-1987:
 
11008
 
3604
11009
@@ -1942,9 +1942,9 @@
3605
11010
         nonzero.  For efficiency, other._exp should not be too large,
3606
11011
         so that 10**abs(other._exp) is a feasible calculation."""
3755
11160
 def _sqrt_nearest(n, a):
3756
11161
     """Closest integer to the square root of the positive integer n.  a is
3757
11162
     an initial approximation to the square root.  Any positive integer
 
11163
diff -r 8527427914a2 Lib/distutils/command/bdist_dumb.py
 
11164
--- a/Lib/distutils/command/bdist_dumb.py
 
11165
+++ b/Lib/distutils/command/bdist_dumb.py
 
11166
@@ -58,7 +58,7 @@
 
11167
         self.format = None
 
11168
         self.keep_temp = 0
 
11169
         self.dist_dir = None
 
11170
-        self.skip_build = 0
 
11171
+        self.skip_build = None
 
11172
         self.relative = 0
 
11173
         self.owner = None
 
11174
         self.group = None
 
11175
@@ -78,7 +78,8 @@
 
11176
 
 
11177
         self.set_undefined_options('bdist',
 
11178
                                    ('dist_dir', 'dist_dir'),
 
11179
-                                   ('plat_name', 'plat_name'))
 
11180
+                                   ('plat_name', 'plat_name'),
 
11181
+                                   ('skip_build', 'skip_build'))
 
11182
 
 
11183
     def run(self):
 
11184
         if not self.skip_build:
 
11185
diff -r 8527427914a2 Lib/distutils/command/bdist_msi.py
 
11186
--- a/Lib/distutils/command/bdist_msi.py
 
11187
+++ b/Lib/distutils/command/bdist_msi.py
 
11188
@@ -131,18 +131,22 @@
 
11189
         self.no_target_optimize = 0
 
11190
         self.target_version = None
 
11191
         self.dist_dir = None
 
11192
-        self.skip_build = 0
 
11193
+        self.skip_build = None
 
11194
         self.install_script = None
 
11195
         self.pre_install_script = None
 
11196
         self.versions = None
 
11197
 
 
11198
     def finalize_options (self):
 
11199
+        self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
 
11200
+
 
11201
         if self.bdist_dir is None:
 
11202
             bdist_base = self.get_finalized_command('bdist').bdist_base
 
11203
             self.bdist_dir = os.path.join(bdist_base, 'msi')
 
11204
+
 
11205
         short_version = get_python_version()
 
11206
         if (not self.target_version) and self.distribution.has_ext_modules():
 
11207
             self.target_version = short_version
 
11208
+
 
11209
         if self.target_version:
 
11210
             self.versions = [self.target_version]
 
11211
             if not self.skip_build and self.distribution.has_ext_modules()\
 
11212
diff -r 8527427914a2 Lib/distutils/command/bdist_wininst.py
 
11213
--- a/Lib/distutils/command/bdist_wininst.py
 
11214
+++ b/Lib/distutils/command/bdist_wininst.py
 
11215
@@ -71,7 +71,7 @@
 
11216
         self.dist_dir = None
 
11217
         self.bitmap = None
 
11218
         self.title = None
 
11219
-        self.skip_build = 0
 
11220
+        self.skip_build = None
 
11221
         self.install_script = None
 
11222
         self.pre_install_script = None
 
11223
         self.user_access_control = None
 
11224
@@ -80,6 +80,8 @@
 
11225
 
 
11226
 
 
11227
     def finalize_options (self):
 
11228
+        self.set_undefined_options('bdist', ('skip_build', 'skip_build'))
 
11229
+
 
11230
         if self.bdist_dir is None:
 
11231
             if self.skip_build and self.plat_name:
 
11232
                 # If build is skipped and plat_name is overridden, bdist will
 
11233
@@ -89,8 +91,10 @@
 
11234
                 # next the command will be initialized using that name
 
11235
             bdist_base = self.get_finalized_command('bdist').bdist_base
 
11236
             self.bdist_dir = os.path.join(bdist_base, 'wininst')
 
11237
+
 
11238
         if not self.target_version:
 
11239
             self.target_version = ""
 
11240
+
 
11241
         if not self.skip_build and self.distribution.has_ext_modules():
 
11242
             short_version = get_python_version()
 
11243
             if self.target_version and self.target_version != short_version:
 
11244
diff -r 8527427914a2 Lib/distutils/command/check.py
 
11245
--- a/Lib/distutils/command/check.py
 
11246
+++ b/Lib/distutils/command/check.py
 
11247
@@ -5,6 +5,7 @@
 
11248
 __revision__ = "$Id$"
 
11249
 
 
11250
 from distutils.core import Command
 
11251
+from distutils.dist import PKG_INFO_ENCODING
 
11252
 from distutils.errors import DistutilsSetupError
 
11253
 
 
11254
 try:
 
11255
@@ -108,6 +109,8 @@
 
11256
     def check_restructuredtext(self):
 
11257
         """Checks if the long string fields are reST-compliant."""
 
11258
         data = self.distribution.get_long_description()
 
11259
+        if not isinstance(data, unicode):
 
11260
+            data = data.decode(PKG_INFO_ENCODING)
 
11261
         for warning in self._check_rst_data(data):
 
11262
             line = warning[-1].get('line')
 
11263
             if line is None:
 
11264
diff -r 8527427914a2 Lib/distutils/command/register.py
 
11265
--- a/Lib/distutils/command/register.py
 
11266
+++ b/Lib/distutils/command/register.py
 
11267
@@ -10,7 +10,6 @@
 
11268
 import urllib2
 
11269
 import getpass
 
11270
 import urlparse
 
11271
-import StringIO
 
11272
 from warnings import warn
 
11273
 
 
11274
 from distutils.core import PyPIRCCommand
 
11275
@@ -260,21 +259,30 @@
 
11276
         boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
 
11277
         sep_boundary = '\n--' + boundary
 
11278
         end_boundary = sep_boundary + '--'
 
11279
-        body = StringIO.StringIO()
 
11280
+        chunks = []
 
11281
         for key, value in data.items():
 
11282
             # handle multiple entries for the same name
 
11283
             if type(value) not in (type([]), type( () )):
 
11284
                 value = [value]
 
11285
             for value in value:
 
11286
-                body.write(sep_boundary)
 
11287
-                body.write('\nContent-Disposition: form-data; name="%s"'%key)
 
11288
-                body.write("\n\n")
 
11289
-                body.write(value)
 
11290
+                chunks.append(sep_boundary)
 
11291
+                chunks.append('\nContent-Disposition: form-data; name="%s"'%key)
 
11292
+                chunks.append("\n\n")
 
11293
+                chunks.append(value)
 
11294
                 if value and value[-1] == '\r':
 
11295
-                    body.write('\n')  # write an extra newline (lurve Macs)
 
11296
-        body.write(end_boundary)
 
11297
-        body.write("\n")
 
11298
-        body = body.getvalue()
 
11299
+                    chunks.append('\n')  # write an extra newline (lurve Macs)
 
11300
+        chunks.append(end_boundary)
 
11301
+        chunks.append("\n")
 
11302
+
 
11303
+        # chunks may be bytes (str) or unicode objects that we need to encode
 
11304
+        body = []
 
11305
+        for chunk in chunks:
 
11306
+            if isinstance(chunk, unicode):
 
11307
+                body.append(chunk.encode('utf-8'))
 
11308
+            else:
 
11309
+                body.append(chunk)
 
11310
+
 
11311
+        body = ''.join(body)
 
11312
 
 
11313
         # build the Request
 
11314
         headers = {
3758
11315
diff -r 8527427914a2 Lib/distutils/command/sdist.py
3759
11316
--- a/Lib/distutils/command/sdist.py
3760
11317
+++ b/Lib/distutils/command/sdist.py
3781
11338
         if not template_exists:
3782
11339
             self.warn(("manifest template '%s' does not exist " +
3783
11340
                         "(using default file list)") %
3784
 
@@ -352,23 +358,28 @@
 
11341
@@ -314,7 +320,10 @@
 
11342
 
 
11343
                 try:
 
11344
                     self.filelist.process_template_line(line)
 
11345
-                except DistutilsTemplateError, msg:
 
11346
+                # the call above can raise a DistutilsTemplateError for
 
11347
+                # malformed lines, or a ValueError from the lower-level
 
11348
+                # convert_path function
 
11349
+                except (DistutilsTemplateError, ValueError) as msg:
 
11350
                     self.warn("%s, line %d: %s" % (template.filename,
 
11351
                                                    template.current_line,
 
11352
                                                    msg))
 
11353
@@ -352,23 +361,28 @@
3785
11354
         by 'add_defaults()' and 'read_template()') to the manifest file
3786
11355
         named by 'self.manifest'.
3787
11356
         """
3821
11390
     def read_manifest(self):
3822
11391
         """Read the manifest file (named by 'self.manifest') and use it to
3823
11392
         fill in 'self.filelist', the list of files to include in the source
3824
 
@@ -376,12 +387,11 @@
 
11393
@@ -376,12 +390,11 @@
3825
11394
         """
3826
11395
         log.info("reading manifest file '%s'", self.manifest)
3827
11396
         manifest = open(self.manifest)
3877
11446
             return True
3878
11447
 
3879
11448
     return False
 
11449
diff -r 8527427914a2 Lib/distutils/dist.py
 
11450
--- a/Lib/distutils/dist.py
 
11451
+++ b/Lib/distutils/dist.py
 
11452
@@ -1111,7 +1111,8 @@
 
11453
         """Write the PKG-INFO format data to a file object.
 
11454
         """
 
11455
         version = '1.0'
 
11456
-        if self.provides or self.requires or self.obsoletes:
 
11457
+        if (self.provides or self.requires or self.obsoletes or
 
11458
+            self.classifiers or self.download_url):
 
11459
             version = '1.1'
 
11460
 
 
11461
         self._write_field(file, 'Metadata-Version', version)
 
11462
diff -r 8527427914a2 Lib/distutils/filelist.py
 
11463
--- a/Lib/distutils/filelist.py
 
11464
+++ b/Lib/distutils/filelist.py
 
11465
@@ -328,7 +328,10 @@
 
11466
         # ditch end of pattern character
 
11467
         empty_pattern = glob_to_re('')
 
11468
         prefix_re = glob_to_re(prefix)[:-len(empty_pattern)]
 
11469
-        pattern_re = "^" + os.path.join(prefix_re, ".*" + pattern_re)
 
11470
+        # match both path separators, as in Postel's principle
 
11471
+        sep_pat = "[" + re.escape(os.path.sep + os.path.altsep
 
11472
+                                  if os.path.altsep else os.path.sep) + "]"
 
11473
+        pattern_re = "^" + sep_pat.join([prefix_re, ".*" + pattern_re])
 
11474
     else:                               # no prefix -- respect anchor flag
 
11475
         if anchor:
 
11476
             pattern_re = "^" + pattern_re
 
11477
diff -r 8527427914a2 Lib/distutils/msvc9compiler.py
 
11478
--- a/Lib/distutils/msvc9compiler.py
 
11479
+++ b/Lib/distutils/msvc9compiler.py
 
11480
@@ -640,15 +640,7 @@
 
11481
                     self.library_filename(dll_name))
 
11482
                 ld_args.append ('/IMPLIB:' + implib_file)
 
11483
 
 
11484
-            # Embedded manifests are recommended - see MSDN article titled
 
11485
-            # "How to: Embed a Manifest Inside a C/C++ Application"
 
11486
-            # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
 
11487
-            # Ask the linker to generate the manifest in the temp dir, so
 
11488
-            # we can embed it later.
 
11489
-            temp_manifest = os.path.join(
 
11490
-                    build_temp,
 
11491
-                    os.path.basename(output_filename) + ".manifest")
 
11492
-            ld_args.append('/MANIFESTFILE:' + temp_manifest)
 
11493
+            self.manifest_setup_ldargs(output_filename, build_temp, ld_args)
 
11494
 
 
11495
             if extra_preargs:
 
11496
                 ld_args[:0] = extra_preargs
 
11497
@@ -666,20 +658,54 @@
 
11498
             # will still consider the DLL up-to-date, but it will not have a
 
11499
             # manifest.  Maybe we should link to a temp file?  OTOH, that
 
11500
             # implies a build environment error that shouldn't go undetected.
 
11501
-            if target_desc == CCompiler.EXECUTABLE:
 
11502
-                mfid = 1
 
11503
-            else:
 
11504
-                mfid = 2
 
11505
-                self._remove_visual_c_ref(temp_manifest)
 
11506
-            out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
 
11507
-            try:
 
11508
-                self.spawn(['mt.exe', '-nologo', '-manifest',
 
11509
-                            temp_manifest, out_arg])
 
11510
-            except DistutilsExecError, msg:
 
11511
-                raise LinkError(msg)
 
11512
+            mfinfo = self.manifest_get_embed_info(target_desc, ld_args)
 
11513
+            if mfinfo is not None:
 
11514
+                mffilename, mfid = mfinfo
 
11515
+                out_arg = '-outputresource:%s;%s' % (output_filename, mfid)
 
11516
+                try:
 
11517
+                    self.spawn(['mt.exe', '-nologo', '-manifest',
 
11518
+                                mffilename, out_arg])
 
11519
+                except DistutilsExecError, msg:
 
11520
+                    raise LinkError(msg)
 
11521
         else:
 
11522
             log.debug("skipping %s (up-to-date)", output_filename)
 
11523
 
 
11524
+    def manifest_setup_ldargs(self, output_filename, build_temp, ld_args):
 
11525
+        # If we need a manifest at all, an embedded manifest is recommended.
 
11526
+        # See MSDN article titled
 
11527
+        # "How to: Embed a Manifest Inside a C/C++ Application"
 
11528
+        # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)
 
11529
+        # Ask the linker to generate the manifest in the temp dir, so
 
11530
+        # we can check it, and possibly embed it, later.
 
11531
+        temp_manifest = os.path.join(
 
11532
+                build_temp,
 
11533
+                os.path.basename(output_filename) + ".manifest")
 
11534
+        ld_args.append('/MANIFESTFILE:' + temp_manifest)
 
11535
+
 
11536
+    def manifest_get_embed_info(self, target_desc, ld_args):
 
11537
+        # If a manifest should be embedded, return a tuple of
 
11538
+        # (manifest_filename, resource_id).  Returns None if no manifest
 
11539
+        # should be embedded.  See http://bugs.python.org/issue7833 for why
 
11540
+        # we want to avoid any manifest for extension modules if we can)
 
11541
+        for arg in ld_args:
 
11542
+            if arg.startswith("/MANIFESTFILE:"):
 
11543
+                temp_manifest = arg.split(":", 1)[1]
 
11544
+                break
 
11545
+        else:
 
11546
+            # no /MANIFESTFILE so nothing to do.
 
11547
+            return None
 
11548
+        if target_desc == CCompiler.EXECUTABLE:
 
11549
+            # by default, executables always get the manifest with the
 
11550
+            # CRT referenced.
 
11551
+            mfid = 1
 
11552
+        else:
 
11553
+            # Extension modules try and avoid any manifest if possible.
 
11554
+            mfid = 2
 
11555
+            temp_manifest = self._remove_visual_c_ref(temp_manifest)
 
11556
+        if temp_manifest is None:
 
11557
+            return None
 
11558
+        return temp_manifest, mfid
 
11559
+
 
11560
     def _remove_visual_c_ref(self, manifest_file):
 
11561
         try:
 
11562
             # Remove references to the Visual C runtime, so they will
 
11563
@@ -688,6 +714,8 @@
 
11564
             # runtimes are not in WinSxS folder, but in Python's own
 
11565
             # folder), the runtimes do not need to be in every folder
 
11566
             # with .pyd's.
 
11567
+            # Returns either the filename of the modified manifest or
 
11568
+            # None if no manifest should be embedded.
 
11569
             manifest_f = open(manifest_file)
 
11570
             try:
 
11571
                 manifest_buf = manifest_f.read()
 
11572
@@ -700,9 +728,18 @@
 
11573
             manifest_buf = re.sub(pattern, "", manifest_buf)
 
11574
             pattern = "<dependentAssembly>\s*</dependentAssembly>"
 
11575
             manifest_buf = re.sub(pattern, "", manifest_buf)
 
11576
+            # Now see if any other assemblies are referenced - if not, we
 
11577
+            # don't want a manifest embedded.
 
11578
+            pattern = re.compile(
 
11579
+                r"""<assemblyIdentity.*?name=(?:"|')(.+?)(?:"|')"""
 
11580
+                r""".*?(?:/>|</assemblyIdentity>)""", re.DOTALL)
 
11581
+            if re.search(pattern, manifest_buf) is None:
 
11582
+                return None
 
11583
+
 
11584
             manifest_f = open(manifest_file, 'w')
 
11585
             try:
 
11586
                 manifest_f.write(manifest_buf)
 
11587
+                return manifest_file
 
11588
             finally:
 
11589
                 manifest_f.close()
 
11590
         except IOError:
3880
11591
diff -r 8527427914a2 Lib/distutils/spawn.py
3881
11592
--- a/Lib/distutils/spawn.py
3882
11593
+++ b/Lib/distutils/spawn.py
3950
11661
     # On AIX, there are wrong paths to the linker scripts in the Makefile
3951
11662
     # -- these paths are relative to the Python source, but when installed
3952
11663
     # the scripts are in another directory.
 
11664
diff -r 8527427914a2 Lib/distutils/tests/support.py
 
11665
--- a/Lib/distutils/tests/support.py
 
11666
+++ b/Lib/distutils/tests/support.py
 
11667
@@ -1,7 +1,10 @@
 
11668
 """Support code for distutils test cases."""
 
11669
 import os
 
11670
+import sys
 
11671
 import shutil
 
11672
 import tempfile
 
11673
+import unittest
 
11674
+import sysconfig
 
11675
 from copy import deepcopy
 
11676
 import warnings
 
11677
 
 
11678
@@ -9,6 +12,7 @@
 
11679
 from distutils.log import DEBUG, INFO, WARN, ERROR, FATAL
 
11680
 from distutils.core import Distribution
 
11681
 
 
11682
+
 
11683
 def capture_warnings(func):
 
11684
     def _capture_warnings(*args, **kw):
 
11685
         with warnings.catch_warnings():
 
11686
@@ -16,6 +20,7 @@
 
11687
             return func(*args, **kw)
 
11688
     return _capture_warnings
 
11689
 
 
11690
+
 
11691
 class LoggingSilencer(object):
 
11692
 
 
11693
     def setUp(self):
 
11694
@@ -49,6 +54,7 @@
 
11695
     def clear_logs(self):
 
11696
         self.logs = []
 
11697
 
 
11698
+
 
11699
 class TempdirManager(object):
 
11700
     """Mix-in class that handles temporary directories for test cases.
 
11701
 
 
11702
@@ -57,9 +63,13 @@
 
11703
 
 
11704
     def setUp(self):
 
11705
         super(TempdirManager, self).setUp()
 
11706
+        self.old_cwd = os.getcwd()
 
11707
         self.tempdirs = []
 
11708
 
 
11709
     def tearDown(self):
 
11710
+        # Restore working dir, for Solaris and derivatives, where rmdir()
 
11711
+        # on the current directory fails.
 
11712
+        os.chdir(self.old_cwd)
 
11713
         super(TempdirManager, self).tearDown()
 
11714
         while self.tempdirs:
 
11715
             d = self.tempdirs.pop()
 
11716
@@ -105,6 +115,7 @@
 
11717
 
 
11718
         return pkg_dir, dist
 
11719
 
 
11720
+
 
11721
 class DummyCommand:
 
11722
     """Class to store options for retrieval via set_undefined_options()."""
 
11723
 
 
11724
@@ -115,6 +126,7 @@
 
11725
     def ensure_finalized(self):
 
11726
         pass
 
11727
 
 
11728
+
 
11729
 class EnvironGuard(object):
 
11730
 
 
11731
     def setUp(self):
 
11732
@@ -131,3 +143,73 @@
 
11733
                 del os.environ[key]
 
11734
 
 
11735
         super(EnvironGuard, self).tearDown()
 
11736
+
 
11737
+
 
11738
+def copy_xxmodule_c(directory):
 
11739
+    """Helper for tests that need the xxmodule.c source file.
 
11740
+
 
11741
+    Example use:
 
11742
+
 
11743
+        def test_compile(self):
 
11744
+            copy_xxmodule_c(self.tmpdir)
 
11745
+            self.assertIn('xxmodule.c', os.listdir(self.tmpdir))
 
11746
+
 
11747
+    If the source file can be found, it will be copied to *directory*.  If not,
 
11748
+    the test will be skipped.  Errors during copy are not caught.
 
11749
+    """
 
11750
+    filename = _get_xxmodule_path()
 
11751
+    if filename is None:
 
11752
+        raise unittest.SkipTest('cannot find xxmodule.c (test must run in '
 
11753
+                                'the python build dir)')
 
11754
+    shutil.copy(filename, directory)
 
11755
+
 
11756
+
 
11757
+def _get_xxmodule_path():
 
11758
+    # FIXME when run from regrtest, srcdir seems to be '.', which does not help
 
11759
+    # us find the xxmodule.c file
 
11760
+    srcdir = sysconfig.get_config_var('srcdir')
 
11761
+    candidates = [
 
11762
+        # use installed copy if available
 
11763
+        os.path.join(os.path.dirname(__file__), 'xxmodule.c'),
 
11764
+        # otherwise try using copy from build directory
 
11765
+        os.path.join(srcdir, 'Modules', 'xxmodule.c'),
 
11766
+        # srcdir mysteriously can be $srcdir/Lib/distutils/tests when
 
11767
+        # this file is run from its parent directory, so walk up the
 
11768
+        # tree to find the real srcdir
 
11769
+        os.path.join(srcdir, '..', '..', '..', 'Modules', 'xxmodule.c'),
 
11770
+    ]
 
11771
+    for path in candidates:
 
11772
+        if os.path.exists(path):
 
11773
+            return path
 
11774
+
 
11775
+
 
11776
+def fixup_build_ext(cmd):
 
11777
+    """Function needed to make build_ext tests pass.
 
11778
+
 
11779
+    When Python was build with --enable-shared on Unix, -L. is not good
 
11780
+    enough to find the libpython<blah>.so.  This is because regrtest runs
 
11781
+    it under a tempdir, not in the top level where the .so lives.  By the
 
11782
+    time we've gotten here, Python's already been chdir'd to the tempdir.
 
11783
+
 
11784
+    When Python was built with in debug mode on Windows, build_ext commands
 
11785
+    need their debug attribute set, and it is not done automatically for
 
11786
+    some reason.
 
11787
+
 
11788
+    This function handles both of these things.  Example use:
 
11789
+
 
11790
+        cmd = build_ext(dist)
 
11791
+        support.fixup_build_ext(cmd)
 
11792
+        cmd.ensure_finalized()
 
11793
+    """
 
11794
+    if os.name == 'nt':
 
11795
+        cmd.debug = sys.executable.endswith('_d.exe')
 
11796
+    elif sysconfig.get_config_var('Py_ENABLE_SHARED'):
 
11797
+        # To further add to the shared builds fun on Unix, we can't just add
 
11798
+        # library_dirs to the Extension() instance because that doesn't get
 
11799
+        # plumbed through to the final compiler command.
 
11800
+        runshared = sysconfig.get_config_var('RUNSHARED')
 
11801
+        if runshared is None:
 
11802
+            cmd.library_dirs = ['.']
 
11803
+        else:
 
11804
+            name, equals, value = runshared.partition('=')
 
11805
+            cmd.library_dirs = value.split(os.pathsep)
 
11806
diff -r 8527427914a2 Lib/distutils/tests/test_bdist.py
 
11807
--- a/Lib/distutils/tests/test_bdist.py
 
11808
+++ b/Lib/distutils/tests/test_bdist.py
 
11809
@@ -1,42 +1,49 @@
 
11810
 """Tests for distutils.command.bdist."""
 
11811
+import os
 
11812
 import unittest
 
11813
-import sys
 
11814
-import os
 
11815
-import tempfile
 
11816
-import shutil
 
11817
 
 
11818
 from test.test_support import run_unittest
 
11819
 
 
11820
-from distutils.core import Distribution
 
11821
 from distutils.command.bdist import bdist
 
11822
 from distutils.tests import support
 
11823
-from distutils.spawn import find_executable
 
11824
-from distutils import spawn
 
11825
-from distutils.errors import DistutilsExecError
 
11826
+
 
11827
 
 
11828
 class BuildTestCase(support.TempdirManager,
 
11829
                     unittest.TestCase):
 
11830
 
 
11831
     def test_formats(self):
 
11832
-
 
11833
         # let's create a command and make sure
 
11834
-        # we can fix the format
 
11835
-        pkg_pth, dist = self.create_dist()
 
11836
+        # we can set the format
 
11837
+        dist = self.create_dist()[1]
 
11838
         cmd = bdist(dist)
 
11839
         cmd.formats = ['msi']
 
11840
         cmd.ensure_finalized()
 
11841
         self.assertEqual(cmd.formats, ['msi'])
 
11842
 
 
11843
-        # what format bdist offers ?
 
11844
-        # XXX an explicit list in bdist is
 
11845
-        # not the best way to  bdist_* commands
 
11846
-        # we should add a registry
 
11847
-        formats = ['rpm', 'zip', 'gztar', 'bztar', 'ztar',
 
11848
-                   'tar', 'wininst', 'msi']
 
11849
-        formats.sort()
 
11850
-        founded = cmd.format_command.keys()
 
11851
-        founded.sort()
 
11852
-        self.assertEqual(founded, formats)
 
11853
+        # what formats does bdist offer?
 
11854
+        formats = ['bztar', 'gztar', 'msi', 'rpm', 'tar',
 
11855
+                   'wininst', 'zip', 'ztar']
 
11856
+        found = sorted(cmd.format_command)
 
11857
+        self.assertEqual(found, formats)
 
11858
+
 
11859
+    def test_skip_build(self):
 
11860
+        # bug #10946: bdist --skip-build should trickle down to subcommands
 
11861
+        dist = self.create_dist()[1]
 
11862
+        cmd = bdist(dist)
 
11863
+        cmd.skip_build = 1
 
11864
+        cmd.ensure_finalized()
 
11865
+        dist.command_obj['bdist'] = cmd
 
11866
+
 
11867
+        names = ['bdist_dumb', 'bdist_wininst']
 
11868
+        # bdist_rpm does not support --skip-build
 
11869
+        if os.name == 'nt':
 
11870
+            names.append('bdist_msi')
 
11871
+
 
11872
+        for name in names:
 
11873
+            subcmd = cmd.get_finalized_command(name)
 
11874
+            self.assertTrue(subcmd.skip_build,
 
11875
+                            '%s should take --skip-build from bdist' % name)
 
11876
+
 
11877
 
 
11878
 def test_suite():
 
11879
     return unittest.makeSuite(BuildTestCase)
3953
11880
diff -r 8527427914a2 Lib/distutils/tests/test_build_ext.py
3954
11881
--- a/Lib/distutils/tests/test_build_ext.py
3955
11882
+++ b/Lib/distutils/tests/test_build_ext.py
3956
 
@@ -9,7 +9,8 @@
 
11883
@@ -1,7 +1,5 @@
 
11884
 import sys
 
11885
 import os
 
11886
-import tempfile
 
11887
-import shutil
 
11888
 from StringIO import StringIO
 
11889
 import textwrap
 
11890
 
 
11891
@@ -9,7 +7,8 @@
3957
11892
 from distutils.command.build_ext import build_ext
3958
11893
 from distutils import sysconfig
3959
11894
 from distutils.tests import support
3963
11898
 
3964
11899
 import unittest
3965
11900
 from test import test_support
3966
 
@@ -19,6 +20,11 @@
 
11901
@@ -18,71 +17,40 @@
 
11902
 # Don't load the xx module more than once.
3967
11903
 ALREADY_TESTED = False
3968
11904
 
3969
 
 def _get_source_filename():
3970
 
+    # use installed copy if available
3971
 
+    tests_f = os.path.join(os.path.dirname(__file__), 'xxmodule.c')
3972
 
+    if os.path.exists(tests_f):
3973
 
+        return tests_f
3974
 
+    # otherwise try using copy from build directory
3975
 
     srcdir = sysconfig.get_config_var('srcdir')
3976
 
     if srcdir is None:
3977
 
         return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')
3978
 
@@ -432,18 +438,43 @@
 
11905
-def _get_source_filename():
 
11906
-    srcdir = sysconfig.get_config_var('srcdir')
 
11907
-    if srcdir is None:
 
11908
-        return os.path.join(sysconfig.project_base, 'Modules', 'xxmodule.c')
 
11909
-    return os.path.join(srcdir, 'Modules', 'xxmodule.c')
 
11910
-
 
11911
-_XX_MODULE_PATH = _get_source_filename()
 
11912
 
 
11913
 class BuildExtTestCase(support.TempdirManager,
 
11914
                        support.LoggingSilencer,
 
11915
                        unittest.TestCase):
 
11916
     def setUp(self):
 
11917
-        # Create a simple test environment
 
11918
-        # Note that we're making changes to sys.path
 
11919
         super(BuildExtTestCase, self).setUp()
 
11920
-        self.tmp_dir = tempfile.mkdtemp(prefix="pythontest_")
 
11921
-        if os.path.exists(_XX_MODULE_PATH):
 
11922
-            self.sys_path = sys.path[:]
 
11923
-            sys.path.append(self.tmp_dir)
 
11924
-            shutil.copy(_XX_MODULE_PATH, self.tmp_dir)
 
11925
+        self.tmp_dir = self.mkdtemp()
 
11926
+        self.xx_created = False
 
11927
+        sys.path.append(self.tmp_dir)
 
11928
+        self.addCleanup(sys.path.remove, self.tmp_dir)
 
11929
+        if sys.version > "2.6":
 
11930
+            import site
 
11931
+            self.old_user_base = site.USER_BASE
 
11932
+            site.USER_BASE = self.mkdtemp()
 
11933
+            from distutils.command import build_ext
 
11934
+            build_ext.USER_BASE = site.USER_BASE
 
11935
 
 
11936
     def tearDown(self):
 
11937
-        # Get everything back to normal
 
11938
-        if os.path.exists(_XX_MODULE_PATH):
 
11939
+        if self.xx_created:
 
11940
             test_support.unload('xx')
 
11941
-            sys.path[:] = self.sys_path
 
11942
             # XXX on Windows the test leaves a directory
 
11943
             # with xx module in TEMP
 
11944
-        shutil.rmtree(self.tmp_dir, os.name == 'nt' or
 
11945
-                                    sys.platform == 'cygwin')
 
11946
         super(BuildExtTestCase, self).tearDown()
 
11947
 
 
11948
-    def _fixup_command(self, cmd):
 
11949
-        # When Python was build with --enable-shared, -L. is not good enough
 
11950
-        # to find the libpython<blah>.so.  This is because regrtest runs it
 
11951
-        # under a tempdir, not in the top level where the .so lives.  By the
 
11952
-        # time we've gotten here, Python's already been chdir'd to the
 
11953
-        # tempdir.
 
11954
-        #
 
11955
-        # To further add to the fun, we can't just add library_dirs to the
 
11956
-        # Extension() instance because that doesn't get plumbed through to the
 
11957
-        # final compiler command.
 
11958
-        if (sysconfig.get_config_var('Py_ENABLE_SHARED') and
 
11959
-            not sys.platform.startswith('win')):
 
11960
-            runshared = sysconfig.get_config_var('RUNSHARED')
 
11961
-            if runshared is None:
 
11962
-                cmd.library_dirs = ['.']
 
11963
-            else:
 
11964
-                name, equals, value = runshared.partition('=')
 
11965
-                cmd.library_dirs = value.split(os.pathsep)
 
11966
-
 
11967
-    @unittest.skipIf(not os.path.exists(_XX_MODULE_PATH),
 
11968
-                     'xxmodule.c not found')
 
11969
     def test_build_ext(self):
 
11970
         global ALREADY_TESTED
 
11971
+        support.copy_xxmodule_c(self.tmp_dir)
 
11972
+        self.xx_created = True
 
11973
         xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
 
11974
         xx_ext = Extension('xx', [xx_c])
 
11975
         dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
 
11976
         dist.package_dir = self.tmp_dir
 
11977
         cmd = build_ext(dist)
 
11978
-        self._fixup_command(cmd)
 
11979
-        if os.name == "nt":
 
11980
-            # On Windows, we must build a debug version iff running
 
11981
-            # a debug build of Python
 
11982
-            cmd.debug = sys.executable.endswith("_d.exe")
 
11983
+        support.fixup_build_ext(cmd)
 
11984
         cmd.build_lib = self.tmp_dir
 
11985
         cmd.build_temp = self.tmp_dir
 
11986
 
 
11987
@@ -135,6 +103,36 @@
 
11988
         # make sure we get some library dirs under solaris
 
11989
         self.assertTrue(len(cmd.library_dirs) > 0)
 
11990
 
 
11991
+    def test_user_site(self):
 
11992
+        # site.USER_SITE was introduced in 2.6
 
11993
+        if sys.version < '2.6':
 
11994
+            return
 
11995
+
 
11996
+        import site
 
11997
+        dist = Distribution({'name': 'xx'})
 
11998
+        cmd = build_ext(dist)
 
11999
+
 
12000
+        # making sure the user option is there
 
12001
+        options = [name for name, short, label in
 
12002
+                   cmd.user_options]
 
12003
+        self.assertIn('user', options)
 
12004
+
 
12005
+        # setting a value
 
12006
+        cmd.user = 1
 
12007
+
 
12008
+        # setting user based lib and include
 
12009
+        lib = os.path.join(site.USER_BASE, 'lib')
 
12010
+        incl = os.path.join(site.USER_BASE, 'include')
 
12011
+        os.mkdir(lib)
 
12012
+        os.mkdir(incl)
 
12013
+
 
12014
+        cmd.ensure_finalized()
 
12015
+
 
12016
+        # see if include_dirs and library_dirs were set
 
12017
+        self.assertIn(lib, cmd.library_dirs)
 
12018
+        self.assertIn(lib, cmd.rpath)
 
12019
+        self.assertIn(incl, cmd.include_dirs)
 
12020
+
 
12021
     def test_finalize_options(self):
 
12022
         # Make sure Python's include directories (for Python.h, pyconfig.h,
 
12023
         # etc.) are in the include search path.
 
12024
@@ -143,7 +141,6 @@
 
12025
         cmd = build_ext(dist)
 
12026
         cmd.finalize_options()
 
12027
 
 
12028
-        from distutils import sysconfig
 
12029
         py_include = sysconfig.get_python_inc()
 
12030
         self.assertTrue(py_include in cmd.include_dirs)
 
12031
 
 
12032
@@ -271,13 +268,10 @@
 
12033
         dist = Distribution({'name': 'xx',
 
12034
                              'ext_modules': [ext]})
 
12035
         cmd = build_ext(dist)
 
12036
-        self._fixup_command(cmd)
 
12037
+        support.fixup_build_ext(cmd)
 
12038
         cmd.ensure_finalized()
 
12039
         self.assertEqual(len(cmd.get_outputs()), 1)
 
12040
 
 
12041
-        if os.name == "nt":
 
12042
-            cmd.debug = sys.executable.endswith("_d.exe")
 
12043
-
 
12044
         cmd.build_lib = os.path.join(self.tmp_dir, 'build')
 
12045
         cmd.build_temp = os.path.join(self.tmp_dir, 'tempt')
 
12046
 
 
12047
@@ -432,18 +426,43 @@
3979
12048
         self.assertEqual(ext_path, wanted)
3980
12049
 
3981
12050
     @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
4025
12094
         deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c')
4026
12095
 
4027
12096
         with open(deptarget_c, 'w') as fp:
4028
 
@@ -452,16 +483,17 @@
 
12097
@@ -452,16 +471,17 @@
4029
12098
 
4030
12099
                 int dummy;
4031
12100
 
4047
12116
         deptarget_ext = Extension(
4048
12117
             'deptarget',
4049
12118
             [deptarget_c],
 
12119
@@ -477,10 +497,8 @@
 
12120
         cmd.build_temp = self.tmp_dir
 
12121
 
 
12122
         try:
 
12123
-            old_stdout = sys.stdout
 
12124
             cmd.ensure_finalized()
 
12125
             cmd.run()
 
12126
-
 
12127
         except CompileError:
 
12128
             self.fail("Wrong deployment target during compilation")
 
12129
 
 
12130
diff -r 8527427914a2 Lib/distutils/tests/test_check.py
 
12131
--- a/Lib/distutils/tests/test_check.py
 
12132
+++ b/Lib/distutils/tests/test_check.py
 
12133
@@ -1,3 +1,4 @@
 
12134
+# -*- encoding: utf8 -*-
 
12135
 """Tests for distutils.command.check."""
 
12136
 import unittest
 
12137
 from test.test_support import run_unittest
 
12138
@@ -46,6 +47,15 @@
 
12139
         cmd = self._run(metadata, strict=1)
 
12140
         self.assertEqual(cmd._warnings, 0)
 
12141
 
 
12142
+        # now a test with Unicode entries
 
12143
+        metadata = {'url': u'xxx', 'author': u'\u00c9ric',
 
12144
+                    'author_email': u'xxx', u'name': 'xxx',
 
12145
+                    'version': u'xxx',
 
12146
+                    'description': u'Something about esszet \u00df',
 
12147
+                    'long_description': u'More things about esszet \u00df'}
 
12148
+        cmd = self._run(metadata)
 
12149
+        self.assertEqual(cmd._warnings, 0)
 
12150
+
 
12151
     def test_check_document(self):
 
12152
         if not HAS_DOCUTILS: # won't test without docutils
 
12153
             return
 
12154
@@ -80,8 +90,8 @@
 
12155
         self.assertRaises(DistutilsSetupError, self._run, metadata,
 
12156
                           **{'strict': 1, 'restructuredtext': 1})
 
12157
 
 
12158
-        # and non-broken rest
 
12159
-        metadata['long_description'] = 'title\n=====\n\ntest'
 
12160
+        # and non-broken rest, including a non-ASCII character to test #12114
 
12161
+        metadata['long_description'] = u'title\n=====\n\ntest \u00df'
 
12162
         cmd = self._run(metadata, strict=1, restructuredtext=1)
 
12163
         self.assertEqual(cmd._warnings, 0)
 
12164
 
 
12165
diff -r 8527427914a2 Lib/distutils/tests/test_config_cmd.py
 
12166
--- a/Lib/distutils/tests/test_config_cmd.py
 
12167
+++ b/Lib/distutils/tests/test_config_cmd.py
 
12168
@@ -44,10 +44,10 @@
 
12169
         cmd = config(dist)
 
12170
 
 
12171
         # simple pattern searches
 
12172
-        match = cmd.search_cpp(pattern='xxx', body='// xxx')
 
12173
+        match = cmd.search_cpp(pattern='xxx', body='/* xxx */')
 
12174
         self.assertEqual(match, 0)
 
12175
 
 
12176
-        match = cmd.search_cpp(pattern='_configtest', body='// xxx')
 
12177
+        match = cmd.search_cpp(pattern='_configtest', body='/* xxx */')
 
12178
         self.assertEqual(match, 1)
 
12179
 
 
12180
     def test_finalize_options(self):
 
12181
diff -r 8527427914a2 Lib/distutils/tests/test_dist.py
 
12182
--- a/Lib/distutils/tests/test_dist.py
 
12183
+++ b/Lib/distutils/tests/test_dist.py
 
12184
@@ -8,12 +8,13 @@
 
12185
 import warnings
 
12186
 import textwrap
 
12187
 
 
12188
-from distutils.dist import Distribution, fix_help_options, DistributionMetadata
 
12189
+from distutils.dist import Distribution, fix_help_options
 
12190
 from distutils.cmd import Command
 
12191
 import distutils.dist
 
12192
 from test.test_support import TESTFN, captured_stdout, run_unittest
 
12193
 from distutils.tests import support
 
12194
 
 
12195
+
 
12196
 class test_dist(Command):
 
12197
     """Sample distutils extension command."""
 
12198
 
 
12199
@@ -61,7 +62,7 @@
 
12200
 
 
12201
     def test_debug_mode(self):
 
12202
         with open(TESTFN, "w") as f:
 
12203
-            f.write("[global]")
 
12204
+            f.write("[global]\n")
 
12205
             f.write("command_packages = foo.bar, splat")
 
12206
 
 
12207
         files = [TESTFN]
 
12208
@@ -97,7 +98,7 @@
 
12209
         self.assertEqual(d.get_command_packages(),
 
12210
                          ["distutils.command", "foo.bar", "distutils.tests"])
 
12211
         cmd = d.get_command_obj("test_dist")
 
12212
-        self.assertTrue(isinstance(cmd, test_dist))
 
12213
+        self.assertIsInstance(cmd, test_dist)
 
12214
         self.assertEqual(cmd.sample_option, "sometext")
 
12215
 
 
12216
     def test_command_packages_configfile(self):
 
12217
@@ -105,8 +106,8 @@
 
12218
         self.addCleanup(os.unlink, TESTFN)
 
12219
         f = open(TESTFN, "w")
 
12220
         try:
 
12221
-            print >>f, "[global]"
 
12222
-            print >>f, "command_packages = foo.bar, splat"
 
12223
+            print >> f, "[global]"
 
12224
+            print >> f, "command_packages = foo.bar, splat"
 
12225
         finally:
 
12226
             f.close()
 
12227
 
 
12228
@@ -138,7 +139,6 @@
 
12229
                             'description': u'Café torréfié',
 
12230
                             'long_description': u'Héhéhé'})
 
12231
 
 
12232
-
 
12233
         # let's make sure the file can be written
 
12234
         # with Unicode fields. they are encoded with
 
12235
         # PKG_INFO_ENCODING
 
12236
@@ -152,33 +152,28 @@
 
12237
                             'long_description': 'Hehehe'})
 
12238
 
 
12239
         my_file2 = os.path.join(tmp_dir, 'f2')
 
12240
-        dist.metadata.write_pkg_file(open(my_file, 'w'))
 
12241
+        dist.metadata.write_pkg_file(open(my_file2, 'w'))
 
12242
 
 
12243
     def test_empty_options(self):
 
12244
         # an empty options dictionary should not stay in the
 
12245
         # list of attributes
 
12246
-        klass = Distribution
 
12247
 
 
12248
         # catching warnings
 
12249
         warns = []
 
12250
+
 
12251
         def _warn(msg):
 
12252
             warns.append(msg)
 
12253
 
 
12254
-        old_warn = warnings.warn
 
12255
+        self.addCleanup(setattr, warnings, 'warn', warnings.warn)
 
12256
         warnings.warn = _warn
 
12257
-        try:
 
12258
-            dist = klass(attrs={'author': 'xxx',
 
12259
-                                'name': 'xxx',
 
12260
-                                'version': 'xxx',
 
12261
-                                'url': 'xxxx',
 
12262
-                                'options': {}})
 
12263
-        finally:
 
12264
-            warnings.warn = old_warn
 
12265
+        dist = Distribution(attrs={'author': 'xxx', 'name': 'xxx',
 
12266
+                                   'version': 'xxx', 'url': 'xxxx',
 
12267
+                                   'options': {}})
 
12268
 
 
12269
         self.assertEqual(len(warns), 0)
 
12270
+        self.assertNotIn('options', dir(dist))
 
12271
 
 
12272
     def test_finalize_options(self):
 
12273
-
 
12274
         attrs = {'keywords': 'one,two',
 
12275
                  'platforms': 'one,two'}
 
12276
 
 
12277
@@ -201,7 +196,6 @@
 
12278
         cmds = dist.get_command_packages()
 
12279
         self.assertEqual(cmds, ['distutils.command', 'one', 'two'])
 
12280
 
 
12281
-
 
12282
     def test_announce(self):
 
12283
         # make sure the level is known
 
12284
         dist = Distribution()
 
12285
@@ -251,15 +245,44 @@
 
12286
         sys.argv[:] = self.argv[1]
 
12287
         super(MetadataTestCase, self).tearDown()
 
12288
 
 
12289
+    def test_classifier(self):
 
12290
+        attrs = {'name': 'Boa', 'version': '3.0',
 
12291
+                 'classifiers': ['Programming Language :: Python :: 3']}
 
12292
+        dist = Distribution(attrs)
 
12293
+        meta = self.format_metadata(dist)
 
12294
+        self.assertIn('Metadata-Version: 1.1', meta)
 
12295
+
 
12296
+    def test_download_url(self):
 
12297
+        attrs = {'name': 'Boa', 'version': '3.0',
 
12298
+                 'download_url': 'http://example.org/boa'}
 
12299
+        dist = Distribution(attrs)
 
12300
+        meta = self.format_metadata(dist)
 
12301
+        self.assertIn('Metadata-Version: 1.1', meta)
 
12302
+
 
12303
+    def test_long_description(self):
 
12304
+        long_desc = textwrap.dedent("""\
 
12305
+        example::
 
12306
+              We start here
 
12307
+            and continue here
 
12308
+          and end here.""")
 
12309
+        attrs = {"name": "package",
 
12310
+                 "version": "1.0",
 
12311
+                 "long_description": long_desc}
 
12312
+
 
12313
+        dist = Distribution(attrs)
 
12314
+        meta = self.format_metadata(dist)
 
12315
+        meta = meta.replace('\n' + 8 * ' ', '\n')
 
12316
+        self.assertIn(long_desc, meta)
 
12317
+
 
12318
     def test_simple_metadata(self):
 
12319
         attrs = {"name": "package",
 
12320
                  "version": "1.0"}
 
12321
         dist = Distribution(attrs)
 
12322
         meta = self.format_metadata(dist)
 
12323
-        self.assertTrue("Metadata-Version: 1.0" in meta)
 
12324
-        self.assertTrue("provides:" not in meta.lower())
 
12325
-        self.assertTrue("requires:" not in meta.lower())
 
12326
-        self.assertTrue("obsoletes:" not in meta.lower())
 
12327
+        self.assertIn("Metadata-Version: 1.0", meta)
 
12328
+        self.assertNotIn("provides:", meta.lower())
 
12329
+        self.assertNotIn("requires:", meta.lower())
 
12330
+        self.assertNotIn("obsoletes:", meta.lower())
 
12331
 
 
12332
     def test_provides(self):
 
12333
         attrs = {"name": "package",
 
12334
@@ -271,9 +294,9 @@
 
12335
         self.assertEqual(dist.get_provides(),
 
12336
                          ["package", "package.sub"])
 
12337
         meta = self.format_metadata(dist)
 
12338
-        self.assertTrue("Metadata-Version: 1.1" in meta)
 
12339
-        self.assertTrue("requires:" not in meta.lower())
 
12340
-        self.assertTrue("obsoletes:" not in meta.lower())
 
12341
+        self.assertIn("Metadata-Version: 1.1", meta)
 
12342
+        self.assertNotIn("requires:", meta.lower())
 
12343
+        self.assertNotIn("obsoletes:", meta.lower())
 
12344
 
 
12345
     def test_provides_illegal(self):
 
12346
         self.assertRaises(ValueError, Distribution,
 
12347
@@ -291,11 +314,11 @@
 
12348
         self.assertEqual(dist.get_requires(),
 
12349
                          ["other", "another (==1.0)"])
 
12350
         meta = self.format_metadata(dist)
 
12351
-        self.assertTrue("Metadata-Version: 1.1" in meta)
 
12352
-        self.assertTrue("provides:" not in meta.lower())
 
12353
-        self.assertTrue("Requires: other" in meta)
 
12354
-        self.assertTrue("Requires: another (==1.0)" in meta)
 
12355
-        self.assertTrue("obsoletes:" not in meta.lower())
 
12356
+        self.assertIn("Metadata-Version: 1.1", meta)
 
12357
+        self.assertNotIn("provides:", meta.lower())
 
12358
+        self.assertIn("Requires: other", meta)
 
12359
+        self.assertIn("Requires: another (==1.0)", meta)
 
12360
+        self.assertNotIn("obsoletes:", meta.lower())
 
12361
 
 
12362
     def test_requires_illegal(self):
 
12363
         self.assertRaises(ValueError, Distribution,
 
12364
@@ -313,11 +336,11 @@
 
12365
         self.assertEqual(dist.get_obsoletes(),
 
12366
                          ["other", "another (<1.0)"])
 
12367
         meta = self.format_metadata(dist)
 
12368
-        self.assertTrue("Metadata-Version: 1.1" in meta)
 
12369
-        self.assertTrue("provides:" not in meta.lower())
 
12370
-        self.assertTrue("requires:" not in meta.lower())
 
12371
-        self.assertTrue("Obsoletes: other" in meta)
 
12372
-        self.assertTrue("Obsoletes: another (<1.0)" in meta)
 
12373
+        self.assertIn("Metadata-Version: 1.1", meta)
 
12374
+        self.assertNotIn("provides:", meta.lower())
 
12375
+        self.assertNotIn("requires:", meta.lower())
 
12376
+        self.assertIn("Obsoletes: other", meta)
 
12377
+        self.assertIn("Obsoletes: another (<1.0)", meta)
 
12378
 
 
12379
     def test_obsoletes_illegal(self):
 
12380
         self.assertRaises(ValueError, Distribution,
 
12381
@@ -353,14 +376,14 @@
 
12382
             if sys.platform in ('linux', 'darwin'):
 
12383
                 os.environ['HOME'] = temp_dir
 
12384
                 files = dist.find_config_files()
 
12385
-                self.assertTrue(user_filename in files)
 
12386
+                self.assertIn(user_filename, files)
 
12387
 
 
12388
             # win32-style
 
12389
             if sys.platform == 'win32':
 
12390
                 # home drive should be found
 
12391
                 os.environ['HOME'] = temp_dir
 
12392
                 files = dist.find_config_files()
 
12393
-                self.assertTrue(user_filename in files,
 
12394
+                self.assertIn(user_filename, files,
 
12395
                              '%r not found in %r' % (user_filename, files))
 
12396
         finally:
 
12397
             os.remove(user_filename)
 
12398
@@ -382,22 +405,7 @@
 
12399
 
 
12400
         output = [line for line in s.getvalue().split('\n')
 
12401
                   if line.strip() != '']
 
12402
-        self.assertTrue(len(output) > 0)
 
12403
-
 
12404
-    def test_long_description(self):
 
12405
-        long_desc = textwrap.dedent("""\
 
12406
-        example::
 
12407
-              We start here
 
12408
-            and continue here
 
12409
-          and end here.""")
 
12410
-        attrs = {"name": "package",
 
12411
-                 "version": "1.0",
 
12412
-                 "long_description": long_desc}
 
12413
-
 
12414
-        dist = distutils.dist.Distribution(attrs)
 
12415
-        meta = self.format_metadata(dist)
 
12416
-        meta = meta.replace('\n' + 8 * ' ', '\n')
 
12417
-        self.assertTrue(long_desc in meta)
 
12418
+        self.assertTrue(output)
 
12419
 
 
12420
     def test_read_metadata(self):
 
12421
         attrs = {"name": "package",
 
12422
@@ -426,6 +434,7 @@
 
12423
         self.assertEqual(metadata.obsoletes, None)
 
12424
         self.assertEqual(metadata.requires, ['foo'])
 
12425
 
 
12426
+
 
12427
 def test_suite():
 
12428
     suite = unittest.TestSuite()
 
12429
     suite.addTest(unittest.makeSuite(DistributionTestCase))
 
12430
diff -r 8527427914a2 Lib/distutils/tests/test_filelist.py
 
12431
--- a/Lib/distutils/tests/test_filelist.py
 
12432
+++ b/Lib/distutils/tests/test_filelist.py
 
12433
@@ -1,10 +1,14 @@
 
12434
 """Tests for distutils.filelist."""
 
12435
+import re
 
12436
+import unittest
 
12437
 from os.path import join
 
12438
-import unittest
 
12439
+from distutils import debug
 
12440
+from distutils.log import WARN
 
12441
+from distutils.errors import DistutilsTemplateError
 
12442
+from distutils.filelist import glob_to_re, translate_pattern, FileList
 
12443
+
 
12444
 from test.test_support import captured_stdout, run_unittest
 
12445
-
 
12446
-from distutils.filelist import glob_to_re, FileList
 
12447
-from distutils import debug
 
12448
+from distutils.tests import support
 
12449
 
 
12450
 MANIFEST_IN = """\
 
12451
 include ok
 
12452
@@ -20,7 +24,17 @@
 
12453
 prune dir3
 
12454
 """
 
12455
 
 
12456
-class FileListTestCase(unittest.TestCase):
 
12457
+
 
12458
+class FileListTestCase(support.LoggingSilencer,
 
12459
+                       unittest.TestCase):
 
12460
+
 
12461
+    def assertNoWarnings(self):
 
12462
+        self.assertEqual(self.get_logs(WARN), [])
 
12463
+        self.clear_logs()
 
12464
+
 
12465
+    def assertWarnings(self):
 
12466
+        self.assertGreater(len(self.get_logs(WARN)), 0)
 
12467
+        self.clear_logs()
 
12468
 
 
12469
     def test_glob_to_re(self):
 
12470
         # simple cases
 
12471
@@ -48,7 +62,7 @@
 
12472
                               join('dir', 'graft-one'),
 
12473
                               join('dir', 'dir2', 'graft2'),
 
12474
                               join('dir3', 'ok'),
 
12475
-                              join('dir3', 'sub', 'ok.txt')
 
12476
+                              join('dir3', 'sub', 'ok.txt'),
 
12477
                               ]
 
12478
 
 
12479
         for line in MANIFEST_IN.split('\n'):
 
12480
@@ -66,18 +80,191 @@
 
12481
         file_list = FileList()
 
12482
         with captured_stdout() as stdout:
 
12483
             file_list.debug_print('xxx')
 
12484
-        stdout.seek(0)
 
12485
-        self.assertEqual(stdout.read(), '')
 
12486
+        self.assertEqual(stdout.getvalue(), '')
 
12487
 
 
12488
         debug.DEBUG = True
 
12489
         try:
 
12490
             with captured_stdout() as stdout:
 
12491
                 file_list.debug_print('xxx')
 
12492
-            stdout.seek(0)
 
12493
-            self.assertEqual(stdout.read(), 'xxx\n')
 
12494
+            self.assertEqual(stdout.getvalue(), 'xxx\n')
 
12495
         finally:
 
12496
             debug.DEBUG = False
 
12497
 
 
12498
+    def test_set_allfiles(self):
 
12499
+        file_list = FileList()
 
12500
+        files = ['a', 'b', 'c']
 
12501
+        file_list.set_allfiles(files)
 
12502
+        self.assertEqual(file_list.allfiles, files)
 
12503
+
 
12504
+    def test_remove_duplicates(self):
 
12505
+        file_list = FileList()
 
12506
+        file_list.files = ['a', 'b', 'a', 'g', 'c', 'g']
 
12507
+        # files must be sorted beforehand (sdist does it)
 
12508
+        file_list.sort()
 
12509
+        file_list.remove_duplicates()
 
12510
+        self.assertEqual(file_list.files, ['a', 'b', 'c', 'g'])
 
12511
+
 
12512
+    def test_translate_pattern(self):
 
12513
+        # not regex
 
12514
+        self.assertTrue(hasattr(
 
12515
+            translate_pattern('a', anchor=True, is_regex=False),
 
12516
+            'search'))
 
12517
+
 
12518
+        # is a regex
 
12519
+        regex = re.compile('a')
 
12520
+        self.assertEqual(
 
12521
+            translate_pattern(regex, anchor=True, is_regex=True),
 
12522
+            regex)
 
12523
+
 
12524
+        # plain string flagged as regex
 
12525
+        self.assertTrue(hasattr(
 
12526
+            translate_pattern('a', anchor=True, is_regex=True),
 
12527
+            'search'))
 
12528
+
 
12529
+        # glob support
 
12530
+        self.assertTrue(translate_pattern(
 
12531
+            '*.py', anchor=True, is_regex=False).search('filelist.py'))
 
12532
+
 
12533
+    def test_exclude_pattern(self):
 
12534
+        # return False if no match
 
12535
+        file_list = FileList()
 
12536
+        self.assertFalse(file_list.exclude_pattern('*.py'))
 
12537
+
 
12538
+        # return True if files match
 
12539
+        file_list = FileList()
 
12540
+        file_list.files = ['a.py', 'b.py']
 
12541
+        self.assertTrue(file_list.exclude_pattern('*.py'))
 
12542
+
 
12543
+        # test excludes
 
12544
+        file_list = FileList()
 
12545
+        file_list.files = ['a.py', 'a.txt']
 
12546
+        file_list.exclude_pattern('*.py')
 
12547
+        self.assertEqual(file_list.files, ['a.txt'])
 
12548
+
 
12549
+    def test_include_pattern(self):
 
12550
+        # return False if no match
 
12551
+        file_list = FileList()
 
12552
+        file_list.set_allfiles([])
 
12553
+        self.assertFalse(file_list.include_pattern('*.py'))
 
12554
+
 
12555
+        # return True if files match
 
12556
+        file_list = FileList()
 
12557
+        file_list.set_allfiles(['a.py', 'b.txt'])
 
12558
+        self.assertTrue(file_list.include_pattern('*.py'))
 
12559
+
 
12560
+        # test * matches all files
 
12561
+        file_list = FileList()
 
12562
+        self.assertIsNone(file_list.allfiles)
 
12563
+        file_list.set_allfiles(['a.py', 'b.txt'])
 
12564
+        file_list.include_pattern('*')
 
12565
+        self.assertEqual(file_list.allfiles, ['a.py', 'b.txt'])
 
12566
+
 
12567
+    def test_process_template(self):
 
12568
+        # invalid lines
 
12569
+        file_list = FileList()
 
12570
+        for action in ('include', 'exclude', 'global-include',
 
12571
+                       'global-exclude', 'recursive-include',
 
12572
+                       'recursive-exclude', 'graft', 'prune', 'blarg'):
 
12573
+            self.assertRaises(DistutilsTemplateError,
 
12574
+                              file_list.process_template_line, action)
 
12575
+
 
12576
+        # include
 
12577
+        file_list = FileList()
 
12578
+        file_list.set_allfiles(['a.py', 'b.txt', 'd/c.py'])
 
12579
+
 
12580
+        file_list.process_template_line('include *.py')
 
12581
+        self.assertEqual(file_list.files, ['a.py'])
 
12582
+        self.assertNoWarnings()
 
12583
+
 
12584
+        file_list.process_template_line('include *.rb')
 
12585
+        self.assertEqual(file_list.files, ['a.py'])
 
12586
+        self.assertWarnings()
 
12587
+
 
12588
+        # exclude
 
12589
+        file_list = FileList()
 
12590
+        file_list.files = ['a.py', 'b.txt', 'd/c.py']
 
12591
+
 
12592
+        file_list.process_template_line('exclude *.py')
 
12593
+        self.assertEqual(file_list.files, ['b.txt', 'd/c.py'])
 
12594
+        self.assertNoWarnings()
 
12595
+
 
12596
+        file_list.process_template_line('exclude *.rb')
 
12597
+        self.assertEqual(file_list.files, ['b.txt', 'd/c.py'])
 
12598
+        self.assertWarnings()
 
12599
+
 
12600
+        # global-include
 
12601
+        file_list = FileList()
 
12602
+        file_list.set_allfiles(['a.py', 'b.txt', 'd/c.py'])
 
12603
+
 
12604
+        file_list.process_template_line('global-include *.py')
 
12605
+        self.assertEqual(file_list.files, ['a.py', 'd/c.py'])
 
12606
+        self.assertNoWarnings()
 
12607
+
 
12608
+        file_list.process_template_line('global-include *.rb')
 
12609
+        self.assertEqual(file_list.files, ['a.py', 'd/c.py'])
 
12610
+        self.assertWarnings()
 
12611
+
 
12612
+        # global-exclude
 
12613
+        file_list = FileList()
 
12614
+        file_list.files = ['a.py', 'b.txt', 'd/c.py']
 
12615
+
 
12616
+        file_list.process_template_line('global-exclude *.py')
 
12617
+        self.assertEqual(file_list.files, ['b.txt'])
 
12618
+        self.assertNoWarnings()
 
12619
+
 
12620
+        file_list.process_template_line('global-exclude *.rb')
 
12621
+        self.assertEqual(file_list.files, ['b.txt'])
 
12622
+        self.assertWarnings()
 
12623
+
 
12624
+        # recursive-include
 
12625
+        file_list = FileList()
 
12626
+        file_list.set_allfiles(['a.py', 'd/b.py', 'd/c.txt', 'd/d/e.py'])
 
12627
+
 
12628
+        file_list.process_template_line('recursive-include d *.py')
 
12629
+        self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py'])
 
12630
+        self.assertNoWarnings()
 
12631
+
 
12632
+        file_list.process_template_line('recursive-include e *.py')
 
12633
+        self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py'])
 
12634
+        self.assertWarnings()
 
12635
+
 
12636
+        # recursive-exclude
 
12637
+        file_list = FileList()
 
12638
+        file_list.files = ['a.py', 'd/b.py', 'd/c.txt', 'd/d/e.py']
 
12639
+
 
12640
+        file_list.process_template_line('recursive-exclude d *.py')
 
12641
+        self.assertEqual(file_list.files, ['a.py', 'd/c.txt'])
 
12642
+        self.assertNoWarnings()
 
12643
+
 
12644
+        file_list.process_template_line('recursive-exclude e *.py')
 
12645
+        self.assertEqual(file_list.files, ['a.py', 'd/c.txt'])
 
12646
+        self.assertWarnings()
 
12647
+
 
12648
+        # graft
 
12649
+        file_list = FileList()
 
12650
+        file_list.set_allfiles(['a.py', 'd/b.py', 'd/d/e.py', 'f/f.py'])
 
12651
+
 
12652
+        file_list.process_template_line('graft d')
 
12653
+        self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py'])
 
12654
+        self.assertNoWarnings()
 
12655
+
 
12656
+        file_list.process_template_line('graft e')
 
12657
+        self.assertEqual(file_list.files, ['d/b.py', 'd/d/e.py'])
 
12658
+        self.assertWarnings()
 
12659
+
 
12660
+        # prune
 
12661
+        file_list = FileList()
 
12662
+        file_list.files = ['a.py', 'd/b.py', 'd/d/e.py', 'f/f.py']
 
12663
+
 
12664
+        file_list.process_template_line('prune d')
 
12665
+        self.assertEqual(file_list.files, ['a.py', 'f/f.py'])
 
12666
+        self.assertNoWarnings()
 
12667
+
 
12668
+        file_list.process_template_line('prune e')
 
12669
+        self.assertEqual(file_list.files, ['a.py', 'f/f.py'])
 
12670
+        self.assertWarnings()
 
12671
+
 
12672
+
 
12673
 def test_suite():
 
12674
     return unittest.makeSuite(FileListTestCase)
 
12675
 
 
12676
diff -r 8527427914a2 Lib/distutils/tests/test_install.py
 
12677
--- a/Lib/distutils/tests/test_install.py
 
12678
+++ b/Lib/distutils/tests/test_install.py
 
12679
@@ -1,17 +1,33 @@
 
12680
 """Tests for distutils.command.install."""
 
12681
 
 
12682
 import os
 
12683
+import sys
 
12684
 import unittest
 
12685
+import site
 
12686
 
 
12687
-from test.test_support import run_unittest
 
12688
+from test.test_support import captured_stdout, run_unittest
 
12689
 
 
12690
+from distutils import sysconfig
 
12691
 from distutils.command.install import install
 
12692
+from distutils.command import install as install_module
 
12693
+from distutils.command.build_ext import build_ext
 
12694
+from distutils.command.install import INSTALL_SCHEMES
 
12695
 from distutils.core import Distribution
 
12696
+from distutils.errors import DistutilsOptionError
 
12697
+from distutils.extension import Extension
 
12698
 
 
12699
 from distutils.tests import support
 
12700
 
 
12701
 
 
12702
-class InstallTestCase(support.TempdirManager, unittest.TestCase):
 
12703
+def _make_ext_name(modname):
 
12704
+    if os.name == 'nt' and sys.executable.endswith('_d.exe'):
 
12705
+        modname += '_d'
 
12706
+    return modname + sysconfig.get_config_var('SO')
 
12707
+
 
12708
+
 
12709
+class InstallTestCase(support.TempdirManager,
 
12710
+                      support.LoggingSilencer,
 
12711
+                      unittest.TestCase):
 
12712
 
 
12713
     def test_home_installation_scheme(self):
 
12714
         # This ensure two things:
 
12715
@@ -49,6 +65,181 @@
 
12716
         check_path(cmd.install_scripts, os.path.join(destination, "bin"))
 
12717
         check_path(cmd.install_data, destination)
 
12718
 
 
12719
+    def test_user_site(self):
 
12720
+        # site.USER_SITE was introduced in 2.6
 
12721
+        if sys.version < '2.6':
 
12722
+            return
 
12723
+
 
12724
+        # preparing the environment for the test
 
12725
+        self.old_user_base = site.USER_BASE
 
12726
+        self.old_user_site = site.USER_SITE
 
12727
+        self.tmpdir = self.mkdtemp()
 
12728
+        self.user_base = os.path.join(self.tmpdir, 'B')
 
12729
+        self.user_site = os.path.join(self.tmpdir, 'S')
 
12730
+        site.USER_BASE = self.user_base
 
12731
+        site.USER_SITE = self.user_site
 
12732
+        install_module.USER_BASE = self.user_base
 
12733
+        install_module.USER_SITE = self.user_site
 
12734
+
 
12735
+        def _expanduser(path):
 
12736
+            return self.tmpdir
 
12737
+        self.old_expand = os.path.expanduser
 
12738
+        os.path.expanduser = _expanduser
 
12739
+
 
12740
+        try:
 
12741
+            # this is the actual test
 
12742
+            self._test_user_site()
 
12743
+        finally:
 
12744
+            site.USER_BASE = self.old_user_base
 
12745
+            site.USER_SITE = self.old_user_site
 
12746
+            install_module.USER_BASE = self.old_user_base
 
12747
+            install_module.USER_SITE = self.old_user_site
 
12748
+            os.path.expanduser = self.old_expand
 
12749
+
 
12750
+    def _test_user_site(self):
 
12751
+        for key in ('nt_user', 'unix_user', 'os2_home'):
 
12752
+            self.assertTrue(key in INSTALL_SCHEMES)
 
12753
+
 
12754
+        dist = Distribution({'name': 'xx'})
 
12755
+        cmd = install(dist)
 
12756
+
 
12757
+        # making sure the user option is there
 
12758
+        options = [name for name, short, lable in
 
12759
+                   cmd.user_options]
 
12760
+        self.assertTrue('user' in options)
 
12761
+
 
12762
+        # setting a value
 
12763
+        cmd.user = 1
 
12764
+
 
12765
+        # user base and site shouldn't be created yet
 
12766
+        self.assertTrue(not os.path.exists(self.user_base))
 
12767
+        self.assertTrue(not os.path.exists(self.user_site))
 
12768
+
 
12769
+        # let's run finalize
 
12770
+        cmd.ensure_finalized()
 
12771
+
 
12772
+        # now they should
 
12773
+        self.assertTrue(os.path.exists(self.user_base))
 
12774
+        self.assertTrue(os.path.exists(self.user_site))
 
12775
+
 
12776
+        self.assertTrue('userbase' in cmd.config_vars)
 
12777
+        self.assertTrue('usersite' in cmd.config_vars)
 
12778
+
 
12779
+    def test_handle_extra_path(self):
 
12780
+        dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
 
12781
+        cmd = install(dist)
 
12782
+
 
12783
+        # two elements
 
12784
+        cmd.handle_extra_path()
 
12785
+        self.assertEqual(cmd.extra_path, ['path', 'dirs'])
 
12786
+        self.assertEqual(cmd.extra_dirs, 'dirs')
 
12787
+        self.assertEqual(cmd.path_file, 'path')
 
12788
+
 
12789
+        # one element
 
12790
+        cmd.extra_path = ['path']
 
12791
+        cmd.handle_extra_path()
 
12792
+        self.assertEqual(cmd.extra_path, ['path'])
 
12793
+        self.assertEqual(cmd.extra_dirs, 'path')
 
12794
+        self.assertEqual(cmd.path_file, 'path')
 
12795
+
 
12796
+        # none
 
12797
+        dist.extra_path = cmd.extra_path = None
 
12798
+        cmd.handle_extra_path()
 
12799
+        self.assertEqual(cmd.extra_path, None)
 
12800
+        self.assertEqual(cmd.extra_dirs, '')
 
12801
+        self.assertEqual(cmd.path_file, None)
 
12802
+
 
12803
+        # three elements (no way !)
 
12804
+        cmd.extra_path = 'path,dirs,again'
 
12805
+        self.assertRaises(DistutilsOptionError, cmd.handle_extra_path)
 
12806
+
 
12807
+    def test_finalize_options(self):
 
12808
+        dist = Distribution({'name': 'xx'})
 
12809
+        cmd = install(dist)
 
12810
+
 
12811
+        # must supply either prefix/exec-prefix/home or
 
12812
+        # install-base/install-platbase -- not both
 
12813
+        cmd.prefix = 'prefix'
 
12814
+        cmd.install_base = 'base'
 
12815
+        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
 
12816
+
 
12817
+        # must supply either home or prefix/exec-prefix -- not both
 
12818
+        cmd.install_base = None
 
12819
+        cmd.home = 'home'
 
12820
+        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
 
12821
+
 
12822
+        # can't combine user with with prefix/exec_prefix/home or
 
12823
+        # install_(plat)base
 
12824
+        cmd.prefix = None
 
12825
+        cmd.user = 'user'
 
12826
+        self.assertRaises(DistutilsOptionError, cmd.finalize_options)
 
12827
+
 
12828
+    def test_record(self):
 
12829
+        install_dir = self.mkdtemp()
 
12830
+        project_dir, dist = self.create_dist(scripts=['hello'])
 
12831
+        self.addCleanup(os.chdir, os.getcwd())
 
12832
+        os.chdir(project_dir)
 
12833
+        self.write_file('hello', "print('o hai')")
 
12834
+
 
12835
+        cmd = install(dist)
 
12836
+        dist.command_obj['install'] = cmd
 
12837
+        cmd.root = install_dir
 
12838
+        cmd.record = os.path.join(project_dir, 'RECORD')
 
12839
+        cmd.ensure_finalized()
 
12840
+        cmd.run()
 
12841
+
 
12842
+        f = open(cmd.record)
 
12843
+        try:
 
12844
+            content = f.read()
 
12845
+        finally:
 
12846
+            f.close()
 
12847
+
 
12848
+        found = [os.path.basename(line) for line in content.splitlines()]
 
12849
+        expected = ['hello',
 
12850
+                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
 
12851
+        self.assertEqual(found, expected)
 
12852
+
 
12853
+    def test_record_extensions(self):
 
12854
+        install_dir = self.mkdtemp()
 
12855
+        project_dir, dist = self.create_dist(ext_modules=[
 
12856
+            Extension('xx', ['xxmodule.c'])])
 
12857
+        self.addCleanup(os.chdir, os.getcwd())
 
12858
+        os.chdir(project_dir)
 
12859
+        support.copy_xxmodule_c(project_dir)
 
12860
+
 
12861
+        buildextcmd = build_ext(dist)
 
12862
+        support.fixup_build_ext(buildextcmd)
 
12863
+        buildextcmd.ensure_finalized()
 
12864
+
 
12865
+        cmd = install(dist)
 
12866
+        dist.command_obj['install'] = cmd
 
12867
+        dist.command_obj['build_ext'] = buildextcmd
 
12868
+        cmd.root = install_dir
 
12869
+        cmd.record = os.path.join(project_dir, 'RECORD')
 
12870
+        cmd.ensure_finalized()
 
12871
+        cmd.run()
 
12872
+
 
12873
+        f = open(cmd.record)
 
12874
+        try:
 
12875
+            content = f.read()
 
12876
+        finally:
 
12877
+            f.close()
 
12878
+
 
12879
+        found = [os.path.basename(line) for line in content.splitlines()]
 
12880
+        expected = [_make_ext_name('xx'),
 
12881
+                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
 
12882
+        self.assertEqual(found, expected)
 
12883
+
 
12884
+    def test_debug_mode(self):
 
12885
+        # this covers the code called when DEBUG is set
 
12886
+        old_logs_len = len(self.logs)
 
12887
+        install_module.DEBUG = True
 
12888
+        try:
 
12889
+            with captured_stdout():
 
12890
+                self.test_record()
 
12891
+        finally:
 
12892
+            install_module.DEBUG = False
 
12893
+        self.assertTrue(len(self.logs) > old_logs_len)
 
12894
 
 
12895
 def test_suite():
 
12896
     return unittest.makeSuite(InstallTestCase)
 
12897
diff -r 8527427914a2 Lib/distutils/tests/test_msvc9compiler.py
 
12898
--- a/Lib/distutils/tests/test_msvc9compiler.py
 
12899
+++ b/Lib/distutils/tests/test_msvc9compiler.py
 
12900
@@ -7,7 +7,36 @@
 
12901
 from distutils.tests import support
 
12902
 from test.test_support import run_unittest
 
12903
 
 
12904
-_MANIFEST = """\
 
12905
+# A manifest with the only assembly reference being the msvcrt assembly, so
 
12906
+# should have the assembly completely stripped.  Note that although the
 
12907
+# assembly has a <security> reference the assembly is removed - that is
 
12908
+# currently a "feature", not a bug :)
 
12909
+_MANIFEST_WITH_ONLY_MSVC_REFERENCE = """\
 
12910
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 
12911
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1"
 
12912
+          manifestVersion="1.0">
 
12913
+  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
 
12914
+    <security>
 
12915
+      <requestedPrivileges>
 
12916
+        <requestedExecutionLevel level="asInvoker" uiAccess="false">
 
12917
+        </requestedExecutionLevel>
 
12918
+      </requestedPrivileges>
 
12919
+    </security>
 
12920
+  </trustInfo>
 
12921
+  <dependency>
 
12922
+    <dependentAssembly>
 
12923
+      <assemblyIdentity type="win32" name="Microsoft.VC90.CRT"
 
12924
+         version="9.0.21022.8" processorArchitecture="x86"
 
12925
+         publicKeyToken="XXXX">
 
12926
+      </assemblyIdentity>
 
12927
+    </dependentAssembly>
 
12928
+  </dependency>
 
12929
+</assembly>
 
12930
+"""
 
12931
+
 
12932
+# A manifest with references to assemblies other than msvcrt.  When processed,
 
12933
+# this assembly should be returned with just the msvcrt part removed.
 
12934
+_MANIFEST_WITH_MULTIPLE_REFERENCES = """\
 
12935
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 
12936
 <assembly xmlns="urn:schemas-microsoft-com:asm.v1"
 
12937
           manifestVersion="1.0">
 
12938
@@ -115,7 +144,7 @@
 
12939
         manifest = os.path.join(tempdir, 'manifest')
 
12940
         f = open(manifest, 'w')
 
12941
         try:
 
12942
-            f.write(_MANIFEST)
 
12943
+            f.write(_MANIFEST_WITH_MULTIPLE_REFERENCES)
 
12944
         finally:
 
12945
             f.close()
 
12946
 
 
12947
@@ -133,6 +162,20 @@
 
12948
         # makes sure the manifest was properly cleaned
 
12949
         self.assertEqual(content, _CLEANED_MANIFEST)
 
12950
 
 
12951
+    def test_remove_entire_manifest(self):
 
12952
+        from distutils.msvc9compiler import MSVCCompiler
 
12953
+        tempdir = self.mkdtemp()
 
12954
+        manifest = os.path.join(tempdir, 'manifest')
 
12955
+        f = open(manifest, 'w')
 
12956
+        try:
 
12957
+            f.write(_MANIFEST_WITH_ONLY_MSVC_REFERENCE)
 
12958
+        finally:
 
12959
+            f.close()
 
12960
+
 
12961
+        compiler = MSVCCompiler()
 
12962
+        got = compiler._remove_visual_c_ref(manifest)
 
12963
+        self.assertIs(got, None)
 
12964
+
 
12965
 
 
12966
 def test_suite():
 
12967
     return unittest.makeSuite(msvc9compilerTestCase)
 
12968
diff -r 8527427914a2 Lib/distutils/tests/test_register.py
 
12969
--- a/Lib/distutils/tests/test_register.py
 
12970
+++ b/Lib/distutils/tests/test_register.py
 
12971
@@ -1,5 +1,5 @@
 
12972
+# -*- encoding: utf8 -*-
 
12973
 """Tests for distutils.command.register."""
 
12974
-# -*- encoding: utf8 -*-
 
12975
 import sys
 
12976
 import os
 
12977
 import unittest
 
12978
@@ -246,6 +246,24 @@
 
12979
         finally:
 
12980
             del register_module.raw_input
 
12981
 
 
12982
+        # and finally a Unicode test (bug #12114)
 
12983
+        metadata = {'url': u'xxx', 'author': u'\u00c9ric',
 
12984
+                    'author_email': u'xxx', u'name': 'xxx',
 
12985
+                    'version': u'xxx',
 
12986
+                    'description': u'Something about esszet \u00df',
 
12987
+                    'long_description': u'More things about esszet \u00df'}
 
12988
+
 
12989
+        cmd = self._get_cmd(metadata)
 
12990
+        cmd.ensure_finalized()
 
12991
+        cmd.strict = 1
 
12992
+        inputs = RawInputs('1', 'tarek', 'y')
 
12993
+        register_module.raw_input = inputs.__call__
 
12994
+        # let's run the command
 
12995
+        try:
 
12996
+            cmd.run()
 
12997
+        finally:
 
12998
+            del register_module.raw_input
 
12999
+
 
13000
     def test_check_metadata_deprecated(self):
 
13001
         # makes sure make_metadata is deprecated
 
13002
         cmd = self._get_cmd()
4050
13003
diff -r 8527427914a2 Lib/distutils/tests/test_sdist.py
4051
13004
--- a/Lib/distutils/tests/test_sdist.py
4052
13005
+++ b/Lib/distutils/tests/test_sdist.py
4064
13017
 
4065
13018
 # zlib is not used here, but if it's not available
4066
13019
 # the tests that use zipfile may fail
4067
 
@@ -19,19 +21,13 @@
 
13020
@@ -19,20 +21,15 @@
4068
13021
 except ImportError:
4069
13022
     UID_GID_SUPPORT = False
4070
13023
 
4083
13036
 from distutils.spawn import find_executable
4084
13037
-from distutils.tests import support
4085
13038
 from distutils.log import WARN
 
13039
+from distutils.filelist import FileList
4086
13040
 from distutils.archive_util import ARCHIVE_FORMATS
4087
13041
 
4088
 
@@ -405,13 +401,33 @@
 
13042
 SETUP_PY = """
 
13043
@@ -89,9 +86,6 @@
 
13044
         dist.include_package_data = True
 
13045
         cmd = sdist(dist)
 
13046
         cmd.dist_dir = 'dist'
 
13047
-        def _warn(*args):
 
13048
-            pass
 
13049
-        cmd.warn = _warn
 
13050
         return dist, cmd
 
13051
 
 
13052
     @unittest.skipUnless(zlib, "requires zlib")
 
13053
@@ -246,7 +240,8 @@
 
13054
         # with the `check` subcommand
 
13055
         cmd.ensure_finalized()
 
13056
         cmd.run()
 
13057
-        warnings = self.get_logs(WARN)
 
13058
+        warnings = [msg for msg in self.get_logs(WARN) if
 
13059
+                    msg.startswith('warning: check:')]
 
13060
         self.assertEqual(len(warnings), 2)
 
13061
 
 
13062
         # trying with a complete set of metadata
 
13063
@@ -255,7 +250,8 @@
 
13064
         cmd.ensure_finalized()
 
13065
         cmd.metadata_check = 0
 
13066
         cmd.run()
 
13067
-        warnings = self.get_logs(WARN)
 
13068
+        warnings = [msg for msg in self.get_logs(WARN) if
 
13069
+                    msg.startswith('warning: check:')]
 
13070
         self.assertEqual(len(warnings), 0)
 
13071
 
 
13072
     def test_check_metadata_deprecated(self):
 
13073
@@ -277,7 +273,6 @@
 
13074
         self.assertEqual(len(output), num_formats)
 
13075
 
 
13076
     def test_finalize_options(self):
 
13077
-
 
13078
         dist, cmd = self.get_cmd()
 
13079
         cmd.finalize_options()
 
13080
 
 
13081
@@ -347,6 +342,32 @@
 
13082
         finally:
 
13083
             archive.close()
 
13084
 
 
13085
+    # the following tests make sure there is a nice error message instead
 
13086
+    # of a traceback when parsing an invalid manifest template
 
13087
+
 
13088
+    def _test_template(self, content):
 
13089
+        dist, cmd = self.get_cmd()
 
13090
+        os.chdir(self.tmp_dir)
 
13091
+        self.write_file('MANIFEST.in', content)
 
13092
+        cmd.ensure_finalized()
 
13093
+        cmd.filelist = FileList()
 
13094
+        cmd.read_template()
 
13095
+        warnings = self.get_logs(WARN)
 
13096
+        self.assertEqual(len(warnings), 1)
 
13097
+
 
13098
+    def test_invalid_template_unknown_command(self):
 
13099
+        self._test_template('taunt knights *')
 
13100
+
 
13101
+    def test_invalid_template_wrong_arguments(self):
 
13102
+        # this manifest command takes one argument
 
13103
+        self._test_template('prune')
 
13104
+
 
13105
+    @unittest.skipIf(os.name != 'nt', 'test relevant for Windows only')
 
13106
+    def test_invalid_template_wrong_path(self):
 
13107
+        # on Windows, trailing slashes are not allowed
 
13108
+        # this used to crash instead of raising a warning: #8286
 
13109
+        self._test_template('include examples/')
 
13110
+
 
13111
     @unittest.skipUnless(zlib, "requires zlib")
 
13112
     def test_get_file_list(self):
 
13113
         # make sure MANIFEST is recalculated
 
13114
@@ -355,6 +376,7 @@
 
13115
         # filling data_files by pointing files in package_data
 
13116
         dist.package_data = {'somecode': ['*.txt']}
 
13117
         self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
 
13118
+        cmd.formats = ['gztar']
 
13119
         cmd.ensure_finalized()
 
13120
         cmd.run()
 
13121
 
 
13122
@@ -405,13 +427,34 @@
4089
13123
         self.assertEqual(manifest[0],
4090
13124
                          '# file GENERATED by distutils, do NOT edit')
4091
13125
 
4110
13144
     def test_manual_manifest(self):
4111
13145
         # check that a MANIFEST without a marker is left alone
4112
13146
         dist, cmd = self.get_cmd()
 
13147
+        cmd.formats = ['gztar']
4113
13148
         cmd.ensure_finalized()
4114
13149
         self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
4115
13150
+        self.write_file((self.tmp_dir, 'README.manual'),
4119
13154
 
4120
13155
         f = open(cmd.manifest)
4121
13156
         try:
4122
 
@@ -422,6 +438,15 @@
 
13157
@@ -422,6 +465,15 @@
4123
13158
 
4124
13159
         self.assertEqual(manifest, ['README.manual'])
4125
13160
 
4238
13273
 
4239
13274
 try:
4240
13275
     import ssl
 
13276
diff -r 8527427914a2 Lib/heapq.py
 
13277
--- a/Lib/heapq.py
 
13278
+++ b/Lib/heapq.py
 
13279
@@ -193,6 +193,8 @@
 
13280
 
 
13281
     Equivalent to:  sorted(iterable, reverse=True)[:n]
 
13282
     """
 
13283
+    if n < 0:
 
13284
+        return []
 
13285
     it = iter(iterable)
 
13286
     result = list(islice(it, n))
 
13287
     if not result:
 
13288
@@ -209,6 +211,8 @@
 
13289
 
 
13290
     Equivalent to:  sorted(iterable)[:n]
 
13291
     """
 
13292
+    if n < 0:
 
13293
+        return []
 
13294
     if hasattr(iterable, '__len__') and n * 10 <= len(iterable):
 
13295
         # For smaller values of n, the bisect method is faster than a minheap.
 
13296
         # It is also memory efficient, consuming only n elements of space.
4241
13297
diff -r 8527427914a2 Lib/httplib.py
4242
13298
--- a/Lib/httplib.py
4243
13299
+++ b/Lib/httplib.py
4244
 
@@ -1322,71 +1322,3 @@
 
13300
@@ -715,7 +715,10 @@
 
13301
                 try:
 
13302
                     port = int(host[i+1:])
 
13303
                 except ValueError:
 
13304
-                    raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
 
13305
+                    if host[i+1:] == "":  # http://foo.com:/ == http://foo.com/
 
13306
+                        port = self.default_port
 
13307
+                    else:
 
13308
+                        raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
 
13309
                 host = host[:i]
 
13310
             else:
 
13311
                 port = self.default_port
 
13312
@@ -939,10 +942,10 @@
 
13313
         """Indicate that the last header line has been sent to the server.
 
13314
 
 
13315
         This method sends the request to the server.  The optional
 
13316
-        message_body argument can be used to pass message body
 
13317
+        message_body argument can be used to pass a message body
 
13318
         associated with the request.  The message body will be sent in
 
13319
-        the same packet as the message headers if possible.  The
 
13320
-        message_body should be a string.
 
13321
+        the same packet as the message headers if it is string, otherwise it is
 
13322
+        sent as a separate packet.
 
13323
         """
 
13324
         if self.__state == _CS_REQ_STARTED:
 
13325
             self.__state = _CS_REQ_SENT
 
13326
@@ -1322,71 +1325,3 @@
4245
13327
             return L + self._file.readlines()
4246
13328
         else:
4247
13329
             return L + self._file.readlines(size)
4337
13419
         except IOError:
4338
13420
             pass  ## file (probably __stderr__) is invalid, warning dropped.
4339
13421
     warnings.showwarning = idle_showwarning
 
13422
@@ -344,6 +344,7 @@
 
13423
         self.restarting = False
 
13424
         self.subprocess_arglist = None
 
13425
         self.port = PORT
 
13426
+        self.original_compiler_flags = self.compile.compiler.flags
 
13427
 
 
13428
     rpcclt = None
 
13429
     rpcpid = None
 
13430
@@ -459,6 +460,7 @@
 
13431
             gui = RemoteDebugger.restart_subprocess_debugger(self.rpcclt)
 
13432
             # reload remote debugger breakpoints for all PyShellEditWindows
 
13433
             debug.load_breakpoints()
 
13434
+        self.compile.compiler.flags = self.original_compiler_flags
 
13435
         self.restarting = False
 
13436
         return self.rpcclt
 
13437
 
 
13438
diff -r 8527427914a2 Lib/idlelib/ScriptBinding.py
 
13439
--- a/Lib/idlelib/ScriptBinding.py
 
13440
+++ b/Lib/idlelib/ScriptBinding.py
 
13441
@@ -101,7 +101,7 @@
 
13442
             try:
 
13443
                 # If successful, return the compiled code
 
13444
                 return compile(source, filename, "exec")
 
13445
-            except (SyntaxError, OverflowError), err:
 
13446
+            except (SyntaxError, OverflowError, ValueError), err:
 
13447
                 try:
 
13448
                     msg, (errorfilename, lineno, offset, line) = err
 
13449
                     if not errorfilename:
4340
13450
diff -r 8527427914a2 Lib/inspect.py
4341
13451
--- a/Lib/inspect.py
4342
13452
+++ b/Lib/inspect.py
4356
13466
     module = getmodule(object, file)
4357
13467
     if module:
4358
13468
         lines = linecache.getlines(file, module.__dict__)
 
13469
diff -r 8527427914a2 Lib/lib-tk/Tix.py
 
13470
--- a/Lib/lib-tk/Tix.py
 
13471
+++ b/Lib/lib-tk/Tix.py
 
13472
@@ -1874,13 +1874,13 @@
 
13473
         return self.tk.call(self, 'info', 'bbox', x, y)
 
13474
 
 
13475
     def move_column(self, from_, to, offset):
 
13476
-        """Moves the the range of columns from position FROM through TO by
 
13477
+        """Moves the range of columns from position FROM through TO by
 
13478
         the distance indicated by OFFSET. For example, move_column(2, 4, 1)
 
13479
         moves the columns 2,3,4 to columns 3,4,5."""
 
13480
         self.tk.call(self, 'move', 'column', from_, to, offset)
 
13481
 
 
13482
     def move_row(self, from_, to, offset):
 
13483
-        """Moves the the range of rows from position FROM through TO by
 
13484
+        """Moves the range of rows from position FROM through TO by
 
13485
         the distance indicated by OFFSET.
 
13486
         For example, move_row(2, 4, 1) moves the rows 2,3,4 to rows 3,4,5."""
 
13487
         self.tk.call(self, 'move', 'row', from_, to, offset)
 
13488
@@ -1939,7 +1939,7 @@
 
13489
               pad0 pixels
 
13490
                      Specifies the paddings to the top of a row.
 
13491
               pad1 pixels
 
13492
-                     Specifies the paddings to the the bottom of a row.
 
13493
+                     Specifies the paddings to the bottom of a row.
 
13494
               size val
 
13495
                      Specifies  the height of a row.
 
13496
                      Val may be: "auto" -- the height of the row  is  set  the
4359
13497
diff -r 8527427914a2 Lib/lib-tk/Tkinter.py
4360
13498
--- a/Lib/lib-tk/Tkinter.py
4361
13499
+++ b/Lib/lib-tk/Tkinter.py
4493
13631
 
4494
13632
 By combining together these and similar commands, intricate shapes and
4495
13633
 pictures can easily be drawn.
 
13634
@@ -96,7 +96,7 @@
 
13635
   docstrings to disc, so it can serve as a template for translations.
 
13636
 
 
13637
 Behind the scenes there are some features included with possible
 
13638
-extensions in in mind. These will be commented and documented elsewhere.
 
13639
+extensions in mind. These will be commented and documented elsewhere.
 
13640
 
 
13641
 """
 
13642
 
4496
13643
diff -r 8527427914a2 Lib/lib2to3/tests/test_refactor.py
4497
13644
--- a/Lib/lib2to3/tests/test_refactor.py
4498
13645
+++ b/Lib/lib2to3/tests/test_refactor.py
4533
13680
diff -r 8527427914a2 Lib/locale.py
4534
13681
--- a/Lib/locale.py
4535
13682
+++ b/Lib/locale.py
4536
 
@@ -331,6 +331,13 @@
 
13683
@@ -135,8 +135,6 @@
 
13684
     grouping = conv[monetary and 'mon_grouping' or 'grouping']
 
13685
     if not grouping:
 
13686
         return (s, 0)
 
13687
-    result = ""
 
13688
-    seps = 0
 
13689
     if s[-1] == ' ':
 
13690
         stripped = s.rstrip()
 
13691
         right_spaces = s[len(stripped):]
 
13692
@@ -331,6 +329,13 @@
4537
13693
 # overridden below)
4538
13694
 _setlocale = setlocale
4539
13695
 
4547
13703
 def normalize(localename):
4548
13704
 
4549
13705
     """ Returns a normalized locale code for the given locale
4550
 
@@ -348,7 +355,9 @@
 
13706
@@ -348,7 +353,9 @@
4551
13707
 
4552
13708
     """
4553
13709
     # Normalize the locale name and extract the encoding
4558
13714
     if ':' in fullname:
4559
13715
         # ':' is sometimes used as encoding delimiter.
4560
13716
         fullname = fullname.replace(':', '.')
 
13717
@@ -517,9 +524,10 @@
 
13718
 def setlocale(category, locale=None):
 
13719
 
 
13720
     """ Set the locale for the given category.  The locale can be
 
13721
-        a string, a locale tuple (language code, encoding), or None.
 
13722
+        a string, an iterable of two strings (language code and encoding),
 
13723
+        or None.
 
13724
 
 
13725
-        Locale tuples are converted to strings the locale aliasing
 
13726
+        Iterables are converted to strings using the locale aliasing
 
13727
         engine.  Locale strings are passed directly to the C lib.
 
13728
 
 
13729
         category may be given as one of the LC_* values.
 
13730
diff -r 8527427914a2 Lib/logging/__init__.py
 
13731
--- a/Lib/logging/__init__.py
 
13732
+++ b/Lib/logging/__init__.py
 
13733
@@ -478,8 +478,12 @@
 
13734
             except UnicodeError:
 
13735
                 # Sometimes filenames have non-ASCII chars, which can lead
 
13736
                 # to errors when s is Unicode and record.exc_text is str
 
13737
-                # See issue 8924
 
13738
-                s = s + record.exc_text.decode(sys.getfilesystemencoding())
 
13739
+                # See issue 8924.
 
13740
+                # We also use replace for when there are multiple
 
13741
+                # encodings, e.g. UTF-8 for the filesystem and latin-1
 
13742
+                # for a script. See issue 13232.
 
13743
+                s = s + record.exc_text.decode(sys.getfilesystemencoding(),
 
13744
+                                               'replace')
 
13745
         return s
 
13746
 
 
13747
 #
 
13748
@@ -1003,6 +1007,10 @@
 
13749
         placeholder to now point to the logger.
 
13750
         """
 
13751
         rv = None
 
13752
+        if not isinstance(name, basestring):
 
13753
+            raise TypeError('A logger name must be string or Unicode')
 
13754
+        if isinstance(name, unicode):
 
13755
+            name = name.encode('utf-8')
 
13756
         _acquireLock()
 
13757
         try:
 
13758
             if name in self.loggerDict:
 
13759
diff -r 8527427914a2 Lib/logging/config.py
 
13760
--- a/Lib/logging/config.py
 
13761
+++ b/Lib/logging/config.py
 
13762
@@ -211,7 +211,7 @@
 
13763
     #avoid disabling child loggers of explicitly
 
13764
     #named loggers. With a sorted list it is easier
 
13765
     #to find the child loggers.
 
13766
-    existing.sort(key=_encoded)
 
13767
+    existing.sort()
 
13768
     #We'll keep the list of existing loggers
 
13769
     #which are children of named loggers here...
 
13770
     child_loggers = []
 
13771
@@ -589,13 +589,14 @@
 
13772
                 #avoid disabling child loggers of explicitly
 
13773
                 #named loggers. With a sorted list it is easier
 
13774
                 #to find the child loggers.
 
13775
-                existing.sort(key=_encoded)
 
13776
+                existing.sort()
 
13777
                 #We'll keep the list of existing loggers
 
13778
                 #which are children of named loggers here...
 
13779
                 child_loggers = []
 
13780
                 #now set up the new ones...
 
13781
                 loggers = config.get('loggers', EMPTY_DICT)
 
13782
                 for name in loggers:
 
13783
+                    name = _encoded(name)
 
13784
                     if name in existing:
 
13785
                         i = existing.index(name)
 
13786
                         prefixed = name + "."
4561
13787
diff -r 8527427914a2 Lib/mailbox.py
4562
13788
--- a/Lib/mailbox.py
4563
13789
+++ b/Lib/mailbox.py
4564
 
@@ -1854,7 +1854,10 @@
 
13790
@@ -247,11 +247,9 @@
 
13791
             else:
 
13792
                 raise NoSuchMailboxError(self._path)
 
13793
         self._toc = {}
 
13794
-        self._toc_mtimes = {}
 
13795
-        for subdir in ('cur', 'new'):
 
13796
-            self._toc_mtimes[subdir] = os.path.getmtime(self._paths[subdir])
 
13797
-        self._last_read = time.time()  # Records last time we read cur/new
 
13798
-        self._skewfactor = 0.1         # Adjust if os/fs clocks are skewing
 
13799
+        self._toc_mtimes = {'cur': 0, 'new': 0}
 
13800
+        self._last_read = 0         # Records last time we read cur/new
 
13801
+        self._skewfactor = 0.1      # Adjust if os/fs clocks are skewing
 
13802
 
 
13803
     def add(self, message):
 
13804
         """Add message and return assigned key."""
 
13805
@@ -1854,7 +1852,10 @@
4565
13806
 
4566
13807
     def close(self):
4567
13808
         """Close the file."""
4573
13814
 
4574
13815
     def _read(self, size, read_method):
4575
13816
         """Read size bytes using read_method."""
4576
 
@@ -1898,6 +1901,12 @@
 
13817
@@ -1898,6 +1899,12 @@
4577
13818
             size = remaining
4578
13819
         return _ProxyFile._read(self, size, read_method)
4579
13820
 
4586
13827
 
4587
13828
 def _lock_file(f, dotlock=True):
4588
13829
     """Lock file f using lockf and dot locking."""
 
13830
diff -r 8527427914a2 Lib/msilib/schema.py
 
13831
--- a/Lib/msilib/schema.py
 
13832
+++ b/Lib/msilib/schema.py
 
13833
@@ -958,7 +958,7 @@
 
13834
 (u'ServiceInstall',u'StartType',u'N',0,4,None, None, None, None, u'Type of the service',),
 
13835
 (u'Shortcut',u'Name',u'N',None, None, None, None, u'Filename',None, u'The name of the shortcut to be created.',),
 
13836
 (u'Shortcut',u'Description',u'Y',None, None, None, None, u'Text',None, u'The description for the shortcut.',),
 
13837
-(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the the shortcut creation/deletion.',),
 
13838
+(u'Shortcut',u'Component_',u'N',None, None, u'Component',1,u'Identifier',None, u'Foreign key into the Component table denoting the component whose selection gates the shortcut creation/deletion.',),
 
13839
 (u'Shortcut',u'Icon_',u'Y',None, None, u'Icon',1,u'Identifier',None, u'Foreign key into the File table denoting the external icon file for the shortcut.',),
 
13840
 (u'Shortcut',u'IconIndex',u'Y',-32767,32767,None, None, None, None, u'The icon index for the shortcut.',),
 
13841
 (u'Shortcut',u'Directory_',u'N',None, None, u'Directory',1,u'Identifier',None, u'Foreign key into the Directory table denoting the directory where the shortcut file is created.',),
 
13842
diff -r 8527427914a2 Lib/multiprocessing/__init__.py
 
13843
--- a/Lib/multiprocessing/__init__.py
 
13844
+++ b/Lib/multiprocessing/__init__.py
 
13845
@@ -9,7 +9,7 @@
 
13846
 # wrapper for 'threading'.
 
13847
 #
 
13848
 # Try calling `multiprocessing.doc.main()` to read the html
 
13849
-# documentation in in a webbrowser.
 
13850
+# documentation in a webbrowser.
 
13851
 #
 
13852
 #
 
13853
 # Copyright (c) 2006-2008, R Oudkerk
4589
13854
diff -r 8527427914a2 Lib/multiprocessing/heap.py
4590
13855
--- a/Lib/multiprocessing/heap.py
4591
13856
+++ b/Lib/multiprocessing/heap.py
4664
13929
 
4665
13930
         if initializer is not None and not hasattr(initializer, '__call__'):
4666
13931
             raise TypeError('initializer must be a callable')
 
13932
@@ -292,7 +294,11 @@
 
13933
 
 
13934
     @staticmethod
 
13935
     def _handle_workers(pool):
 
13936
-        while pool._worker_handler._state == RUN and pool._state == RUN:
 
13937
+        thread = threading.current_thread()
 
13938
+
 
13939
+        # Keep maintaining workers until the cache gets drained, unless the pool
 
13940
+        # is terminated.
 
13941
+        while thread._state == RUN or (pool._cache and thread._state != TERMINATE):
 
13942
             pool._maintain_pool()
 
13943
             time.sleep(0.1)
 
13944
         # send sentinel to stop workers
 
13945
diff -r 8527427914a2 Lib/multiprocessing/queues.py
 
13946
--- a/Lib/multiprocessing/queues.py
 
13947
+++ b/Lib/multiprocessing/queues.py
 
13948
@@ -126,7 +126,11 @@
 
13949
             if not self._rlock.acquire(block, timeout):
 
13950
                 raise Empty
 
13951
             try:
 
13952
-                if not self._poll(block and (deadline-time.time()) or 0.0):
 
13953
+                if block:
 
13954
+                    timeout = deadline - time.time()
 
13955
+                    if timeout < 0 or not self._poll(timeout):
 
13956
+                        raise Empty
 
13957
+                elif not self._poll():
 
13958
                     raise Empty
 
13959
                 res = self._recv()
 
13960
                 self._sem.release()
 
13961
@@ -188,13 +192,7 @@
 
13962
         debug('... done self._thread.start()')
 
13963
 
 
13964
         # On process exit we will wait for data to be flushed to pipe.
 
13965
-        #
 
13966
-        # However, if this process created the queue then all
 
13967
-        # processes which use the queue will be descendants of this
 
13968
-        # process.  Therefore waiting for the queue to be flushed
 
13969
-        # is pointless once all the child processes have been joined.
 
13970
-        created_by_this_process = (self._opid == os.getpid())
 
13971
-        if not self._joincancelled and not created_by_this_process:
 
13972
+        if not self._joincancelled:
 
13973
             self._jointhread = Finalize(
 
13974
                 self._thread, Queue._finalize_join,
 
13975
                 [weakref.ref(self._thread)],
4667
13976
diff -r 8527427914a2 Lib/ntpath.py
4668
13977
--- a/Lib/ntpath.py
4669
13978
+++ b/Lib/ntpath.py
4681
13990
+except ImportError:
4682
13991
+    # Use genericpath.isdir as imported above.
4683
13992
+    pass
 
13993
diff -r 8527427914a2 Lib/pdb.py
 
13994
--- a/Lib/pdb.py
 
13995
+++ b/Lib/pdb.py
 
13996
@@ -1229,7 +1229,7 @@
 
13997
         self._wait_for_mainpyfile = 1
 
13998
         self.mainpyfile = self.canonic(filename)
 
13999
         self._user_requested_quit = 0
 
14000
-        statement = 'execfile( "%s")' % filename
 
14001
+        statement = 'execfile(%r)' % filename
 
14002
         self.run(statement)
 
14003
 
 
14004
 # Simplified interface
4684
14005
diff -r 8527427914a2 Lib/pickle.py
4685
14006
--- a/Lib/pickle.py
4686
14007
+++ b/Lib/pickle.py
4693
14014
 
4694
14015
 from types import *
4695
14016
 from copy_reg import dispatch_table
4696
 
diff -r 8527427914a2 Lib/plat-linux3/CDROM.py
4697
 
--- /dev/null
4698
 
+++ b/Lib/plat-linux3/CDROM.py
4699
 
@@ -0,0 +1,207 @@
4700
 
+# Generated by h2py from /usr/include/linux/cdrom.h
4701
 
+
4702
 
+CDROMPAUSE = 0x5301
4703
 
+CDROMRESUME = 0x5302
4704
 
+CDROMPLAYMSF = 0x5303
4705
 
+CDROMPLAYTRKIND = 0x5304
4706
 
+CDROMREADTOCHDR = 0x5305
4707
 
+CDROMREADTOCENTRY = 0x5306
4708
 
+CDROMSTOP = 0x5307
4709
 
+CDROMSTART = 0x5308
4710
 
+CDROMEJECT = 0x5309
4711
 
+CDROMVOLCTRL = 0x530a
4712
 
+CDROMSUBCHNL = 0x530b
4713
 
+CDROMREADMODE2 = 0x530c
4714
 
+CDROMREADMODE1 = 0x530d
4715
 
+CDROMREADAUDIO = 0x530e
4716
 
+CDROMEJECT_SW = 0x530f
4717
 
+CDROMMULTISESSION = 0x5310
4718
 
+CDROM_GET_MCN = 0x5311
4719
 
+CDROM_GET_UPC = CDROM_GET_MCN
4720
 
+CDROMRESET = 0x5312
4721
 
+CDROMVOLREAD = 0x5313
4722
 
+CDROMREADRAW = 0x5314
4723
 
+CDROMREADCOOKED = 0x5315
4724
 
+CDROMSEEK = 0x5316
4725
 
+CDROMPLAYBLK = 0x5317
4726
 
+CDROMREADALL = 0x5318
4727
 
+CDROMGETSPINDOWN = 0x531d
4728
 
+CDROMSETSPINDOWN = 0x531e
4729
 
+CDROMCLOSETRAY = 0x5319
4730
 
+CDROM_SET_OPTIONS = 0x5320
4731
 
+CDROM_CLEAR_OPTIONS = 0x5321
4732
 
+CDROM_SELECT_SPEED = 0x5322
4733
 
+CDROM_SELECT_DISC = 0x5323
4734
 
+CDROM_MEDIA_CHANGED = 0x5325
4735
 
+CDROM_DRIVE_STATUS = 0x5326
4736
 
+CDROM_DISC_STATUS = 0x5327
4737
 
+CDROM_CHANGER_NSLOTS = 0x5328
4738
 
+CDROM_LOCKDOOR = 0x5329
4739
 
+CDROM_DEBUG = 0x5330
4740
 
+CDROM_GET_CAPABILITY = 0x5331
4741
 
+CDROMAUDIOBUFSIZ = 0x5382
4742
 
+DVD_READ_STRUCT = 0x5390
4743
 
+DVD_WRITE_STRUCT = 0x5391
4744
 
+DVD_AUTH = 0x5392
4745
 
+CDROM_SEND_PACKET = 0x5393
4746
 
+CDROM_NEXT_WRITABLE = 0x5394
4747
 
+CDROM_LAST_WRITTEN = 0x5395
4748
 
+CDROM_PACKET_SIZE = 12
4749
 
+CGC_DATA_UNKNOWN = 0
4750
 
+CGC_DATA_WRITE = 1
4751
 
+CGC_DATA_READ = 2
4752
 
+CGC_DATA_NONE = 3
4753
 
+CD_MINS = 74
4754
 
+CD_SECS = 60
4755
 
+CD_FRAMES = 75
4756
 
+CD_SYNC_SIZE = 12
4757
 
+CD_MSF_OFFSET = 150
4758
 
+CD_CHUNK_SIZE = 24
4759
 
+CD_NUM_OF_CHUNKS = 98
4760
 
+CD_FRAMESIZE_SUB = 96
4761
 
+CD_HEAD_SIZE = 4
4762
 
+CD_SUBHEAD_SIZE = 8
4763
 
+CD_EDC_SIZE = 4
4764
 
+CD_ZERO_SIZE = 8
4765
 
+CD_ECC_SIZE = 276
4766
 
+CD_FRAMESIZE = 2048
4767
 
+CD_FRAMESIZE_RAW = 2352
4768
 
+CD_FRAMESIZE_RAWER = 2646
4769
 
+CD_FRAMESIZE_RAW1 = (CD_FRAMESIZE_RAW-CD_SYNC_SIZE)
4770
 
+CD_FRAMESIZE_RAW0 = (CD_FRAMESIZE_RAW-CD_SYNC_SIZE-CD_HEAD_SIZE)
4771
 
+CD_XA_HEAD = (CD_HEAD_SIZE+CD_SUBHEAD_SIZE)
4772
 
+CD_XA_TAIL = (CD_EDC_SIZE+CD_ECC_SIZE)
4773
 
+CD_XA_SYNC_HEAD = (CD_SYNC_SIZE+CD_XA_HEAD)
4774
 
+CDROM_LBA = 0x01
4775
 
+CDROM_MSF = 0x02
4776
 
+CDROM_DATA_TRACK = 0x04
4777
 
+CDROM_LEADOUT = 0xAA
4778
 
+CDROM_AUDIO_INVALID = 0x00
4779
 
+CDROM_AUDIO_PLAY = 0x11
4780
 
+CDROM_AUDIO_PAUSED = 0x12
4781
 
+CDROM_AUDIO_COMPLETED = 0x13
4782
 
+CDROM_AUDIO_ERROR = 0x14
4783
 
+CDROM_AUDIO_NO_STATUS = 0x15
4784
 
+CDC_CLOSE_TRAY = 0x1
4785
 
+CDC_OPEN_TRAY = 0x2
4786
 
+CDC_LOCK = 0x4
4787
 
+CDC_SELECT_SPEED = 0x8
4788
 
+CDC_SELECT_DISC = 0x10
4789
 
+CDC_MULTI_SESSION = 0x20
4790
 
+CDC_MCN = 0x40
4791
 
+CDC_MEDIA_CHANGED = 0x80
4792
 
+CDC_PLAY_AUDIO = 0x100
4793
 
+CDC_RESET = 0x200
4794
 
+CDC_IOCTLS = 0x400
4795
 
+CDC_DRIVE_STATUS = 0x800
4796
 
+CDC_GENERIC_PACKET = 0x1000
4797
 
+CDC_CD_R = 0x2000
4798
 
+CDC_CD_RW = 0x4000
4799
 
+CDC_DVD = 0x8000
4800
 
+CDC_DVD_R = 0x10000
4801
 
+CDC_DVD_RAM = 0x20000
4802
 
+CDS_NO_INFO = 0
4803
 
+CDS_NO_DISC = 1
4804
 
+CDS_TRAY_OPEN = 2
4805
 
+CDS_DRIVE_NOT_READY = 3
4806
 
+CDS_DISC_OK = 4
4807
 
+CDS_AUDIO = 100
4808
 
+CDS_DATA_1 = 101
4809
 
+CDS_DATA_2 = 102
4810
 
+CDS_XA_2_1 = 103
4811
 
+CDS_XA_2_2 = 104
4812
 
+CDS_MIXED = 105
4813
 
+CDO_AUTO_CLOSE = 0x1
4814
 
+CDO_AUTO_EJECT = 0x2
4815
 
+CDO_USE_FFLAGS = 0x4
4816
 
+CDO_LOCK = 0x8
4817
 
+CDO_CHECK_TYPE = 0x10
4818
 
+CD_PART_MAX = 64
4819
 
+CD_PART_MASK = (CD_PART_MAX - 1)
4820
 
+GPCMD_BLANK = 0xa1
4821
 
+GPCMD_CLOSE_TRACK = 0x5b
4822
 
+GPCMD_FLUSH_CACHE = 0x35
4823
 
+GPCMD_FORMAT_UNIT = 0x04
4824
 
+GPCMD_GET_CONFIGURATION = 0x46
4825
 
+GPCMD_GET_EVENT_STATUS_NOTIFICATION = 0x4a
4826
 
+GPCMD_GET_PERFORMANCE = 0xac
4827
 
+GPCMD_INQUIRY = 0x12
4828
 
+GPCMD_LOAD_UNLOAD = 0xa6
4829
 
+GPCMD_MECHANISM_STATUS = 0xbd
4830
 
+GPCMD_MODE_SELECT_10 = 0x55
4831
 
+GPCMD_MODE_SENSE_10 = 0x5a
4832
 
+GPCMD_PAUSE_RESUME = 0x4b
4833
 
+GPCMD_PLAY_AUDIO_10 = 0x45
4834
 
+GPCMD_PLAY_AUDIO_MSF = 0x47
4835
 
+GPCMD_PLAY_AUDIO_TI = 0x48
4836
 
+GPCMD_PLAY_CD = 0xbc
4837
 
+GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1e
4838
 
+GPCMD_READ_10 = 0x28
4839
 
+GPCMD_READ_12 = 0xa8
4840
 
+GPCMD_READ_CDVD_CAPACITY = 0x25
4841
 
+GPCMD_READ_CD = 0xbe
4842
 
+GPCMD_READ_CD_MSF = 0xb9
4843
 
+GPCMD_READ_DISC_INFO = 0x51
4844
 
+GPCMD_READ_DVD_STRUCTURE = 0xad
4845
 
+GPCMD_READ_FORMAT_CAPACITIES = 0x23
4846
 
+GPCMD_READ_HEADER = 0x44
4847
 
+GPCMD_READ_TRACK_RZONE_INFO = 0x52
4848
 
+GPCMD_READ_SUBCHANNEL = 0x42
4849
 
+GPCMD_READ_TOC_PMA_ATIP = 0x43
4850
 
+GPCMD_REPAIR_RZONE_TRACK = 0x58
4851
 
+GPCMD_REPORT_KEY = 0xa4
4852
 
+GPCMD_REQUEST_SENSE = 0x03
4853
 
+GPCMD_RESERVE_RZONE_TRACK = 0x53
4854
 
+GPCMD_SCAN = 0xba
4855
 
+GPCMD_SEEK = 0x2b
4856
 
+GPCMD_SEND_DVD_STRUCTURE = 0xad
4857
 
+GPCMD_SEND_EVENT = 0xa2
4858
 
+GPCMD_SEND_KEY = 0xa3
4859
 
+GPCMD_SEND_OPC = 0x54
4860
 
+GPCMD_SET_READ_AHEAD = 0xa7
4861
 
+GPCMD_SET_STREAMING = 0xb6
4862
 
+GPCMD_START_STOP_UNIT = 0x1b
4863
 
+GPCMD_STOP_PLAY_SCAN = 0x4e
4864
 
+GPCMD_TEST_UNIT_READY = 0x00
4865
 
+GPCMD_VERIFY_10 = 0x2f
4866
 
+GPCMD_WRITE_10 = 0x2a
4867
 
+GPCMD_WRITE_AND_VERIFY_10 = 0x2e
4868
 
+GPCMD_SET_SPEED = 0xbb
4869
 
+GPCMD_PLAYAUDIO_TI = 0x48
4870
 
+GPCMD_GET_MEDIA_STATUS = 0xda
4871
 
+GPMODE_R_W_ERROR_PAGE = 0x01
4872
 
+GPMODE_WRITE_PARMS_PAGE = 0x05
4873
 
+GPMODE_AUDIO_CTL_PAGE = 0x0e
4874
 
+GPMODE_POWER_PAGE = 0x1a
4875
 
+GPMODE_FAULT_FAIL_PAGE = 0x1c
4876
 
+GPMODE_TO_PROTECT_PAGE = 0x1d
4877
 
+GPMODE_CAPABILITIES_PAGE = 0x2a
4878
 
+GPMODE_ALL_PAGES = 0x3f
4879
 
+GPMODE_CDROM_PAGE = 0x0d
4880
 
+DVD_STRUCT_PHYSICAL = 0x00
4881
 
+DVD_STRUCT_COPYRIGHT = 0x01
4882
 
+DVD_STRUCT_DISCKEY = 0x02
4883
 
+DVD_STRUCT_BCA = 0x03
4884
 
+DVD_STRUCT_MANUFACT = 0x04
4885
 
+DVD_LAYERS = 4
4886
 
+DVD_LU_SEND_AGID = 0
4887
 
+DVD_HOST_SEND_CHALLENGE = 1
4888
 
+DVD_LU_SEND_KEY1 = 2
4889
 
+DVD_LU_SEND_CHALLENGE = 3
4890
 
+DVD_HOST_SEND_KEY2 = 4
4891
 
+DVD_AUTH_ESTABLISHED = 5
4892
 
+DVD_AUTH_FAILURE = 6
4893
 
+DVD_LU_SEND_TITLE_KEY = 7
4894
 
+DVD_LU_SEND_ASF = 8
4895
 
+DVD_INVALIDATE_AGID = 9
4896
 
+DVD_LU_SEND_RPC_STATE = 10
4897
 
+DVD_HOST_SEND_RPC_STATE = 11
4898
 
+DVD_CPM_NO_COPYRIGHT = 0
4899
 
+DVD_CPM_COPYRIGHTED = 1
4900
 
+DVD_CP_SEC_NONE = 0
4901
 
+DVD_CP_SEC_EXIST = 1
4902
 
+DVD_CGMS_UNRESTRICTED = 0
4903
 
+DVD_CGMS_SINGLE = 2
4904
 
+DVD_CGMS_RESTRICTED = 3
4905
 
+
4906
 
+CDROM_MAX_SLOTS = 256
4907
 
diff -r 8527427914a2 Lib/plat-linux3/DLFCN.py
4908
 
--- /dev/null
4909
 
+++ b/Lib/plat-linux3/DLFCN.py
4910
 
@@ -0,0 +1,83 @@
4911
 
+# Generated by h2py from /usr/include/dlfcn.h
4912
 
+_DLFCN_H = 1
4913
 
+
4914
 
+# Included from features.h
4915
 
+_FEATURES_H = 1
4916
 
+__USE_ANSI = 1
4917
 
+__FAVOR_BSD = 1
4918
 
+_ISOC99_SOURCE = 1
4919
 
+_POSIX_SOURCE = 1
4920
 
+_POSIX_C_SOURCE = 199506L
4921
 
+_XOPEN_SOURCE = 600
4922
 
+_XOPEN_SOURCE_EXTENDED = 1
4923
 
+_LARGEFILE64_SOURCE = 1
4924
 
+_BSD_SOURCE = 1
4925
 
+_SVID_SOURCE = 1
4926
 
+_BSD_SOURCE = 1
4927
 
+_SVID_SOURCE = 1
4928
 
+__USE_ISOC99 = 1
4929
 
+_POSIX_SOURCE = 1
4930
 
+_POSIX_C_SOURCE = 2
4931
 
+_POSIX_C_SOURCE = 199506L
4932
 
+__USE_POSIX = 1
4933
 
+__USE_POSIX2 = 1
4934
 
+__USE_POSIX199309 = 1
4935
 
+__USE_POSIX199506 = 1
4936
 
+__USE_XOPEN = 1
4937
 
+__USE_XOPEN_EXTENDED = 1
4938
 
+__USE_UNIX98 = 1
4939
 
+_LARGEFILE_SOURCE = 1
4940
 
+__USE_XOPEN2K = 1
4941
 
+__USE_ISOC99 = 1
4942
 
+__USE_XOPEN_EXTENDED = 1
4943
 
+__USE_LARGEFILE = 1
4944
 
+__USE_LARGEFILE64 = 1
4945
 
+__USE_FILE_OFFSET64 = 1
4946
 
+__USE_MISC = 1
4947
 
+__USE_BSD = 1
4948
 
+__USE_SVID = 1
4949
 
+__USE_GNU = 1
4950
 
+__USE_REENTRANT = 1
4951
 
+__STDC_IEC_559__ = 1
4952
 
+__STDC_IEC_559_COMPLEX__ = 1
4953
 
+__STDC_ISO_10646__ = 200009L
4954
 
+__GNU_LIBRARY__ = 6
4955
 
+__GLIBC__ = 2
4956
 
+__GLIBC_MINOR__ = 2
4957
 
+
4958
 
+# Included from sys/cdefs.h
4959
 
+_SYS_CDEFS_H = 1
4960
 
+def __PMT(args): return args
4961
 
+
4962
 
+def __P(args): return args
4963
 
+
4964
 
+def __PMT(args): return args
4965
 
+
4966
 
+def __STRING(x): return #x
4967
 
+
4968
 
+__flexarr = []
4969
 
+__flexarr = [0]
4970
 
+__flexarr = []
4971
 
+__flexarr = [1]
4972
 
+def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
4973
 
+
4974
 
+def __attribute__(xyz): return
4975
 
+
4976
 
+def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x)))
4977
 
+
4978
 
+def __attribute_format_arg__(x): return
4979
 
+
4980
 
+__USE_LARGEFILE = 1
4981
 
+__USE_LARGEFILE64 = 1
4982
 
+__USE_EXTERN_INLINES = 1
4983
 
+
4984
 
+# Included from gnu/stubs.h
4985
 
+
4986
 
+# Included from bits/dlfcn.h
4987
 
+RTLD_LAZY = 0x00001
4988
 
+RTLD_NOW = 0x00002
4989
 
+RTLD_BINDING_MASK = 0x3
4990
 
+RTLD_NOLOAD = 0x00004
4991
 
+RTLD_GLOBAL = 0x00100
4992
 
+RTLD_LOCAL = 0
4993
 
+RTLD_NODELETE = 0x01000
4994
 
diff -r 8527427914a2 Lib/plat-linux3/IN.py
4995
 
--- /dev/null
4996
 
+++ b/Lib/plat-linux3/IN.py
4997
 
@@ -0,0 +1,615 @@
4998
 
+# Generated by h2py from /usr/include/netinet/in.h
4999
 
+_NETINET_IN_H = 1
5000
 
+
5001
 
+# Included from features.h
5002
 
+_FEATURES_H = 1
5003
 
+__USE_ANSI = 1
5004
 
+__FAVOR_BSD = 1
5005
 
+_ISOC99_SOURCE = 1
5006
 
+_POSIX_SOURCE = 1
5007
 
+_POSIX_C_SOURCE = 199506L
5008
 
+_XOPEN_SOURCE = 600
5009
 
+_XOPEN_SOURCE_EXTENDED = 1
5010
 
+_LARGEFILE64_SOURCE = 1
5011
 
+_BSD_SOURCE = 1
5012
 
+_SVID_SOURCE = 1
5013
 
+_BSD_SOURCE = 1
5014
 
+_SVID_SOURCE = 1
5015
 
+__USE_ISOC99 = 1
5016
 
+_POSIX_SOURCE = 1
5017
 
+_POSIX_C_SOURCE = 2
5018
 
+_POSIX_C_SOURCE = 199506L
5019
 
+__USE_POSIX = 1
5020
 
+__USE_POSIX2 = 1
5021
 
+__USE_POSIX199309 = 1
5022
 
+__USE_POSIX199506 = 1
5023
 
+__USE_XOPEN = 1
5024
 
+__USE_XOPEN_EXTENDED = 1
5025
 
+__USE_UNIX98 = 1
5026
 
+_LARGEFILE_SOURCE = 1
5027
 
+__USE_XOPEN2K = 1
5028
 
+__USE_ISOC99 = 1
5029
 
+__USE_XOPEN_EXTENDED = 1
5030
 
+__USE_LARGEFILE = 1
5031
 
+__USE_LARGEFILE64 = 1
5032
 
+__USE_FILE_OFFSET64 = 1
5033
 
+__USE_MISC = 1
5034
 
+__USE_BSD = 1
5035
 
+__USE_SVID = 1
5036
 
+__USE_GNU = 1
5037
 
+__USE_REENTRANT = 1
5038
 
+__STDC_IEC_559__ = 1
5039
 
+__STDC_IEC_559_COMPLEX__ = 1
5040
 
+__STDC_ISO_10646__ = 200009L
5041
 
+__GNU_LIBRARY__ = 6
5042
 
+__GLIBC__ = 2
5043
 
+__GLIBC_MINOR__ = 2
5044
 
+
5045
 
+# Included from sys/cdefs.h
5046
 
+_SYS_CDEFS_H = 1
5047
 
+def __PMT(args): return args
5048
 
+
5049
 
+def __P(args): return args
5050
 
+
5051
 
+def __PMT(args): return args
5052
 
+
5053
 
+def __STRING(x): return #x
5054
 
+
5055
 
+__flexarr = []
5056
 
+__flexarr = [0]
5057
 
+__flexarr = []
5058
 
+__flexarr = [1]
5059
 
+def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
5060
 
+
5061
 
+def __attribute__(xyz): return
5062
 
+
5063
 
+def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x)))
5064
 
+
5065
 
+def __attribute_format_arg__(x): return
5066
 
+
5067
 
+__USE_LARGEFILE = 1
5068
 
+__USE_LARGEFILE64 = 1
5069
 
+__USE_EXTERN_INLINES = 1
5070
 
+
5071
 
+# Included from gnu/stubs.h
5072
 
+
5073
 
+# Included from stdint.h
5074
 
+_STDINT_H = 1
5075
 
+
5076
 
+# Included from bits/wchar.h
5077
 
+_BITS_WCHAR_H = 1
5078
 
+__WCHAR_MIN = (-2147483647l - 1l)
5079
 
+__WCHAR_MAX = (2147483647l)
5080
 
+
5081
 
+# Included from bits/wordsize.h
5082
 
+__WORDSIZE = 32
5083
 
+def __INT64_C(c): return c ## L
5084
 
+
5085
 
+def __UINT64_C(c): return c ## UL
5086
 
+
5087
 
+def __INT64_C(c): return c ## LL
5088
 
+
5089
 
+def __UINT64_C(c): return c ## ULL
5090
 
+
5091
 
+INT8_MIN = (-128)
5092
 
+INT16_MIN = (-32767-1)
5093
 
+INT32_MIN = (-2147483647-1)
5094
 
+INT64_MIN = (-__INT64_C(9223372036854775807)-1)
5095
 
+INT8_MAX = (127)
5096
 
+INT16_MAX = (32767)
5097
 
+INT32_MAX = (2147483647)
5098
 
+INT64_MAX = (__INT64_C(9223372036854775807))
5099
 
+UINT8_MAX = (255)
5100
 
+UINT16_MAX = (65535)
5101
 
+UINT64_MAX = (__UINT64_C(18446744073709551615))
5102
 
+INT_LEAST8_MIN = (-128)
5103
 
+INT_LEAST16_MIN = (-32767-1)
5104
 
+INT_LEAST32_MIN = (-2147483647-1)
5105
 
+INT_LEAST64_MIN = (-__INT64_C(9223372036854775807)-1)
5106
 
+INT_LEAST8_MAX = (127)
5107
 
+INT_LEAST16_MAX = (32767)
5108
 
+INT_LEAST32_MAX = (2147483647)
5109
 
+INT_LEAST64_MAX = (__INT64_C(9223372036854775807))
5110
 
+UINT_LEAST8_MAX = (255)
5111
 
+UINT_LEAST16_MAX = (65535)
5112
 
+UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615))
5113
 
+INT_FAST8_MIN = (-128)
5114
 
+INT_FAST16_MIN = (-9223372036854775807L-1)
5115
 
+INT_FAST32_MIN = (-9223372036854775807L-1)
5116
 
+INT_FAST16_MIN = (-2147483647-1)
5117
 
+INT_FAST32_MIN = (-2147483647-1)
5118
 
+INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1)
5119
 
+INT_FAST8_MAX = (127)
5120
 
+INT_FAST16_MAX = (9223372036854775807L)
5121
 
+INT_FAST32_MAX = (9223372036854775807L)
5122
 
+INT_FAST16_MAX = (2147483647)
5123
 
+INT_FAST32_MAX = (2147483647)
5124
 
+INT_FAST64_MAX = (__INT64_C(9223372036854775807))
5125
 
+UINT_FAST8_MAX = (255)
5126
 
+UINT_FAST64_MAX = (__UINT64_C(18446744073709551615))
5127
 
+INTPTR_MIN = (-9223372036854775807L-1)
5128
 
+INTPTR_MAX = (9223372036854775807L)
5129
 
+INTPTR_MIN = (-2147483647-1)
5130
 
+INTPTR_MAX = (2147483647)
5131
 
+INTMAX_MIN = (-__INT64_C(9223372036854775807)-1)
5132
 
+INTMAX_MAX = (__INT64_C(9223372036854775807))
5133
 
+UINTMAX_MAX = (__UINT64_C(18446744073709551615))
5134
 
+PTRDIFF_MIN = (-9223372036854775807L-1)
5135
 
+PTRDIFF_MAX = (9223372036854775807L)
5136
 
+PTRDIFF_MIN = (-2147483647-1)
5137
 
+PTRDIFF_MAX = (2147483647)
5138
 
+SIG_ATOMIC_MIN = (-2147483647-1)
5139
 
+SIG_ATOMIC_MAX = (2147483647)
5140
 
+WCHAR_MIN = __WCHAR_MIN
5141
 
+WCHAR_MAX = __WCHAR_MAX
5142
 
+def INT8_C(c): return c
5143
 
+
5144
 
+def INT16_C(c): return c
5145
 
+
5146
 
+def INT32_C(c): return c
5147
 
+
5148
 
+def INT64_C(c): return c ## L
5149
 
+
5150
 
+def INT64_C(c): return c ## LL
5151
 
+
5152
 
+def UINT8_C(c): return c ## U
5153
 
+
5154
 
+def UINT16_C(c): return c ## U
5155
 
+
5156
 
+def UINT32_C(c): return c ## U
5157
 
+
5158
 
+def UINT64_C(c): return c ## UL
5159
 
+
5160
 
+def UINT64_C(c): return c ## ULL
5161
 
+
5162
 
+def INTMAX_C(c): return c ## L
5163
 
+
5164
 
+def UINTMAX_C(c): return c ## UL
5165
 
+
5166
 
+def INTMAX_C(c): return c ## LL
5167
 
+
5168
 
+def UINTMAX_C(c): return c ## ULL
5169
 
+
5170
 
+
5171
 
+# Included from bits/types.h
5172
 
+_BITS_TYPES_H = 1
5173
 
+__FD_SETSIZE = 1024
5174
 
+
5175
 
+# Included from bits/pthreadtypes.h
5176
 
+_BITS_PTHREADTYPES_H = 1
5177
 
+
5178
 
+# Included from bits/sched.h
5179
 
+SCHED_OTHER = 0
5180
 
+SCHED_FIFO = 1
5181
 
+SCHED_RR = 2
5182
 
+CSIGNAL = 0x000000ff
5183
 
+CLONE_VM = 0x00000100
5184
 
+CLONE_FS = 0x00000200
5185
 
+CLONE_FILES = 0x00000400
5186
 
+CLONE_SIGHAND = 0x00000800
5187
 
+CLONE_PID = 0x00001000
5188
 
+CLONE_PTRACE = 0x00002000
5189
 
+CLONE_VFORK = 0x00004000
5190
 
+__defined_schedparam = 1
5191
 
+def IN_CLASSA(a): return ((((in_addr_t)(a)) & (-2147483648)) == 0)
5192
 
+
5193
 
+IN_CLASSA_NET = (-16777216)
5194
 
+IN_CLASSA_NSHIFT = 24
5195
 
+IN_CLASSA_HOST = ((-1) & ~IN_CLASSA_NET)
5196
 
+IN_CLASSA_MAX = 128
5197
 
+def IN_CLASSB(a): return ((((in_addr_t)(a)) & (-1073741824)) == (-2147483648))
5198
 
+
5199
 
+IN_CLASSB_NET = (-65536)
5200
 
+IN_CLASSB_NSHIFT = 16
5201
 
+IN_CLASSB_HOST = ((-1) & ~IN_CLASSB_NET)
5202
 
+IN_CLASSB_MAX = 65536
5203
 
+def IN_CLASSC(a): return ((((in_addr_t)(a)) & (-536870912)) == (-1073741824))
5204
 
+
5205
 
+IN_CLASSC_NET = (-256)
5206
 
+IN_CLASSC_NSHIFT = 8
5207
 
+IN_CLASSC_HOST = ((-1) & ~IN_CLASSC_NET)
5208
 
+def IN_CLASSD(a): return ((((in_addr_t)(a)) & (-268435456)) == (-536870912))
5209
 
+
5210
 
+def IN_MULTICAST(a): return IN_CLASSD(a)
5211
 
+
5212
 
+def IN_EXPERIMENTAL(a): return ((((in_addr_t)(a)) & (-536870912)) == (-536870912))
5213
 
+
5214
 
+def IN_BADCLASS(a): return ((((in_addr_t)(a)) & (-268435456)) == (-268435456))
5215
 
+
5216
 
+IN_LOOPBACKNET = 127
5217
 
+INET_ADDRSTRLEN = 16
5218
 
+INET6_ADDRSTRLEN = 46
5219
 
+
5220
 
+# Included from bits/socket.h
5221
 
+
5222
 
+# Included from limits.h
5223
 
+_LIBC_LIMITS_H_ = 1
5224
 
+MB_LEN_MAX = 16
5225
 
+_LIMITS_H = 1
5226
 
+CHAR_BIT = 8
5227
 
+SCHAR_MIN = (-128)
5228
 
+SCHAR_MAX = 127
5229
 
+UCHAR_MAX = 255
5230
 
+CHAR_MIN = 0
5231
 
+CHAR_MAX = UCHAR_MAX
5232
 
+CHAR_MIN = SCHAR_MIN
5233
 
+CHAR_MAX = SCHAR_MAX
5234
 
+SHRT_MIN = (-32768)
5235
 
+SHRT_MAX = 32767
5236
 
+USHRT_MAX = 65535
5237
 
+INT_MAX = 2147483647
5238
 
+LONG_MAX = 9223372036854775807L
5239
 
+LONG_MAX = 2147483647L
5240
 
+LONG_MIN = (-LONG_MAX - 1L)
5241
 
+
5242
 
+# Included from bits/posix1_lim.h
5243
 
+_BITS_POSIX1_LIM_H = 1
5244
 
+_POSIX_AIO_LISTIO_MAX = 2
5245
 
+_POSIX_AIO_MAX = 1
5246
 
+_POSIX_ARG_MAX = 4096
5247
 
+_POSIX_CHILD_MAX = 6
5248
 
+_POSIX_DELAYTIMER_MAX = 32
5249
 
+_POSIX_LINK_MAX = 8
5250
 
+_POSIX_MAX_CANON = 255
5251
 
+_POSIX_MAX_INPUT = 255
5252
 
+_POSIX_MQ_OPEN_MAX = 8
5253
 
+_POSIX_MQ_PRIO_MAX = 32
5254
 
+_POSIX_NGROUPS_MAX = 0
5255
 
+_POSIX_OPEN_MAX = 16
5256
 
+_POSIX_FD_SETSIZE = _POSIX_OPEN_MAX
5257
 
+_POSIX_NAME_MAX = 14
5258
 
+_POSIX_PATH_MAX = 256
5259
 
+_POSIX_PIPE_BUF = 512
5260
 
+_POSIX_RTSIG_MAX = 8
5261
 
+_POSIX_SEM_NSEMS_MAX = 256
5262
 
+_POSIX_SEM_VALUE_MAX = 32767
5263
 
+_POSIX_SIGQUEUE_MAX = 32
5264
 
+_POSIX_SSIZE_MAX = 32767
5265
 
+_POSIX_STREAM_MAX = 8
5266
 
+_POSIX_TZNAME_MAX = 6
5267
 
+_POSIX_QLIMIT = 1
5268
 
+_POSIX_HIWAT = _POSIX_PIPE_BUF
5269
 
+_POSIX_UIO_MAXIOV = 16
5270
 
+_POSIX_TTY_NAME_MAX = 9
5271
 
+_POSIX_TIMER_MAX = 32
5272
 
+_POSIX_LOGIN_NAME_MAX = 9
5273
 
+_POSIX_CLOCKRES_MIN = 20000000
5274
 
+
5275
 
+# Included from bits/local_lim.h
5276
 
+
5277
 
+# Included from linux/limits.h
5278
 
+NR_OPEN = 1024
5279
 
+NGROUPS_MAX = 32
5280
 
+ARG_MAX = 131072
5281
 
+CHILD_MAX = 999
5282
 
+OPEN_MAX = 256
5283
 
+LINK_MAX = 127
5284
 
+MAX_CANON = 255
5285
 
+MAX_INPUT = 255
5286
 
+NAME_MAX = 255
5287
 
+PATH_MAX = 4096
5288
 
+PIPE_BUF = 4096
5289
 
+RTSIG_MAX = 32
5290
 
+_POSIX_THREAD_KEYS_MAX = 128
5291
 
+PTHREAD_KEYS_MAX = 1024
5292
 
+_POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4
5293
 
+PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS
5294
 
+_POSIX_THREAD_THREADS_MAX = 64
5295
 
+PTHREAD_THREADS_MAX = 1024
5296
 
+AIO_PRIO_DELTA_MAX = 20
5297
 
+PTHREAD_STACK_MIN = 16384
5298
 
+TIMER_MAX = 256
5299
 
+SSIZE_MAX = LONG_MAX
5300
 
+NGROUPS_MAX = _POSIX_NGROUPS_MAX
5301
 
+
5302
 
+# Included from bits/posix2_lim.h
5303
 
+_BITS_POSIX2_LIM_H = 1
5304
 
+_POSIX2_BC_BASE_MAX = 99
5305
 
+_POSIX2_BC_DIM_MAX = 2048
5306
 
+_POSIX2_BC_SCALE_MAX = 99
5307
 
+_POSIX2_BC_STRING_MAX = 1000
5308
 
+_POSIX2_COLL_WEIGHTS_MAX = 2
5309
 
+_POSIX2_EXPR_NEST_MAX = 32
5310
 
+_POSIX2_LINE_MAX = 2048
5311
 
+_POSIX2_RE_DUP_MAX = 255
5312
 
+_POSIX2_CHARCLASS_NAME_MAX = 14
5313
 
+BC_BASE_MAX = _POSIX2_BC_BASE_MAX
5314
 
+BC_DIM_MAX = _POSIX2_BC_DIM_MAX
5315
 
+BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX
5316
 
+BC_STRING_MAX = _POSIX2_BC_STRING_MAX
5317
 
+COLL_WEIGHTS_MAX = 255
5318
 
+EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX
5319
 
+LINE_MAX = _POSIX2_LINE_MAX
5320
 
+CHARCLASS_NAME_MAX = 2048
5321
 
+RE_DUP_MAX = (0x7fff)
5322
 
+
5323
 
+# Included from bits/xopen_lim.h
5324
 
+_XOPEN_LIM_H = 1
5325
 
+
5326
 
+# Included from bits/stdio_lim.h
5327
 
+L_tmpnam = 20
5328
 
+TMP_MAX = 238328
5329
 
+FILENAME_MAX = 4096
5330
 
+L_ctermid = 9
5331
 
+L_cuserid = 9
5332
 
+FOPEN_MAX = 16
5333
 
+IOV_MAX = 1024
5334
 
+_XOPEN_IOV_MAX = _POSIX_UIO_MAXIOV
5335
 
+NL_ARGMAX = _POSIX_ARG_MAX
5336
 
+NL_LANGMAX = _POSIX2_LINE_MAX
5337
 
+NL_MSGMAX = INT_MAX
5338
 
+NL_NMAX = INT_MAX
5339
 
+NL_SETMAX = INT_MAX
5340
 
+NL_TEXTMAX = INT_MAX
5341
 
+NZERO = 20
5342
 
+WORD_BIT = 16
5343
 
+WORD_BIT = 32
5344
 
+WORD_BIT = 64
5345
 
+WORD_BIT = 16
5346
 
+WORD_BIT = 32
5347
 
+WORD_BIT = 64
5348
 
+WORD_BIT = 32
5349
 
+LONG_BIT = 32
5350
 
+LONG_BIT = 64
5351
 
+LONG_BIT = 32
5352
 
+LONG_BIT = 64
5353
 
+LONG_BIT = 64
5354
 
+LONG_BIT = 32
5355
 
+from TYPES import *
5356
 
+PF_UNSPEC = 0
5357
 
+PF_LOCAL = 1
5358
 
+PF_UNIX = PF_LOCAL
5359
 
+PF_FILE = PF_LOCAL
5360
 
+PF_INET = 2
5361
 
+PF_AX25 = 3
5362
 
+PF_IPX = 4
5363
 
+PF_APPLETALK = 5
5364
 
+PF_NETROM = 6
5365
 
+PF_BRIDGE = 7
5366
 
+PF_ATMPVC = 8
5367
 
+PF_X25 = 9
5368
 
+PF_INET6 = 10
5369
 
+PF_ROSE = 11
5370
 
+PF_DECnet = 12
5371
 
+PF_NETBEUI = 13
5372
 
+PF_SECURITY = 14
5373
 
+PF_KEY = 15
5374
 
+PF_NETLINK = 16
5375
 
+PF_ROUTE = PF_NETLINK
5376
 
+PF_PACKET = 17
5377
 
+PF_ASH = 18
5378
 
+PF_ECONET = 19
5379
 
+PF_ATMSVC = 20
5380
 
+PF_SNA = 22
5381
 
+PF_IRDA = 23
5382
 
+PF_PPPOX = 24
5383
 
+PF_WANPIPE = 25
5384
 
+PF_BLUETOOTH = 31
5385
 
+PF_MAX = 32
5386
 
+AF_UNSPEC = PF_UNSPEC
5387
 
+AF_LOCAL = PF_LOCAL
5388
 
+AF_UNIX = PF_UNIX
5389
 
+AF_FILE = PF_FILE
5390
 
+AF_INET = PF_INET
5391
 
+AF_AX25 = PF_AX25
5392
 
+AF_IPX = PF_IPX
5393
 
+AF_APPLETALK = PF_APPLETALK
5394
 
+AF_NETROM = PF_NETROM
5395
 
+AF_BRIDGE = PF_BRIDGE
5396
 
+AF_ATMPVC = PF_ATMPVC
5397
 
+AF_X25 = PF_X25
5398
 
+AF_INET6 = PF_INET6
5399
 
+AF_ROSE = PF_ROSE
5400
 
+AF_DECnet = PF_DECnet
5401
 
+AF_NETBEUI = PF_NETBEUI
5402
 
+AF_SECURITY = PF_SECURITY
5403
 
+AF_KEY = PF_KEY
5404
 
+AF_NETLINK = PF_NETLINK
5405
 
+AF_ROUTE = PF_ROUTE
5406
 
+AF_PACKET = PF_PACKET
5407
 
+AF_ASH = PF_ASH
5408
 
+AF_ECONET = PF_ECONET
5409
 
+AF_ATMSVC = PF_ATMSVC
5410
 
+AF_SNA = PF_SNA
5411
 
+AF_IRDA = PF_IRDA
5412
 
+AF_PPPOX = PF_PPPOX
5413
 
+AF_WANPIPE = PF_WANPIPE
5414
 
+AF_BLUETOOTH = PF_BLUETOOTH
5415
 
+AF_MAX = PF_MAX
5416
 
+SOL_RAW = 255
5417
 
+SOL_DECNET = 261
5418
 
+SOL_X25 = 262
5419
 
+SOL_PACKET = 263
5420
 
+SOL_ATM = 264
5421
 
+SOL_AAL = 265
5422
 
+SOL_IRDA = 266
5423
 
+SOMAXCONN = 128
5424
 
+
5425
 
+# Included from bits/sockaddr.h
5426
 
+_BITS_SOCKADDR_H = 1
5427
 
+def __SOCKADDR_COMMON(sa_prefix): return \
5428
 
+
5429
 
+_SS_SIZE = 128
5430
 
+def CMSG_FIRSTHDR(mhdr): return \
5431
 
+
5432
 
+
5433
 
+# Included from asm/socket.h
5434
 
+
5435
 
+# Included from asm/sockios.h
5436
 
+FIOSETOWN = 0x8901
5437
 
+SIOCSPGRP = 0x8902
5438
 
+FIOGETOWN = 0x8903
5439
 
+SIOCGPGRP = 0x8904
5440
 
+SIOCATMARK = 0x8905
5441
 
+SIOCGSTAMP = 0x8906
5442
 
+SOL_SOCKET = 1
5443
 
+SO_DEBUG = 1
5444
 
+SO_REUSEADDR = 2
5445
 
+SO_TYPE = 3
5446
 
+SO_ERROR = 4
5447
 
+SO_DONTROUTE = 5
5448
 
+SO_BROADCAST = 6
5449
 
+SO_SNDBUF = 7
5450
 
+SO_RCVBUF = 8
5451
 
+SO_KEEPALIVE = 9
5452
 
+SO_OOBINLINE = 10
5453
 
+SO_NO_CHECK = 11
5454
 
+SO_PRIORITY = 12
5455
 
+SO_LINGER = 13
5456
 
+SO_BSDCOMPAT = 14
5457
 
+SO_PASSCRED = 16
5458
 
+SO_PEERCRED = 17
5459
 
+SO_RCVLOWAT = 18
5460
 
+SO_SNDLOWAT = 19
5461
 
+SO_RCVTIMEO = 20
5462
 
+SO_SNDTIMEO = 21
5463
 
+SO_SECURITY_AUTHENTICATION = 22
5464
 
+SO_SECURITY_ENCRYPTION_TRANSPORT = 23
5465
 
+SO_SECURITY_ENCRYPTION_NETWORK = 24
5466
 
+SO_BINDTODEVICE = 25
5467
 
+SO_ATTACH_FILTER = 26
5468
 
+SO_DETACH_FILTER = 27
5469
 
+SO_PEERNAME = 28
5470
 
+SO_TIMESTAMP = 29
5471
 
+SCM_TIMESTAMP = SO_TIMESTAMP
5472
 
+SO_ACCEPTCONN = 30
5473
 
+SOCK_STREAM = 1
5474
 
+SOCK_DGRAM = 2
5475
 
+SOCK_RAW = 3
5476
 
+SOCK_RDM = 4
5477
 
+SOCK_SEQPACKET = 5
5478
 
+SOCK_PACKET = 10
5479
 
+SOCK_MAX = (SOCK_PACKET+1)
5480
 
+
5481
 
+# Included from bits/in.h
5482
 
+IP_TOS = 1
5483
 
+IP_TTL = 2
5484
 
+IP_HDRINCL = 3
5485
 
+IP_OPTIONS = 4
5486
 
+IP_ROUTER_ALERT = 5
5487
 
+IP_RECVOPTS = 6
5488
 
+IP_RETOPTS = 7
5489
 
+IP_PKTINFO = 8
5490
 
+IP_PKTOPTIONS = 9
5491
 
+IP_PMTUDISC = 10
5492
 
+IP_MTU_DISCOVER = 10
5493
 
+IP_RECVERR = 11
5494
 
+IP_RECVTTL = 12
5495
 
+IP_RECVTOS = 13
5496
 
+IP_MULTICAST_IF = 32
5497
 
+IP_MULTICAST_TTL = 33
5498
 
+IP_MULTICAST_LOOP = 34
5499
 
+IP_ADD_MEMBERSHIP = 35
5500
 
+IP_DROP_MEMBERSHIP = 36
5501
 
+IP_RECVRETOPTS = IP_RETOPTS
5502
 
+IP_PMTUDISC_DONT = 0
5503
 
+IP_PMTUDISC_WANT = 1
5504
 
+IP_PMTUDISC_DO = 2
5505
 
+SOL_IP = 0
5506
 
+IP_DEFAULT_MULTICAST_TTL = 1
5507
 
+IP_DEFAULT_MULTICAST_LOOP = 1
5508
 
+IP_MAX_MEMBERSHIPS = 20
5509
 
+IPV6_ADDRFORM = 1
5510
 
+IPV6_PKTINFO = 2
5511
 
+IPV6_HOPOPTS = 3
5512
 
+IPV6_DSTOPTS = 4
5513
 
+IPV6_RTHDR = 5
5514
 
+IPV6_PKTOPTIONS = 6
5515
 
+IPV6_CHECKSUM = 7
5516
 
+IPV6_HOPLIMIT = 8
5517
 
+IPV6_NEXTHOP = 9
5518
 
+IPV6_AUTHHDR = 10
5519
 
+IPV6_UNICAST_HOPS = 16
5520
 
+IPV6_MULTICAST_IF = 17
5521
 
+IPV6_MULTICAST_HOPS = 18
5522
 
+IPV6_MULTICAST_LOOP = 19
5523
 
+IPV6_JOIN_GROUP = 20
5524
 
+IPV6_LEAVE_GROUP = 21
5525
 
+IPV6_ROUTER_ALERT = 22
5526
 
+IPV6_MTU_DISCOVER = 23
5527
 
+IPV6_MTU = 24
5528
 
+IPV6_RECVERR = 25
5529
 
+IPV6_RXHOPOPTS = IPV6_HOPOPTS
5530
 
+IPV6_RXDSTOPTS = IPV6_DSTOPTS
5531
 
+IPV6_ADD_MEMBERSHIP = IPV6_JOIN_GROUP
5532
 
+IPV6_DROP_MEMBERSHIP = IPV6_LEAVE_GROUP
5533
 
+IPV6_PMTUDISC_DONT = 0
5534
 
+IPV6_PMTUDISC_WANT = 1
5535
 
+IPV6_PMTUDISC_DO = 2
5536
 
+SOL_IPV6 = 41
5537
 
+SOL_ICMPV6 = 58
5538
 
+IPV6_RTHDR_LOOSE = 0
5539
 
+IPV6_RTHDR_STRICT = 1
5540
 
+IPV6_RTHDR_TYPE_0 = 0
5541
 
+
5542
 
+# Included from endian.h
5543
 
+_ENDIAN_H = 1
5544
 
+__LITTLE_ENDIAN = 1234
5545
 
+__BIG_ENDIAN = 4321
5546
 
+__PDP_ENDIAN = 3412
5547
 
+
5548
 
+# Included from bits/endian.h
5549
 
+__BYTE_ORDER = __LITTLE_ENDIAN
5550
 
+__FLOAT_WORD_ORDER = __BYTE_ORDER
5551
 
+LITTLE_ENDIAN = __LITTLE_ENDIAN
5552
 
+BIG_ENDIAN = __BIG_ENDIAN
5553
 
+PDP_ENDIAN = __PDP_ENDIAN
5554
 
+BYTE_ORDER = __BYTE_ORDER
5555
 
+
5556
 
+# Included from bits/byteswap.h
5557
 
+_BITS_BYTESWAP_H = 1
5558
 
+def __bswap_constant_16(x): return \
5559
 
+
5560
 
+def __bswap_16(x): return \
5561
 
+
5562
 
+def __bswap_16(x): return __bswap_constant_16 (x)
5563
 
+
5564
 
+def __bswap_constant_32(x): return \
5565
 
+
5566
 
+def __bswap_32(x): return \
5567
 
+
5568
 
+def __bswap_32(x): return \
5569
 
+
5570
 
+def __bswap_32(x): return __bswap_constant_32 (x)
5571
 
+
5572
 
+def __bswap_constant_64(x): return \
5573
 
+
5574
 
+def __bswap_64(x): return \
5575
 
+
5576
 
+def ntohl(x): return (x)
5577
 
+
5578
 
+def ntohs(x): return (x)
5579
 
+
5580
 
+def htonl(x): return (x)
5581
 
+
5582
 
+def htons(x): return (x)
5583
 
+
5584
 
+def ntohl(x): return __bswap_32 (x)
5585
 
+
5586
 
+def ntohs(x): return __bswap_16 (x)
5587
 
+
5588
 
+def htonl(x): return __bswap_32 (x)
5589
 
+
5590
 
+def htons(x): return __bswap_16 (x)
5591
 
+
5592
 
+def IN6_IS_ADDR_UNSPECIFIED(a): return \
5593
 
+
5594
 
+def IN6_IS_ADDR_LOOPBACK(a): return \
5595
 
+
5596
 
+def IN6_IS_ADDR_LINKLOCAL(a): return \
5597
 
+
5598
 
+def IN6_IS_ADDR_SITELOCAL(a): return \
5599
 
+
5600
 
+def IN6_IS_ADDR_V4MAPPED(a): return \
5601
 
+
5602
 
+def IN6_IS_ADDR_V4COMPAT(a): return \
5603
 
+
5604
 
+def IN6_IS_ADDR_MC_NODELOCAL(a): return \
5605
 
+
5606
 
+def IN6_IS_ADDR_MC_LINKLOCAL(a): return \
5607
 
+
5608
 
+def IN6_IS_ADDR_MC_SITELOCAL(a): return \
5609
 
+
5610
 
+def IN6_IS_ADDR_MC_ORGLOCAL(a): return \
5611
 
+
5612
 
+def IN6_IS_ADDR_MC_GLOBAL(a): return
5613
 
diff -r 8527427914a2 Lib/plat-linux3/TYPES.py
5614
 
--- /dev/null
5615
 
+++ b/Lib/plat-linux3/TYPES.py
5616
 
@@ -0,0 +1,170 @@
5617
 
+# Generated by h2py from /usr/include/sys/types.h
5618
 
+_SYS_TYPES_H = 1
5619
 
+
5620
 
+# Included from features.h
5621
 
+_FEATURES_H = 1
5622
 
+__USE_ANSI = 1
5623
 
+__FAVOR_BSD = 1
5624
 
+_ISOC99_SOURCE = 1
5625
 
+_POSIX_SOURCE = 1
5626
 
+_POSIX_C_SOURCE = 199506L
5627
 
+_XOPEN_SOURCE = 600
5628
 
+_XOPEN_SOURCE_EXTENDED = 1
5629
 
+_LARGEFILE64_SOURCE = 1
5630
 
+_BSD_SOURCE = 1
5631
 
+_SVID_SOURCE = 1
5632
 
+_BSD_SOURCE = 1
5633
 
+_SVID_SOURCE = 1
5634
 
+__USE_ISOC99 = 1
5635
 
+_POSIX_SOURCE = 1
5636
 
+_POSIX_C_SOURCE = 2
5637
 
+_POSIX_C_SOURCE = 199506L
5638
 
+__USE_POSIX = 1
5639
 
+__USE_POSIX2 = 1
5640
 
+__USE_POSIX199309 = 1
5641
 
+__USE_POSIX199506 = 1
5642
 
+__USE_XOPEN = 1
5643
 
+__USE_XOPEN_EXTENDED = 1
5644
 
+__USE_UNIX98 = 1
5645
 
+_LARGEFILE_SOURCE = 1
5646
 
+__USE_XOPEN2K = 1
5647
 
+__USE_ISOC99 = 1
5648
 
+__USE_XOPEN_EXTENDED = 1
5649
 
+__USE_LARGEFILE = 1
5650
 
+__USE_LARGEFILE64 = 1
5651
 
+__USE_FILE_OFFSET64 = 1
5652
 
+__USE_MISC = 1
5653
 
+__USE_BSD = 1
5654
 
+__USE_SVID = 1
5655
 
+__USE_GNU = 1
5656
 
+__USE_REENTRANT = 1
5657
 
+__STDC_IEC_559__ = 1
5658
 
+__STDC_IEC_559_COMPLEX__ = 1
5659
 
+__STDC_ISO_10646__ = 200009L
5660
 
+__GNU_LIBRARY__ = 6
5661
 
+__GLIBC__ = 2
5662
 
+__GLIBC_MINOR__ = 2
5663
 
+
5664
 
+# Included from sys/cdefs.h
5665
 
+_SYS_CDEFS_H = 1
5666
 
+def __PMT(args): return args
5667
 
+
5668
 
+def __P(args): return args
5669
 
+
5670
 
+def __PMT(args): return args
5671
 
+
5672
 
+def __STRING(x): return #x
5673
 
+
5674
 
+__flexarr = []
5675
 
+__flexarr = [0]
5676
 
+__flexarr = []
5677
 
+__flexarr = [1]
5678
 
+def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
5679
 
+
5680
 
+def __attribute__(xyz): return
5681
 
+
5682
 
+def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x)))
5683
 
+
5684
 
+def __attribute_format_arg__(x): return
5685
 
+
5686
 
+__USE_LARGEFILE = 1
5687
 
+__USE_LARGEFILE64 = 1
5688
 
+__USE_EXTERN_INLINES = 1
5689
 
+
5690
 
+# Included from gnu/stubs.h
5691
 
+
5692
 
+# Included from bits/types.h
5693
 
+_BITS_TYPES_H = 1
5694
 
+__FD_SETSIZE = 1024
5695
 
+
5696
 
+# Included from bits/pthreadtypes.h
5697
 
+_BITS_PTHREADTYPES_H = 1
5698
 
+
5699
 
+# Included from bits/sched.h
5700
 
+SCHED_OTHER = 0
5701
 
+SCHED_FIFO = 1
5702
 
+SCHED_RR = 2
5703
 
+CSIGNAL = 0x000000ff
5704
 
+CLONE_VM = 0x00000100
5705
 
+CLONE_FS = 0x00000200
5706
 
+CLONE_FILES = 0x00000400
5707
 
+CLONE_SIGHAND = 0x00000800
5708
 
+CLONE_PID = 0x00001000
5709
 
+CLONE_PTRACE = 0x00002000
5710
 
+CLONE_VFORK = 0x00004000
5711
 
+__defined_schedparam = 1
5712
 
+
5713
 
+# Included from time.h
5714
 
+_TIME_H = 1
5715
 
+
5716
 
+# Included from bits/time.h
5717
 
+_BITS_TIME_H = 1
5718
 
+CLOCKS_PER_SEC = 1000000l
5719
 
+CLOCK_REALTIME = 0
5720
 
+CLOCK_PROCESS_CPUTIME_ID = 2
5721
 
+CLOCK_THREAD_CPUTIME_ID = 3
5722
 
+TIMER_ABSTIME = 1
5723
 
+_STRUCT_TIMEVAL = 1
5724
 
+CLK_TCK = CLOCKS_PER_SEC
5725
 
+__clock_t_defined = 1
5726
 
+__time_t_defined = 1
5727
 
+__clockid_t_defined = 1
5728
 
+__timer_t_defined = 1
5729
 
+__timespec_defined = 1
5730
 
+def __isleap(year): return \
5731
 
+
5732
 
+__BIT_TYPES_DEFINED__ = 1
5733
 
+
5734
 
+# Included from endian.h
5735
 
+_ENDIAN_H = 1
5736
 
+__LITTLE_ENDIAN = 1234
5737
 
+__BIG_ENDIAN = 4321
5738
 
+__PDP_ENDIAN = 3412
5739
 
+
5740
 
+# Included from bits/endian.h
5741
 
+__BYTE_ORDER = __LITTLE_ENDIAN
5742
 
+__FLOAT_WORD_ORDER = __BYTE_ORDER
5743
 
+LITTLE_ENDIAN = __LITTLE_ENDIAN
5744
 
+BIG_ENDIAN = __BIG_ENDIAN
5745
 
+PDP_ENDIAN = __PDP_ENDIAN
5746
 
+BYTE_ORDER = __BYTE_ORDER
5747
 
+
5748
 
+# Included from sys/select.h
5749
 
+_SYS_SELECT_H = 1
5750
 
+
5751
 
+# Included from bits/select.h
5752
 
+def __FD_ZERO(fdsp): return \
5753
 
+
5754
 
+def __FD_ZERO(set): return \
5755
 
+
5756
 
+
5757
 
+# Included from bits/sigset.h
5758
 
+_SIGSET_H_types = 1
5759
 
+_SIGSET_H_fns = 1
5760
 
+def __sigmask(sig): return \
5761
 
+
5762
 
+def __sigemptyset(set): return \
5763
 
+
5764
 
+def __sigfillset(set): return \
5765
 
+
5766
 
+def __sigisemptyset(set): return \
5767
 
+
5768
 
+def __FDELT(d): return ((d) / __NFDBITS)
5769
 
+
5770
 
+FD_SETSIZE = __FD_SETSIZE
5771
 
+def FD_ZERO(fdsetp): return __FD_ZERO (fdsetp)
5772
 
+
5773
 
+
5774
 
+# Included from sys/sysmacros.h
5775
 
+_SYS_SYSMACROS_H = 1
5776
 
+def major(dev): return ((int)(((dev) >> 8) & 0xff))
5777
 
+
5778
 
+def minor(dev): return ((int)((dev) & 0xff))
5779
 
+
5780
 
+def major(dev): return (((dev).__val[1] >> 8) & 0xff)
5781
 
+
5782
 
+def minor(dev): return ((dev).__val[1] & 0xff)
5783
 
+
5784
 
+def major(dev): return (((dev).__val[0] >> 8) & 0xff)
5785
 
+
5786
 
+def minor(dev): return ((dev).__val[0] & 0xff)
5787
 
diff -r 8527427914a2 Lib/plat-linux3/regen
5788
 
--- /dev/null
5789
 
+++ b/Lib/plat-linux3/regen
5790
 
@@ -0,0 +1,8 @@
5791
 
+#! /bin/sh
5792
 
+case `uname` in
5793
 
+Linux*)        ;;
5794
 
+*)     echo Probably not on a Linux system 1>&2
5795
 
+       exit 1;;
5796
 
+esac
5797
 
+set -v
5798
 
+h2py -i '(u_long)' /usr/include/sys/types.h /usr/include/netinet/in.h /usr/include/dlfcn.h
 
14017
@@ -286,20 +286,20 @@
 
14018
             f(self, obj) # Call unbound method with explicit self
 
14019
             return
 
14020
 
 
14021
-        # Check for a class with a custom metaclass; treat as regular class
 
14022
-        try:
 
14023
-            issc = issubclass(t, TypeType)
 
14024
-        except TypeError: # t is not a class (old Boost; see SF #502085)
 
14025
-            issc = 0
 
14026
-        if issc:
 
14027
-            self.save_global(obj)
 
14028
-            return
 
14029
-
 
14030
         # Check copy_reg.dispatch_table
 
14031
         reduce = dispatch_table.get(t)
 
14032
         if reduce:
 
14033
             rv = reduce(obj)
 
14034
         else:
 
14035
+            # Check for a class with a custom metaclass; treat as regular class
 
14036
+            try:
 
14037
+                issc = issubclass(t, TypeType)
 
14038
+            except TypeError: # t is not a class (old Boost; see SF #502085)
 
14039
+                issc = 0
 
14040
+            if issc:
 
14041
+                self.save_global(obj)
 
14042
+                return
 
14043
+
 
14044
             # Check for a __reduce_ex__ method, fall back to __reduce__
 
14045
             reduce = getattr(obj, "__reduce_ex__", None)
 
14046
             if reduce:
 
14047
diff -r 8527427914a2 Lib/pipes.py
 
14048
--- a/Lib/pipes.py
 
14049
+++ b/Lib/pipes.py
 
14050
@@ -54,8 +54,6 @@
 
14051
 
 
14052
 To create a new template object initialized to a given one:
 
14053
    t2 = t.clone()
 
14054
-
 
14055
-For an example, see the function test() at the end of the file.
 
14056
 """                                     # '
 
14057
 
 
14058
 
 
14059
diff -r 8527427914a2 Lib/pkgutil.py
 
14060
--- a/Lib/pkgutil.py
 
14061
+++ b/Lib/pkgutil.py
 
14062
@@ -194,8 +194,11 @@
 
14063
 
 
14064
         yielded = {}
 
14065
         import inspect
 
14066
-
 
14067
-        filenames = os.listdir(self.path)
 
14068
+        try:
 
14069
+            filenames = os.listdir(self.path)
 
14070
+        except OSError:
 
14071
+            # ignore unreadable directories like import does
 
14072
+            filenames = []
 
14073
         filenames.sort()  # handle packages before same-named modules
 
14074
 
 
14075
         for fn in filenames:
 
14076
@@ -208,7 +211,12 @@
 
14077
 
 
14078
             if not modname and os.path.isdir(path) and '.' not in fn:
 
14079
                 modname = fn
 
14080
-                for fn in os.listdir(path):
 
14081
+                try:
 
14082
+                    dircontents = os.listdir(path)
 
14083
+                except OSError:
 
14084
+                    # ignore unreadable directories like import does
 
14085
+                    dircontents = []
 
14086
+                for fn in dircontents:
 
14087
                     subname = inspect.getmodulename(fn)
 
14088
                     if subname=='__init__':
 
14089
                         ispkg = True
 
14090
diff -r 8527427914a2 Lib/plat-mac/findertools.py
 
14091
--- a/Lib/plat-mac/findertools.py
 
14092
+++ b/Lib/plat-mac/findertools.py
 
14093
@@ -128,7 +128,7 @@
 
14094
 def comment(object, comment=None):
 
14095
     """comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window."""
 
14096
     object = Carbon.File.FSRef(object)
 
14097
-    object_alias = object.FSNewAliasMonimal()
 
14098
+    object_alias = object.FSNewAliasMinimal()
 
14099
     if comment is None:
 
14100
         return _getcomment(object_alias)
 
14101
     else:
5799
14102
diff -r 8527427914a2 Lib/platform.py
5800
14103
--- a/Lib/platform.py
5801
14104
+++ b/Lib/platform.py
5819
14122
 __credits__ = """Guido van Rossum, for an excellent programming language.
5820
14123
 Tommy Burnette, the original creator of manpy.
5821
14124
 Paul Prescod, for all his work on onlinehelp.
 
14125
@@ -52,7 +52,7 @@
 
14126
 #     the current directory is changed with os.chdir(), an incorrect
 
14127
 #     path will be displayed.
 
14128
 
 
14129
-import sys, imp, os, re, types, inspect, __builtin__, pkgutil
 
14130
+import sys, imp, os, re, types, inspect, __builtin__, pkgutil, warnings
 
14131
 from repr import Repr
 
14132
 from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
 
14133
 from traceback import extract_tb
5822
14134
@@ -212,8 +212,8 @@
5823
14135
 def synopsis(filename, cache={}):
5824
14136
     """Get the one-line summary out of a module file."""
5851
14163
 
5852
14164
 # --------------------------------------- interactive interpreter interface
5853
14165
 
 
14166
@@ -1967,10 +1968,11 @@
 
14167
         if modname[-9:] == '.__init__':
 
14168
             modname = modname[:-9] + ' (package)'
 
14169
         print modname, desc and '- ' + desc
 
14170
-    try: import warnings
 
14171
-    except ImportError: pass
 
14172
-    else: warnings.filterwarnings('ignore') # ignore problems during import
 
14173
-    ModuleScanner().run(callback, key)
 
14174
+    def onerror(modname):
 
14175
+        pass
 
14176
+    with warnings.catch_warnings():
 
14177
+        warnings.filterwarnings('ignore') # ignore problems during import
 
14178
+        ModuleScanner().run(callback, key, onerror=onerror)
 
14179
 
 
14180
 # --------------------------------------------------- web browser interface
 
14181
 
5854
14182
diff -r 8527427914a2 Lib/random.py
5855
14183
--- a/Lib/random.py
5856
14184
+++ b/Lib/random.py
5869
14197
 
5870
14198
 ## -------------------- von Mises distribution --------------------
5871
14199
 
 
14200
diff -r 8527427914a2 Lib/rfc822.py
 
14201
--- a/Lib/rfc822.py
 
14202
+++ b/Lib/rfc822.py
 
14203
@@ -34,7 +34,7 @@
 
14204
 libraries in which tell() discards buffered data before discovering that the
 
14205
 lseek() system call doesn't work.  For maximum portability, you should set the
 
14206
 seekable argument to zero to prevent that initial \code{tell} when passing in
 
14207
-an unseekable object such as a a file object created from a socket object.  If
 
14208
+an unseekable object such as a file object created from a socket object.  If
 
14209
 it is 1 on entry -- which it is by default -- the tell() method of the open
 
14210
 file object is called once; if this raises an exception, seekable is reset to
 
14211
 0.  For other nonzero values of seekable, this test is not made.
 
14212
diff -r 8527427914a2 Lib/sched.py
 
14213
--- a/Lib/sched.py
 
14214
+++ b/Lib/sched.py
 
14215
@@ -88,7 +88,7 @@
 
14216
         restarted.
 
14217
 
 
14218
         It is legal for both the delay function and the action
 
14219
-        function to to modify the queue or to raise an exception;
 
14220
+        function to modify the queue or to raise an exception;
 
14221
         exceptions are not caught but the scheduler's state remains
 
14222
         well-defined so run() may be called again.
 
14223
 
 
14224
diff -r 8527427914a2 Lib/shutil.py
 
14225
--- a/Lib/shutil.py
 
14226
+++ b/Lib/shutil.py
 
14227
@@ -25,7 +25,8 @@
 
14228
 __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
 
14229
            "copytree", "move", "rmtree", "Error", "SpecialFileError",
 
14230
            "ExecError", "make_archive", "get_archive_formats",
 
14231
-           "register_archive_format", "unregister_archive_format"]
 
14232
+           "register_archive_format", "unregister_archive_format",
 
14233
+           "ignore_patterns"]
 
14234
 
 
14235
 class Error(EnvironmentError):
 
14236
     pass
 
14237
@@ -359,7 +360,8 @@
 
14238
     archive_dir = os.path.dirname(archive_name)
 
14239
 
 
14240
     if not os.path.exists(archive_dir):
 
14241
-        logger.info("creating %s" % archive_dir)
 
14242
+        if logger is not None:
 
14243
+            logger.info("creating %s", archive_dir)
 
14244
         if not dry_run:
 
14245
             os.makedirs(archive_dir)
 
14246
 
 
14247
diff -r 8527427914a2 Lib/smtpd.py
 
14248
--- a/Lib/smtpd.py
 
14249
+++ b/Lib/smtpd.py
 
14250
@@ -524,6 +524,16 @@
 
14251
 if __name__ == '__main__':
 
14252
     options = parseargs()
 
14253
     # Become nobody
 
14254
+    classname = options.classname
 
14255
+    if "." in classname:
 
14256
+        lastdot = classname.rfind(".")
 
14257
+        mod = __import__(classname[:lastdot], globals(), locals(), [""])
 
14258
+        classname = classname[lastdot+1:]
 
14259
+    else:
 
14260
+        import __main__ as mod
 
14261
+    class_ = getattr(mod, classname)
 
14262
+    proxy = class_((options.localhost, options.localport),
 
14263
+                   (options.remotehost, options.remoteport))
 
14264
     if options.setuid:
 
14265
         try:
 
14266
             import pwd
 
14267
@@ -539,16 +549,6 @@
 
14268
             print >> sys.stderr, \
 
14269
                   'Cannot setuid "nobody"; try running with -n option.'
 
14270
             sys.exit(1)
 
14271
-    classname = options.classname
 
14272
-    if "." in classname:
 
14273
-        lastdot = classname.rfind(".")
 
14274
-        mod = __import__(classname[:lastdot], globals(), locals(), [""])
 
14275
-        classname = classname[lastdot+1:]
 
14276
-    else:
 
14277
-        import __main__ as mod
 
14278
-    class_ = getattr(mod, classname)
 
14279
-    proxy = class_((options.localhost, options.localport),
 
14280
-                   (options.remotehost, options.remoteport))
 
14281
     try:
 
14282
         asyncore.loop()
 
14283
     except KeyboardInterrupt:
5872
14284
diff -r 8527427914a2 Lib/smtplib.py
5873
14285
--- a/Lib/smtplib.py
5874
14286
+++ b/Lib/smtplib.py
5886
14298
 def quotedata(data):
5887
14299
     """Quote data for email.
5888
14300
 
5889
 
@@ -497,14 +504,14 @@
 
14301
@@ -345,8 +352,10 @@
 
14302
         while 1:
 
14303
             try:
 
14304
                 line = self.file.readline()
 
14305
-            except socket.error:
 
14306
-                line = ''
 
14307
+            except socket.error as e:
 
14308
+                self.close()
 
14309
+                raise SMTPServerDisconnected("Connection unexpectedly closed: "
 
14310
+                                             + str(e))
 
14311
             if line == '':
 
14312
                 self.close()
 
14313
                 raise SMTPServerDisconnected("Connection unexpectedly closed")
 
14314
@@ -497,14 +506,14 @@
5890
14315
 
5891
14316
     def verify(self, address):
5892
14317
         """SMTP 'verify' command -- checks for address validity."""
5918
14343
diff -r 8527427914a2 Lib/subprocess.py
5919
14344
--- a/Lib/subprocess.py
5920
14345
+++ b/Lib/subprocess.py
 
14346
@@ -460,7 +460,7 @@
 
14347
 def _cleanup():
 
14348
     for inst in _active[:]:
 
14349
         res = inst._internal_poll(_deadstate=sys.maxint)
 
14350
-        if res is not None and res >= 0:
 
14351
+        if res is not None:
 
14352
             try:
 
14353
                 _active.remove(inst)
 
14354
             except ValueError:
5921
14355
@@ -476,7 +476,7 @@
5922
14356
     while True:
5923
14357
         try:
5952
14386
                 self.stderr.close()
5953
14387
             self.wait()
5954
14388
             return (stdout, stderr)
5955
 
@@ -1145,6 +1148,14 @@
 
14389
@@ -1032,7 +1035,7 @@
 
14390
             if stdin is None:
 
14391
                 pass
 
14392
             elif stdin == PIPE:
 
14393
-                p2cread, p2cwrite = os.pipe()
 
14394
+                p2cread, p2cwrite = self.pipe_cloexec()
 
14395
             elif isinstance(stdin, int):
 
14396
                 p2cread = stdin
 
14397
             else:
 
14398
@@ -1042,7 +1045,7 @@
 
14399
             if stdout is None:
 
14400
                 pass
 
14401
             elif stdout == PIPE:
 
14402
-                c2pread, c2pwrite = os.pipe()
 
14403
+                c2pread, c2pwrite = self.pipe_cloexec()
 
14404
             elif isinstance(stdout, int):
 
14405
                 c2pwrite = stdout
 
14406
             else:
 
14407
@@ -1052,7 +1055,7 @@
 
14408
             if stderr is None:
 
14409
                 pass
 
14410
             elif stderr == PIPE:
 
14411
-                errread, errwrite = os.pipe()
 
14412
+                errread, errwrite = self.pipe_cloexec()
 
14413
             elif stderr == STDOUT:
 
14414
                 errwrite = c2pwrite
 
14415
             elif isinstance(stderr, int):
 
14416
@@ -1079,6 +1082,18 @@
 
14417
                 fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
 
14418
 
 
14419
 
 
14420
+        def pipe_cloexec(self):
 
14421
+            """Create a pipe with FDs set CLOEXEC."""
 
14422
+            # Pipes' FDs are set CLOEXEC by default because we don't want them
 
14423
+            # to be inherited by other subprocesses: the CLOEXEC flag is removed
 
14424
+            # from the child's FDs by _dup2(), between fork() and exec().
 
14425
+            # This is not atomic: we would need the pipe2() syscall for that.
 
14426
+            r, w = os.pipe()
 
14427
+            self._set_cloexec_flag(r)
 
14428
+            self._set_cloexec_flag(w)
 
14429
+            return r, w
 
14430
+
 
14431
+
 
14432
         def _close_fds(self, but):
 
14433
             if hasattr(os, 'closerange'):
 
14434
                 os.closerange(3, but)
 
14435
@@ -1117,11 +1132,9 @@
 
14436
             # For transferring possible exec failure from child to parent
 
14437
             # The first char specifies the exception type: 0 means
 
14438
             # OSError, 1 means some other error.
 
14439
-            errpipe_read, errpipe_write = os.pipe()
 
14440
+            errpipe_read, errpipe_write = self.pipe_cloexec()
 
14441
             try:
 
14442
                 try:
 
14443
-                    self._set_cloexec_flag(errpipe_write)
 
14444
-
 
14445
                     gc_was_enabled = gc.isenabled()
 
14446
                     # Disable gc to avoid bug where gc -> file_dealloc ->
 
14447
                     # write to stderr -> hang.  http://bugs.python.org/issue1336
 
14448
@@ -1145,6 +1158,14 @@
5956
14449
                                 os.close(errread)
5957
14450
                             os.close(errpipe_read)
5958
14451
 
5979
14472
 # $Source$
5980
14473
 
5981
14474
 version     = "0.9.0"
 
14475
@@ -2264,17 +2264,11 @@
 
14476
             try:
 
14477
                 g = grp.getgrnam(tarinfo.gname)[2]
 
14478
             except KeyError:
 
14479
-                try:
 
14480
-                    g = grp.getgrgid(tarinfo.gid)[2]
 
14481
-                except KeyError:
 
14482
-                    g = os.getgid()
 
14483
+                g = tarinfo.gid
 
14484
             try:
 
14485
                 u = pwd.getpwnam(tarinfo.uname)[2]
 
14486
             except KeyError:
 
14487
-                try:
 
14488
-                    u = pwd.getpwuid(tarinfo.uid)[2]
 
14489
-                except KeyError:
 
14490
-                    u = os.getuid()
 
14491
+                u = tarinfo.uid
 
14492
             try:
 
14493
                 if tarinfo.issym() and hasattr(os, "lchown"):
 
14494
                     os.lchown(targetpath, u, g)
 
14495
diff -r 8527427914a2 Lib/tempfile.py
 
14496
--- a/Lib/tempfile.py
 
14497
+++ b/Lib/tempfile.py
 
14498
@@ -118,9 +118,16 @@
 
14499
 
 
14500
     def __init__(self):
 
14501
         self.mutex = _allocate_lock()
 
14502
-        self.rng = _Random()
 
14503
         self.normcase = _os.path.normcase
 
14504
 
 
14505
+    @property
 
14506
+    def rng(self):
 
14507
+        cur_pid = _os.getpid()
 
14508
+        if cur_pid != getattr(self, '_rng_pid', None):
 
14509
+            self._rng = _Random()
 
14510
+            self._rng_pid = cur_pid
 
14511
+        return self._rng
 
14512
+
 
14513
     def __iter__(self):
 
14514
         return self
 
14515
 
5982
14516
diff -r 8527427914a2 Lib/test/cjkencodings/iso2022_jp-utf8.txt
5983
14517
--- /dev/null
5984
14518
+++ b/Lib/test/cjkencodings/iso2022_jp-utf8.txt
6052
14586
 -- Tests for the is_* boolean operations
6053
14587
 precision: 9
6054
14588
 maxExponent: 999
 
14589
diff -r 8527427914a2 Lib/test/nokia.pem
 
14590
--- /dev/null
 
14591
+++ b/Lib/test/nokia.pem
 
14592
@@ -0,0 +1,31 @@
 
14593
+# Certificate for projects.developer.nokia.com:443 (see issue 13034)
 
14594
+-----BEGIN CERTIFICATE-----
 
14595
+MIIFLDCCBBSgAwIBAgIQLubqdkCgdc7lAF9NfHlUmjANBgkqhkiG9w0BAQUFADCB
 
14596
+vDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
 
14597
+ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2Ug
 
14598
+YXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYSAoYykxMDE2MDQGA1UEAxMt
 
14599
+VmVyaVNpZ24gQ2xhc3MgMyBJbnRlcm5hdGlvbmFsIFNlcnZlciBDQSAtIEczMB4X
 
14600
+DTExMDkyMTAwMDAwMFoXDTEyMDkyMDIzNTk1OVowcTELMAkGA1UEBhMCRkkxDjAM
 
14601
+BgNVBAgTBUVzcG9vMQ4wDAYDVQQHFAVFc3BvbzEOMAwGA1UEChQFTm9raWExCzAJ
 
14602
+BgNVBAsUAkJJMSUwIwYDVQQDFBxwcm9qZWN0cy5kZXZlbG9wZXIubm9raWEuY29t
 
14603
+MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCr92w1bpHYSYxUEx8N/8Iddda2
 
14604
+lYi+aXNtQfV/l2Fw9Ykv3Ipw4nLeGTj18FFlAZgMdPRlgrzF/NNXGw/9l3/qKdow
 
14605
+CypkQf8lLaxb9Ze1E/KKmkRJa48QTOqvo6GqKuTI6HCeGlG1RxDb8YSKcQWLiytn
 
14606
+yj3Wp4MgRQO266xmMQIDAQABo4IB9jCCAfIwQQYDVR0RBDowOIIccHJvamVjdHMu
 
14607
+ZGV2ZWxvcGVyLm5va2lhLmNvbYIYcHJvamVjdHMuZm9ydW0ubm9raWEuY29tMAkG
 
14608
+A1UdEwQCMAAwCwYDVR0PBAQDAgWgMEEGA1UdHwQ6MDgwNqA0oDKGMGh0dHA6Ly9T
 
14609
+VlJJbnRsLUczLWNybC52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNybDBEBgNVHSAE
 
14610
+PTA7MDkGC2CGSAGG+EUBBxcDMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3LnZl
 
14611
+cmlzaWduLmNvbS9ycGEwKAYDVR0lBCEwHwYJYIZIAYb4QgQBBggrBgEFBQcDAQYI
 
14612
+KwYBBQUHAwIwcgYIKwYBBQUHAQEEZjBkMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz
 
14613
+cC52ZXJpc2lnbi5jb20wPAYIKwYBBQUHMAKGMGh0dHA6Ly9TVlJJbnRsLUczLWFp
 
14614
+YS52ZXJpc2lnbi5jb20vU1ZSSW50bEczLmNlcjBuBggrBgEFBQcBDARiMGChXqBc
 
14615
+MFowWDBWFglpbWFnZS9naWYwITAfMAcGBSsOAwIaBBRLa7kolgYMu9BSOJsprEsH
 
14616
+iyEFGDAmFiRodHRwOi8vbG9nby52ZXJpc2lnbi5jb20vdnNsb2dvMS5naWYwDQYJ
 
14617
+KoZIhvcNAQEFBQADggEBACQuPyIJqXwUyFRWw9x5yDXgMW4zYFopQYOw/ItRY522
 
14618
+O5BsySTh56BWS6mQB07XVfxmYUGAvRQDA5QHpmY8jIlNwSmN3s8RKo+fAtiNRlcL
 
14619
+x/mWSfuMs3D/S6ev3D6+dpEMZtjrhOdctsarMKp8n/hPbwhAbg5hVjpkW5n8vz2y
 
14620
+0KxvvkA1AxpLwpVv7OlK17ttzIHw8bp9HTlHBU5s8bKz4a565V/a5HI0CSEv/+0y
 
14621
+ko4/ghTnZc1CkmUngKKeFMSah/mT/xAh8XnE2l1AazFa8UKuYki1e+ArHaGZc4ix
 
14622
+UYOtiRphwfuYQhRZ7qX9q2MMkCMI65XNK/SaFrAbbG0=
 
14623
+-----END CERTIFICATE-----
 
14624
diff -r 8527427914a2 Lib/test/pickletester.py
 
14625
--- a/Lib/test/pickletester.py
 
14626
+++ b/Lib/test/pickletester.py
 
14627
@@ -124,6 +124,21 @@
 
14628
 class use_metaclass(object):
 
14629
     __metaclass__ = metaclass
 
14630
 
 
14631
+class pickling_metaclass(type):
 
14632
+    def __eq__(self, other):
 
14633
+        return (type(self) == type(other) and
 
14634
+                self.reduce_args == other.reduce_args)
 
14635
+
 
14636
+    def __reduce__(self):
 
14637
+        return (create_dynamic_class, self.reduce_args)
 
14638
+
 
14639
+    __hash__ = None
 
14640
+
 
14641
+def create_dynamic_class(name, bases):
 
14642
+    result = pickling_metaclass(name, bases, dict())
 
14643
+    result.reduce_args = (name, bases)
 
14644
+    return result
 
14645
+
 
14646
 # DATA0 .. DATA2 are the pickles we expect under the various protocols, for
 
14647
 # the object returned by create_data().
 
14648
 
 
14649
@@ -609,6 +624,14 @@
 
14650
             b = self.loads(s)
 
14651
             self.assertEqual(a.__class__, b.__class__)
 
14652
 
 
14653
+    def test_dynamic_class(self):
 
14654
+        a = create_dynamic_class("my_dynamic_class", (object,))
 
14655
+        copy_reg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
 
14656
+        for proto in protocols:
 
14657
+            s = self.dumps(a, proto)
 
14658
+            b = self.loads(s)
 
14659
+            self.assertEqual(a, b)
 
14660
+
 
14661
     def test_structseq(self):
 
14662
         import time
 
14663
         import os
 
14664
diff -r 8527427914a2 Lib/test/regrtest.py
 
14665
--- a/Lib/test/regrtest.py
 
14666
+++ b/Lib/test/regrtest.py
 
14667
@@ -1076,6 +1076,13 @@
 
14668
     filecmp._cache.clear()
 
14669
     struct._clearcache()
 
14670
     doctest.master = None
 
14671
+    try:
 
14672
+        import ctypes
 
14673
+    except ImportError:
 
14674
+        # Don't worry about resetting the cache if ctypes is not supported
 
14675
+        pass
 
14676
+    else:
 
14677
+        ctypes._reset_cache()
 
14678
 
 
14679
     # Collect cyclic trash.
 
14680
     gc.collect()
 
14681
diff -r 8527427914a2 Lib/test/test_StringIO.py
 
14682
--- a/Lib/test/test_StringIO.py
 
14683
+++ b/Lib/test/test_StringIO.py
 
14684
@@ -4,6 +4,7 @@
 
14685
 import StringIO
 
14686
 import cStringIO
 
14687
 import types
 
14688
+import array
 
14689
 from test import test_support
 
14690
 
 
14691
 
 
14692
@@ -127,6 +128,34 @@
 
14693
 class TestcStringIO(TestGenericStringIO):
 
14694
     MODULE = cStringIO
 
14695
 
 
14696
+    def test_array_support(self):
 
14697
+        # Issue #1730114: cStringIO should accept array objects
 
14698
+        a = array.array('B', [0,1,2])
 
14699
+        f = self.MODULE.StringIO(a)
 
14700
+        self.assertEqual(f.getvalue(), '\x00\x01\x02')
 
14701
+
 
14702
+    def test_unicode(self):
 
14703
+
 
14704
+        if not test_support.have_unicode: return
 
14705
+
 
14706
+        # The cStringIO module converts Unicode strings to character
 
14707
+        # strings when writing them to cStringIO objects.
 
14708
+        # Check that this works.
 
14709
+
 
14710
+        f = self.MODULE.StringIO()
 
14711
+        f.write(u'abcde')
 
14712
+        s = f.getvalue()
 
14713
+        self.assertEqual(s, 'abcde')
 
14714
+        self.assertEqual(type(s), str)
 
14715
+
 
14716
+        f = self.MODULE.StringIO(u'abcde')
 
14717
+        s = f.getvalue()
 
14718
+        self.assertEqual(s, 'abcde')
 
14719
+        self.assertEqual(type(s), str)
 
14720
+
 
14721
+        self.assertRaises(UnicodeEncodeError, self.MODULE.StringIO, u'\xf4')
 
14722
+
 
14723
+
 
14724
 import sys
 
14725
 if sys.platform.startswith('java'):
 
14726
     # Jython doesn't have a buffer object, so we just do a useless
 
14727
diff -r 8527427914a2 Lib/test/test_argparse.py
 
14728
--- a/Lib/test/test_argparse.py
 
14729
+++ b/Lib/test/test_argparse.py
 
14730
@@ -1509,6 +1509,8 @@
 
14731
         return self.name == other.name
 
14732
 
 
14733
 
 
14734
+@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
 
14735
+                 "non-root user required")
 
14736
 class TestFileTypeW(TempDirMixin, ParserTestCase):
 
14737
     """Test the FileType option/argument type for writing files"""
 
14738
 
6055
14739
diff -r 8527427914a2 Lib/test/test_array.py
6056
14740
--- a/Lib/test/test_array.py
6057
14741
+++ b/Lib/test/test_array.py
6382
15066
 ('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)),
6383
15067
 ]
6384
15068
 main()
6385
 
diff -r 8527427914a2 Lib/test/test_builtin.py
6386
 
--- a/Lib/test/test_builtin.py
6387
 
+++ b/Lib/test/test_builtin.py
6388
 
@@ -1683,6 +1683,7 @@
6389
 
 
6390
 
 def _run_unittest(*args):
6391
 
     with check_py3k_warnings(
6392
 
+            (".+ not supported in 3.1", DeprecationWarning),
6393
 
             (".+ not supported in 3.x", DeprecationWarning),
6394
 
             (".+ is renamed to imp.reload", DeprecationWarning),
6395
 
             ("classic int division", DeprecationWarning)):
 
15069
diff -r 8527427914a2 Lib/test/test_bool.py
 
15070
--- a/Lib/test/test_bool.py
 
15071
+++ b/Lib/test/test_bool.py
 
15072
@@ -180,9 +180,8 @@
 
15073
         self.assertIs(hasattr([], "wobble"), False)
 
15074
 
 
15075
     def test_callable(self):
 
15076
-        with test_support.check_py3k_warnings():
 
15077
-            self.assertIs(callable(len), True)
 
15078
-            self.assertIs(callable(1), False)
 
15079
+        self.assertIs(callable(len), True)
 
15080
+        self.assertIs(callable(1), False)
 
15081
 
 
15082
     def test_isinstance(self):
 
15083
         self.assertIs(isinstance(True, bool), True)
6396
15084
diff -r 8527427914a2 Lib/test/test_cfgparser.py
6397
15085
--- a/Lib/test/test_cfgparser.py
6398
15086
+++ b/Lib/test/test_cfgparser.py
6399
 
@@ -529,6 +529,27 @@
 
15087
@@ -529,6 +529,28 @@
6400
15088
 class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):
6401
15089
     allow_no_value = True
6402
15090
 
6419
15107
+                         [dcomb.get(k, 10) for k in klist])      # get()
6420
15108
+        self.assertEqual([k in cm for k in klist],
6421
15109
+                         [k in dcomb for k in klist])            # __contains__()
6422
 
+        self.assertEqual([cm.has_key(k) for k in klist],
6423
 
+                         [dcomb.has_key(k) for k in klist])      # has_key()
 
15110
+        with test_support.check_py3k_warnings():
 
15111
+            self.assertEqual([cm.has_key(k) for k in klist],
 
15112
+                             [dcomb.has_key(k) for k in klist])  # has_key()
6424
15113
 
6425
15114
 class Issue7005TestCase(unittest.TestCase):
6426
15115
     """Test output when None is set() as a value and allow_no_value == False.
6427
 
@@ -591,6 +612,7 @@
 
15116
@@ -591,6 +613,7 @@
6428
15117
         SafeConfigParserTestCaseNoValue,
6429
15118
         SortedTestCase,
6430
15119
         Issue7005TestCase,
6432
15121
         )
6433
15122
 
6434
15123
 
 
15124
diff -r 8527427914a2 Lib/test/test_cgi.py
 
15125
--- a/Lib/test/test_cgi.py
 
15126
+++ b/Lib/test/test_cgi.py
 
15127
@@ -377,6 +377,9 @@
 
15128
         self.assertEqual(
 
15129
             cgi.parse_header('attachment; filename="strange;name";size=123;'),
 
15130
             ("attachment", {"filename": "strange;name", "size": "123"}))
 
15131
+        self.assertEqual(
 
15132
+            cgi.parse_header('form-data; name="files"; filename="fo\\"o;bar"'),
 
15133
+            ("form-data", {"name": "files", "filename": 'fo"o;bar'}))
 
15134
 
 
15135
 
 
15136
 def test_main():
 
15137
diff -r 8527427914a2 Lib/test/test_class.py
 
15138
--- a/Lib/test/test_class.py
 
15139
+++ b/Lib/test/test_class.py
 
15140
@@ -350,6 +350,19 @@
 
15141
         AllTests.__delslice__ = delslice
 
15142
 
 
15143
 
 
15144
+    @test_support.cpython_only
 
15145
+    def testDelItem(self):
 
15146
+        class A:
 
15147
+            ok = False
 
15148
+            def __delitem__(self, key):
 
15149
+                self.ok = True
 
15150
+        a = A()
 
15151
+        # Subtle: we need to call PySequence_SetItem, not PyMapping_SetItem.
 
15152
+        from _testcapi import sequence_delitem
 
15153
+        sequence_delitem(a, 2)
 
15154
+        self.assertTrue(a.ok)
 
15155
+
 
15156
+
 
15157
     def testUnaryOps(self):
 
15158
         testme = AllTests()
 
15159
 
6435
15160
diff -r 8527427914a2 Lib/test/test_codecencodings_iso2022.py
6436
15161
--- /dev/null
6437
15162
+++ b/Lib/test/test_codecencodings_iso2022.py
6559
15284
     def test_iter_keys(self):
6560
15285
         # Testing dict-proxy iterkeys...
6561
15286
         keys = [ key for key in self.C.__dict__.iterkeys() ]
 
15287
diff -r 8527427914a2 Lib/test/test_dis.py
 
15288
--- a/Lib/test/test_dis.py
 
15289
+++ b/Lib/test/test_dis.py
 
15290
@@ -54,7 +54,7 @@
 
15291
 
 
15292
 dis_bug1333982 = """\
 
15293
  %-4d         0 LOAD_CONST               1 (0)
 
15294
-              3 POP_JUMP_IF_TRUE        38
 
15295
+              3 POP_JUMP_IF_TRUE        41
 
15296
               6 LOAD_GLOBAL              0 (AssertionError)
 
15297
               9 BUILD_LIST               0
 
15298
              12 LOAD_FAST                0 (x)
 
15299
@@ -67,10 +67,11 @@
 
15300
 
 
15301
  %-4d   >>   31 LOAD_CONST               2 (1)
 
15302
              34 BINARY_ADD
 
15303
-             35 RAISE_VARARGS            2
 
15304
+             35 CALL_FUNCTION            1
 
15305
+             38 RAISE_VARARGS            1
 
15306
 
 
15307
- %-4d   >>   38 LOAD_CONST               0 (None)
 
15308
-             41 RETURN_VALUE
 
15309
+ %-4d   >>   41 LOAD_CONST               0 (None)
 
15310
+             44 RETURN_VALUE
 
15311
 """%(bug1333982.func_code.co_firstlineno + 1,
 
15312
      bug1333982.func_code.co_firstlineno + 2,
 
15313
      bug1333982.func_code.co_firstlineno + 3)
6562
15314
diff -r 8527427914a2 Lib/test/test_exceptions.py
6563
15315
--- a/Lib/test/test_exceptions.py
6564
15316
+++ b/Lib/test/test_exceptions.py
6565
 
@@ -464,6 +464,14 @@
 
15317
@@ -464,6 +464,20 @@
6566
15318
             self.assertTrue(e is RuntimeError, e)
6567
15319
             self.assertIn("maximum recursion depth exceeded", str(v))
6568
15320
 
6574
15326
+
6575
15327
+        with self.assertRaises(TypeError):
6576
15328
+            raise MyException
 
15329
+
 
15330
+    def test_assert_with_tuple_arg(self):
 
15331
+        try:
 
15332
+            assert False, (3,)
 
15333
+        except AssertionError as e:
 
15334
+            self.assertEqual(str(e), "(3,)")
6577
15335
 
6578
15336
 
6579
15337
 # Helper class used by TestSameStrAndUnicodeMsg
 
15338
diff -r 8527427914a2 Lib/test/test_fcntl.py
 
15339
--- a/Lib/test/test_fcntl.py
 
15340
+++ b/Lib/test/test_fcntl.py
 
15341
@@ -27,12 +27,8 @@
 
15342
         else:
 
15343
             start_len = "qq"
 
15344
 
 
15345
-    if sys.platform in ('netbsd1', 'netbsd2', 'netbsd3',
 
15346
-                        'Darwin1.2', 'darwin',
 
15347
-                        'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
 
15348
-                        'freebsd6', 'freebsd7', 'freebsd8',
 
15349
-                        'bsdos2', 'bsdos3', 'bsdos4',
 
15350
-                        'openbsd', 'openbsd2', 'openbsd3', 'openbsd4'):
 
15351
+    if (sys.platform.startswith(('netbsd', 'freebsd', 'openbsd', 'bsdos'))
 
15352
+        or sys.platform == 'darwin'):
 
15353
         if struct.calcsize('l') == 8:
 
15354
             off_t = 'l'
 
15355
             pid_t = 'i'
 
15356
diff -r 8527427914a2 Lib/test/test_float.py
 
15357
--- a/Lib/test/test_float.py
 
15358
+++ b/Lib/test/test_float.py
 
15359
@@ -164,6 +164,12 @@
 
15360
         self.assertAlmostEqual(float(FooUnicode('8')), 9.)
 
15361
         self.assertAlmostEqual(float(FooStr('8')), 9.)
 
15362
 
 
15363
+    def test_is_integer(self):
 
15364
+        self.assertFalse((1.1).is_integer())
 
15365
+        self.assertTrue((1.).is_integer())
 
15366
+        self.assertFalse(float("nan").is_integer())
 
15367
+        self.assertFalse(float("inf").is_integer())
 
15368
+
 
15369
     def test_floatasratio(self):
 
15370
         for f, ratio in [
 
15371
                 (0.875, (7, 8)),
 
15372
diff -r 8527427914a2 Lib/test/test_htmlparser.py
 
15373
--- a/Lib/test/test_htmlparser.py
 
15374
+++ b/Lib/test/test_htmlparser.py
 
15375
@@ -181,60 +181,6 @@
 
15376
             ("data", "this < text > contains < bare>pointy< brackets"),
 
15377
             ])
 
15378
 
 
15379
-    def test_attr_syntax(self):
 
15380
-        output = [
 
15381
-          ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
 
15382
-          ]
 
15383
-        self._run_check("""<a b='v' c="v" d=v e>""", output)
 
15384
-        self._run_check("""<a  b = 'v' c = "v" d = v e>""", output)
 
15385
-        self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
 
15386
-        self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
 
15387
-
 
15388
-    def test_attr_values(self):
 
15389
-        self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
 
15390
-                        [("starttag", "a", [("b", "xxx\n\txxx"),
 
15391
-                                            ("c", "yyy\t\nyyy"),
 
15392
-                                            ("d", "\txyz\n")])
 
15393
-                         ])
 
15394
-        self._run_check("""<a b='' c="">""", [
 
15395
-            ("starttag", "a", [("b", ""), ("c", "")]),
 
15396
-            ])
 
15397
-        # Regression test for SF patch #669683.
 
15398
-        self._run_check("<e a=rgb(1,2,3)>", [
 
15399
-            ("starttag", "e", [("a", "rgb(1,2,3)")]),
 
15400
-            ])
 
15401
-        # Regression test for SF bug #921657.
 
15402
-        self._run_check("<a href=mailto:xyz@example.com>", [
 
15403
-            ("starttag", "a", [("href", "mailto:xyz@example.com")]),
 
15404
-            ])
 
15405
-
 
15406
-    def test_attr_nonascii(self):
 
15407
-        # see issue 7311
 
15408
-        self._run_check(u"<img src=/foo/bar.png alt=\u4e2d\u6587>", [
 
15409
-            ("starttag", "img", [("src", "/foo/bar.png"),
 
15410
-                                 ("alt", u"\u4e2d\u6587")]),
 
15411
-            ])
 
15412
-        self._run_check(u"<a title='\u30c6\u30b9\u30c8' "
 
15413
-                        u"href='\u30c6\u30b9\u30c8.html'>", [
 
15414
-            ("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"),
 
15415
-                               ("href", u"\u30c6\u30b9\u30c8.html")]),
 
15416
-            ])
 
15417
-        self._run_check(u'<a title="\u30c6\u30b9\u30c8" '
 
15418
-                        u'href="\u30c6\u30b9\u30c8.html">', [
 
15419
-            ("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"),
 
15420
-                               ("href", u"\u30c6\u30b9\u30c8.html")]),
 
15421
-            ])
 
15422
-
 
15423
-    def test_attr_entity_replacement(self):
 
15424
-        self._run_check("""<a b='&amp;&gt;&lt;&quot;&apos;'>""", [
 
15425
-            ("starttag", "a", [("b", "&><\"'")]),
 
15426
-            ])
 
15427
-
 
15428
-    def test_attr_funky_names(self):
 
15429
-        self._run_check("""<a a.b='v' c:d=v e-f=v>""", [
 
15430
-            ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
 
15431
-            ])
 
15432
-
 
15433
     def test_illegal_declarations(self):
 
15434
         self._parse_error('<!spacer type="block" height="25">')
 
15435
 
 
15436
@@ -280,13 +226,11 @@
 
15437
         self._parse_error("<a<a>")
 
15438
         self._parse_error("</a<a>")
 
15439
         self._parse_error("<!")
 
15440
-        self._parse_error("<a $>")
 
15441
         self._parse_error("<a")
 
15442
         self._parse_error("<a foo='bar'")
 
15443
         self._parse_error("<a foo='bar")
 
15444
         self._parse_error("<a foo='>'")
 
15445
         self._parse_error("<a foo='>")
 
15446
-        self._parse_error("<a foo=>")
 
15447
 
 
15448
     def test_declaration_junk_chars(self):
 
15449
         self._parse_error("<!DOCTYPE foo $ >")
 
15450
@@ -312,23 +256,56 @@
 
15451
             ("starttag_text", s)])
 
15452
 
 
15453
     def test_cdata_content(self):
 
15454
-        s = """<script> <!-- not a comment --> &not-an-entity-ref; </script>"""
 
15455
-        self._run_check(s, [
 
15456
-            ("starttag", "script", []),
 
15457
-            ("data", " <!-- not a comment --> &not-an-entity-ref; "),
 
15458
-            ("endtag", "script"),
 
15459
-            ])
 
15460
-        s = """<script> <not a='start tag'> </script>"""
 
15461
-        self._run_check(s, [
 
15462
-            ("starttag", "script", []),
 
15463
-            ("data", " <not a='start tag'> "),
 
15464
-            ("endtag", "script"),
 
15465
-            ])
 
15466
+        contents = [
 
15467
+            '<!-- not a comment --> &not-an-entity-ref;',
 
15468
+            "<not a='start tag'>",
 
15469
+            '<a href="" /> <p> <span></span>',
 
15470
+            'foo = "</scr" + "ipt>";',
 
15471
+            'foo = "</SCRIPT" + ">";',
 
15472
+            'foo = <\n/script> ',
 
15473
+            '<!-- document.write("</scr" + "ipt>"); -->',
 
15474
+            ('\n//<![CDATA[\n'
 
15475
+             'document.write(\'<s\'+\'cript type="text/javascript" '
 
15476
+             'src="http://www.example.org/r=\'+new '
 
15477
+             'Date().getTime()+\'"><\\/s\'+\'cript>\');\n//]]>'),
 
15478
+            '\n<!-- //\nvar foo = 3.14;\n// -->\n',
 
15479
+            'foo = "</sty" + "le>";',
 
15480
+            u'<!-- \u2603 -->',
 
15481
+            # these two should be invalid according to the HTML 5 spec,
 
15482
+            # section 8.1.2.2
 
15483
+            #'foo = </\nscript>',
 
15484
+            #'foo = </ script>',
 
15485
+        ]
 
15486
+        elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style']
 
15487
+        for content in contents:
 
15488
+            for element in elements:
 
15489
+                element_lower = element.lower()
 
15490
+                s = u'<{element}>{content}</{element}>'.format(element=element,
 
15491
+                                                               content=content)
 
15492
+                self._run_check(s, [("starttag", element_lower, []),
 
15493
+                                    ("data", content),
 
15494
+                                    ("endtag", element_lower)])
 
15495
 
 
15496
-    def test_entityrefs_in_attributes(self):
 
15497
-        self._run_check("<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>", [
 
15498
-                ("starttag", "html", [("foo", u"\u20AC&aa&unsupported;")])
 
15499
-                ])
 
15500
+    def test_cdata_with_closing_tags(self):
 
15501
+        # see issue #13358
 
15502
+        # make sure that HTMLParser calls handle_data only once for each CDATA.
 
15503
+        # The normal event collector normalizes the events in get_events,
 
15504
+        # so we override it to return the original list of events.
 
15505
+        class Collector(EventCollector):
 
15506
+            def get_events(self):
 
15507
+                return self.events
 
15508
+
 
15509
+        content = """<!-- not a comment --> &not-an-entity-ref;
 
15510
+                  <a href="" /> </p><p> &amp; <span></span></style>
 
15511
+                  '</script' + '>' </html> </head> </scripter>!"""
 
15512
+        for element in [' script', 'script ', ' script ',
 
15513
+                        '\nscript', 'script\n', '\nscript\n']:
 
15514
+            s = u'<script>{content}</{element}>'.format(element=element,
 
15515
+                                                        content=content)
 
15516
+            self._run_check(s, [("starttag", "script", []),
 
15517
+                                ("data", content),
 
15518
+                                ("endtag", "script")],
 
15519
+                            collector=Collector)
 
15520
 
 
15521
     def test_malformatted_charref(self):
 
15522
         self._run_check("<p>&#bad;</p>", [
 
15523
@@ -343,8 +320,138 @@
 
15524
         self.assertEqual(parser.unescape('&#0038;'),'&')
 
15525
 
 
15526
 
 
15527
+
 
15528
+class AttributesTestCase(TestCaseBase):
 
15529
+
 
15530
+    def test_attr_syntax(self):
 
15531
+        output = [
 
15532
+          ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
 
15533
+        ]
 
15534
+        self._run_check("""<a b='v' c="v" d=v e>""", output)
 
15535
+        self._run_check("""<a  b = 'v' c = "v" d = v e>""", output)
 
15536
+        self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
 
15537
+        self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)
 
15538
+
 
15539
+    def test_attr_values(self):
 
15540
+        self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
 
15541
+                        [("starttag", "a", [("b", "xxx\n\txxx"),
 
15542
+                                            ("c", "yyy\t\nyyy"),
 
15543
+                                            ("d", "\txyz\n")])])
 
15544
+        self._run_check("""<a b='' c="">""",
 
15545
+                        [("starttag", "a", [("b", ""), ("c", "")])])
 
15546
+        # Regression test for SF patch #669683.
 
15547
+        self._run_check("<e a=rgb(1,2,3)>",
 
15548
+                        [("starttag", "e", [("a", "rgb(1,2,3)")])])
 
15549
+        # Regression test for SF bug #921657.
 
15550
+        self._run_check(
 
15551
+            "<a href=mailto:xyz@example.com>",
 
15552
+            [("starttag", "a", [("href", "mailto:xyz@example.com")])])
 
15553
+
 
15554
+    def test_attr_nonascii(self):
 
15555
+        # see issue 7311
 
15556
+        self._run_check(
 
15557
+            u"<img src=/foo/bar.png alt=\u4e2d\u6587>",
 
15558
+            [("starttag", "img", [("src", "/foo/bar.png"),
 
15559
+                                  ("alt", u"\u4e2d\u6587")])])
 
15560
+        self._run_check(
 
15561
+            u"<a title='\u30c6\u30b9\u30c8' href='\u30c6\u30b9\u30c8.html'>",
 
15562
+            [("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"),
 
15563
+                                ("href", u"\u30c6\u30b9\u30c8.html")])])
 
15564
+        self._run_check(
 
15565
+            u'<a title="\u30c6\u30b9\u30c8" href="\u30c6\u30b9\u30c8.html">',
 
15566
+            [("starttag", "a", [("title", u"\u30c6\u30b9\u30c8"),
 
15567
+                                ("href", u"\u30c6\u30b9\u30c8.html")])])
 
15568
+
 
15569
+    def test_attr_entity_replacement(self):
 
15570
+        self._run_check(
 
15571
+            "<a b='&amp;&gt;&lt;&quot;&apos;'>",
 
15572
+            [("starttag", "a", [("b", "&><\"'")])])
 
15573
+
 
15574
+    def test_attr_funky_names(self):
 
15575
+        self._run_check(
 
15576
+            "<a a.b='v' c:d=v e-f=v>",
 
15577
+            [("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")])])
 
15578
+        self._run_check(
 
15579
+            "<a $><b $=%><c \=/>",
 
15580
+            [("starttag", "a", [("$", None)]),
 
15581
+             ("starttag", "b", [("$", "%")]),
 
15582
+             ("starttag", "c", [("\\", "/")])])
 
15583
+
 
15584
+    def test_entityrefs_in_attributes(self):
 
15585
+        self._run_check(
 
15586
+            "<html foo='&euro;&amp;&#97;&#x61;&unsupported;'>",
 
15587
+            [("starttag", "html", [("foo", u"\u20AC&aa&unsupported;")])])
 
15588
+
 
15589
+    def test_entities_in_attribute_value(self):
 
15590
+        # see #1200313
 
15591
+        for entity in ['&', '&amp;', '&#38;', '&#x26;']:
 
15592
+            self._run_check('<a href="%s">' % entity,
 
15593
+                            [("starttag", "a", [("href", "&")])])
 
15594
+            self._run_check("<a href='%s'>" % entity,
 
15595
+                            [("starttag", "a", [("href", "&")])])
 
15596
+            self._run_check("<a href=%s>" % entity,
 
15597
+                            [("starttag", "a", [("href", "&")])])
 
15598
+
 
15599
+    def test_malformed_attributes(self):
 
15600
+        # see #13357
 
15601
+        html = (
 
15602
+            "<a href=test'style='color:red;bad1'>test - bad1</a>"
 
15603
+            "<a href=test'+style='color:red;ba2'>test - bad2</a>"
 
15604
+            "<a href=test'&nbsp;style='color:red;bad3'>test - bad3</a>"
 
15605
+            "<a href = test'&nbsp;style='color:red;bad4'  >test - bad4</a>"
 
15606
+        )
 
15607
+        expected = [
 
15608
+            ('starttag', 'a', [('href', "test'style='color:red;bad1'")]),
 
15609
+            ('data', 'test - bad1'), ('endtag', 'a'),
 
15610
+            ('starttag', 'a', [('href', "test'+style='color:red;ba2'")]),
 
15611
+            ('data', 'test - bad2'), ('endtag', 'a'),
 
15612
+            ('starttag', 'a', [('href', u"test'\xa0style='color:red;bad3'")]),
 
15613
+            ('data', 'test - bad3'), ('endtag', 'a'),
 
15614
+            ('starttag', 'a', [('href', u"test'\xa0style='color:red;bad4'")]),
 
15615
+            ('data', 'test - bad4'), ('endtag', 'a')
 
15616
+        ]
 
15617
+        self._run_check(html, expected)
 
15618
+
 
15619
+    def test_malformed_adjacent_attributes(self):
 
15620
+        # see #12629
 
15621
+        self._run_check('<x><y z=""o"" /></x>',
 
15622
+                        [('starttag', 'x', []),
 
15623
+                            ('startendtag', 'y', [('z', ''), ('o""', None)]),
 
15624
+                            ('endtag', 'x')])
 
15625
+        self._run_check('<x><y z="""" /></x>',
 
15626
+                        [('starttag', 'x', []),
 
15627
+                            ('startendtag', 'y', [('z', ''), ('""', None)]),
 
15628
+                            ('endtag', 'x')])
 
15629
+
 
15630
+    # see #755670 for the following 3 tests
 
15631
+    def test_adjacent_attributes(self):
 
15632
+        self._run_check('<a width="100%"cellspacing=0>',
 
15633
+                        [("starttag", "a",
 
15634
+                          [("width", "100%"), ("cellspacing","0")])])
 
15635
+
 
15636
+        self._run_check('<a id="foo"class="bar">',
 
15637
+                        [("starttag", "a",
 
15638
+                          [("id", "foo"), ("class","bar")])])
 
15639
+
 
15640
+    def test_missing_attribute_value(self):
 
15641
+        self._run_check('<a v=>',
 
15642
+                        [("starttag", "a", [("v", "")])])
 
15643
+
 
15644
+    def test_javascript_attribute_value(self):
 
15645
+        self._run_check("<a href=javascript:popup('/popup/help.html')>",
 
15646
+                        [("starttag", "a",
 
15647
+                          [("href", "javascript:popup('/popup/help.html')")])])
 
15648
+
 
15649
+    def test_end_tag_in_attribute_value(self):
 
15650
+        # see #1745761
 
15651
+        self._run_check("<a href='http://www.example.org/\">;'>spam</a>",
 
15652
+                        [("starttag", "a",
 
15653
+                          [("href", "http://www.example.org/\">;")]),
 
15654
+                         ("data", "spam"), ("endtag", "a")])
 
15655
+
 
15656
+
 
15657
 def test_main():
 
15658
-    test_support.run_unittest(HTMLParserTestCase)
 
15659
+    test_support.run_unittest(HTMLParserTestCase, AttributesTestCase)
 
15660
 
 
15661
 
 
15662
 if __name__ == "__main__":
 
15663
diff -r 8527427914a2 Lib/test/test_httplib.py
 
15664
--- a/Lib/test/test_httplib.py
 
15665
+++ b/Lib/test/test_httplib.py
 
15666
@@ -152,13 +152,15 @@
 
15667
     def test_host_port(self):
 
15668
         # Check invalid host_port
 
15669
 
 
15670
-        for hp in ("www.python.org:abc", "www.python.org:"):
 
15671
+        # Note that httplib does not accept user:password@ in the host-port.
 
15672
+        for hp in ("www.python.org:abc", "user:password@www.python.org"):
 
15673
             self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
 
15674
 
 
15675
         for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
 
15676
                           8000),
 
15677
                          ("www.python.org:80", "www.python.org", 80),
 
15678
                          ("www.python.org", "www.python.org", 80),
 
15679
+                         ("www.python.org:", "www.python.org", 80),
 
15680
                          ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)):
 
15681
             http = httplib.HTTP(hp)
 
15682
             c = http._conn
 
15683
@@ -439,6 +441,28 @@
 
15684
             h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
 
15685
             self.assertEqual(h.timeout, 30)
 
15686
 
 
15687
+    @unittest.skipIf(not hasattr(httplib, 'HTTPS'), 'httplib.HTTPS not available')
 
15688
+    def test_host_port(self):
 
15689
+        # Check invalid host_port
 
15690
+
 
15691
+        # Note that httplib does not accept user:password@ in the host-port.
 
15692
+        for hp in ("www.python.org:abc", "user:password@www.python.org"):
 
15693
+            self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
 
15694
+
 
15695
+        for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
 
15696
+                          8000),
 
15697
+                         ("pypi.python.org:443", "pypi.python.org", 443),
 
15698
+                         ("pypi.python.org", "pypi.python.org", 443),
 
15699
+                         ("pypi.python.org:", "pypi.python.org", 443),
 
15700
+                         ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443)):
 
15701
+            http = httplib.HTTPS(hp)
 
15702
+            c = http._conn
 
15703
+            if h != c.host:
 
15704
+                self.fail("Host incorrectly parsed: %s != %s" % (h, c.host))
 
15705
+            if p != c.port:
 
15706
+                self.fail("Port incorrectly parsed: %s != %s" % (p, c.host))
 
15707
+
 
15708
+
 
15709
 def test_main(verbose=None):
 
15710
     test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
 
15711
                               HTTPSTimeoutTest, SourceAddressTest)
 
15712
diff -r 8527427914a2 Lib/test/test_httpservers.py
 
15713
--- a/Lib/test/test_httpservers.py
 
15714
+++ b/Lib/test/test_httpservers.py
 
15715
@@ -324,8 +324,10 @@
 
15716
         f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
 
15717
         response = self.request('/' + self.tempdir_name + '/')
 
15718
         self.check_status_and_reason(response, 200)
 
15719
-        if os.name == 'posix':
 
15720
-            # chmod won't work as expected on Windows platforms
 
15721
+
 
15722
+        # chmod() doesn't work as expected on Windows, and filesystem
 
15723
+        # permissions are ignored by root on Unix.
 
15724
+        if os.name == 'posix' and os.geteuid() != 0:
 
15725
             os.chmod(self.tempdir, 0)
 
15726
             response = self.request(self.tempdir_name + '/')
 
15727
             self.check_status_and_reason(response, 404)
 
15728
@@ -370,6 +372,9 @@
 
15729
                           form.getfirst("bacon"))
 
15730
 """
 
15731
 
 
15732
+
 
15733
+@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
 
15734
+        "This test can't be run reliably as root (issue #13308).")
 
15735
 class CGIHTTPServerTestCase(BaseTestCase):
 
15736
     class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
 
15737
         pass
 
15738
diff -r 8527427914a2 Lib/test/test_import.py
 
15739
--- a/Lib/test/test_import.py
 
15740
+++ b/Lib/test/test_import.py
 
15741
@@ -265,6 +265,15 @@
 
15742
             """))
 
15743
         script_helper.assert_python_ok(testfn)
 
15744
 
 
15745
+    def test_bug7732(self):
 
15746
+        source = TESTFN + '.py'
 
15747
+        os.mkdir(source)
 
15748
+        try:
 
15749
+            self.assertRaises((ImportError, IOError),
 
15750
+                              imp.find_module, TESTFN, ["."])
 
15751
+        finally:
 
15752
+            os.rmdir(source)
 
15753
+
 
15754
 
 
15755
 class PycRewritingTests(unittest.TestCase):
 
15756
     # Test that the `co_filename` attribute on code objects always points
6580
15757
diff -r 8527427914a2 Lib/test/test_inspect.py
6581
15758
--- a/Lib/test/test_inspect.py
6582
15759
+++ b/Lib/test/test_inspect.py
6607
15784
diff -r 8527427914a2 Lib/test/test_io.py
6608
15785
--- a/Lib/test/test_io.py
6609
15786
+++ b/Lib/test/test_io.py
6610
 
@@ -585,7 +585,24 @@
 
15787
@@ -43,6 +43,10 @@
 
15788
     import threading
 
15789
 except ImportError:
 
15790
     threading = None
 
15791
+try:
 
15792
+    import fcntl
 
15793
+except ImportError:
 
15794
+    fcntl = None
 
15795
 
 
15796
 __metaclass__ = type
 
15797
 bytes = support.py3k_bytes
 
15798
@@ -228,9 +232,14 @@
 
15799
             except ValueError:
 
15800
                 pass
 
15801
             else:
 
15802
-                self._blocker_char = None
 
15803
-                self._write_stack.append(b[:n])
 
15804
-                raise self.BlockingIOError(0, "test blocking", n)
 
15805
+                if n > 0:
 
15806
+                    # write data up to the first blocker
 
15807
+                    self._write_stack.append(b[:n])
 
15808
+                    return n
 
15809
+                else:
 
15810
+                    # cancel blocker and indicate would block
 
15811
+                    self._blocker_char = None
 
15812
+                    return None
 
15813
         self._write_stack.append(b)
 
15814
         return len(b)
 
15815
 
 
15816
@@ -585,7 +594,24 @@
6611
15817
         self.assertEqual(rawio.read(2), b"")
6612
15818
 
6613
15819
 class CIOTest(IOTest):
6633
15839
 
6634
15840
 class PyIOTest(IOTest):
6635
15841
     test_array_writes = unittest.skip(
6636
 
@@ -2557,6 +2574,8 @@
 
15842
@@ -1350,15 +1376,18 @@
 
15843
         rw.seek(0, 0)
 
15844
         self.assertEqual(b"asdf", rw.read(4))
 
15845
 
 
15846
-        rw.write(b"asdf")
 
15847
+        rw.write(b"123f")
 
15848
         rw.seek(0, 0)
 
15849
-        self.assertEqual(b"asdfasdfl", rw.read())
 
15850
+        self.assertEqual(b"asdf123fl", rw.read())
 
15851
         self.assertEqual(9, rw.tell())
 
15852
         rw.seek(-4, 2)
 
15853
         self.assertEqual(5, rw.tell())
 
15854
         rw.seek(2, 1)
 
15855
         self.assertEqual(7, rw.tell())
 
15856
         self.assertEqual(b"fl", rw.read(11))
 
15857
+        rw.flush()
 
15858
+        self.assertEqual(b"asdf123fl", raw.getvalue())
 
15859
+
 
15860
         self.assertRaises(TypeError, rw.seek, 0.0)
 
15861
 
 
15862
     def check_flush_and_read(self, read_func):
 
15863
@@ -1503,6 +1532,44 @@
 
15864
         BufferedReaderTest.test_misbehaved_io(self)
 
15865
         BufferedWriterTest.test_misbehaved_io(self)
 
15866
 
 
15867
+    def test_interleaved_read_write(self):
 
15868
+        # Test for issue #12213
 
15869
+        with self.BytesIO(b'abcdefgh') as raw:
 
15870
+            with self.tp(raw, 100) as f:
 
15871
+                f.write(b"1")
 
15872
+                self.assertEqual(f.read(1), b'b')
 
15873
+                f.write(b'2')
 
15874
+                self.assertEqual(f.read1(1), b'd')
 
15875
+                f.write(b'3')
 
15876
+                buf = bytearray(1)
 
15877
+                f.readinto(buf)
 
15878
+                self.assertEqual(buf, b'f')
 
15879
+                f.write(b'4')
 
15880
+                self.assertEqual(f.peek(1), b'h')
 
15881
+                f.flush()
 
15882
+                self.assertEqual(raw.getvalue(), b'1b2d3f4h')
 
15883
+
 
15884
+        with self.BytesIO(b'abc') as raw:
 
15885
+            with self.tp(raw, 100) as f:
 
15886
+                self.assertEqual(f.read(1), b'a')
 
15887
+                f.write(b"2")
 
15888
+                self.assertEqual(f.read(1), b'c')
 
15889
+                f.flush()
 
15890
+                self.assertEqual(raw.getvalue(), b'a2c')
 
15891
+
 
15892
+    def test_interleaved_readline_write(self):
 
15893
+        with self.BytesIO(b'ab\ncdef\ng\n') as raw:
 
15894
+            with self.tp(raw) as f:
 
15895
+                f.write(b'1')
 
15896
+                self.assertEqual(f.readline(), b'b\n')
 
15897
+                f.write(b'2')
 
15898
+                self.assertEqual(f.readline(), b'def\n')
 
15899
+                f.write(b'3')
 
15900
+                self.assertEqual(f.readline(), b'\n')
 
15901
+                f.flush()
 
15902
+                self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n')
 
15903
+
 
15904
+
 
15905
 class CBufferedRandomTest(CBufferedReaderTest, CBufferedWriterTest, BufferedRandomTest):
 
15906
     tp = io.BufferedRandom
 
15907
 
 
15908
@@ -2280,6 +2347,21 @@
 
15909
         with self.open(support.TESTFN, "rb") as f:
 
15910
             self.assertEqual(f.read(), b"456def")
 
15911
 
 
15912
+    def test_rwpair_cleared_before_textio(self):
 
15913
+        # Issue 13070: TextIOWrapper's finalization would crash when called
 
15914
+        # after the reference to the underlying BufferedRWPair's writer got
 
15915
+        # cleared by the GC.
 
15916
+        for i in range(1000):
 
15917
+            b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())
 
15918
+            t1 = self.TextIOWrapper(b1, encoding="ascii")
 
15919
+            b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())
 
15920
+            t2 = self.TextIOWrapper(b2, encoding="ascii")
 
15921
+            # circular references
 
15922
+            t1.buddy = t2
 
15923
+            t2.buddy = t1
 
15924
+        support.gc_collect()
 
15925
+
 
15926
+
 
15927
 class PyTextIOWrapperTest(TextIOWrapperTest):
 
15928
     pass
 
15929
 
 
15930
@@ -2537,6 +2619,68 @@
 
15931
         # baseline "io" module.
 
15932
         self._check_abc_inheritance(io)
 
15933
 
 
15934
+    @unittest.skipUnless(fcntl, 'fcntl required for this test')
 
15935
+    def test_nonblock_pipe_write_bigbuf(self):
 
15936
+        self._test_nonblock_pipe_write(16*1024)
 
15937
+
 
15938
+    @unittest.skipUnless(fcntl, 'fcntl required for this test')
 
15939
+    def test_nonblock_pipe_write_smallbuf(self):
 
15940
+        self._test_nonblock_pipe_write(1024)
 
15941
+
 
15942
+    def _set_non_blocking(self, fd):
 
15943
+        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
 
15944
+        self.assertNotEqual(flags, -1)
 
15945
+        res = fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
 
15946
+        self.assertEqual(res, 0)
 
15947
+
 
15948
+    def _test_nonblock_pipe_write(self, bufsize):
 
15949
+        sent = []
 
15950
+        received = []
 
15951
+        r, w = os.pipe()
 
15952
+        self._set_non_blocking(r)
 
15953
+        self._set_non_blocking(w)
 
15954
+
 
15955
+        # To exercise all code paths in the C implementation we need
 
15956
+        # to play with buffer sizes.  For instance, if we choose a
 
15957
+        # buffer size less than or equal to _PIPE_BUF (4096 on Linux)
 
15958
+        # then we will never get a partial write of the buffer.
 
15959
+        rf = self.open(r, mode='rb', closefd=True, buffering=bufsize)
 
15960
+        wf = self.open(w, mode='wb', closefd=True, buffering=bufsize)
 
15961
+
 
15962
+        with rf, wf:
 
15963
+            for N in 9999, 73, 7574:
 
15964
+                try:
 
15965
+                    i = 0
 
15966
+                    while True:
 
15967
+                        msg = bytes([i % 26 + 97]) * N
 
15968
+                        sent.append(msg)
 
15969
+                        wf.write(msg)
 
15970
+                        i += 1
 
15971
+
 
15972
+                except self.BlockingIOError as e:
 
15973
+                    self.assertEqual(e.args[0], errno.EAGAIN)
 
15974
+                    sent[-1] = sent[-1][:e.characters_written]
 
15975
+                    received.append(rf.read())
 
15976
+                    msg = b'BLOCKED'
 
15977
+                    wf.write(msg)
 
15978
+                    sent.append(msg)
 
15979
+
 
15980
+            while True:
 
15981
+                try:
 
15982
+                    wf.flush()
 
15983
+                    break
 
15984
+                except self.BlockingIOError as e:
 
15985
+                    self.assertEqual(e.args[0], errno.EAGAIN)
 
15986
+                    self.assertEqual(e.characters_written, 0)
 
15987
+                    received.append(rf.read())
 
15988
+
 
15989
+            received += iter(rf.read, None)
 
15990
+
 
15991
+        sent, received = b''.join(sent), b''.join(received)
 
15992
+        self.assertTrue(sent == received)
 
15993
+        self.assertTrue(wf.closed)
 
15994
+        self.assertTrue(rf.closed)
 
15995
+
 
15996
 class CMiscIOTest(MiscIOTest):
 
15997
     io = io
 
15998
 
 
15999
@@ -2557,6 +2701,8 @@
6637
16000
         1 // 0
6638
16001
 
6639
16002
     @unittest.skipUnless(threading, 'Threading required for this test.')
6642
16005
     def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
6643
16006
         """Check that a partial write, when it gets interrupted, properly
6644
16007
         invokes the signal handler, and bubbles up the exception raised
6645
 
@@ -2610,7 +2629,7 @@
 
16008
@@ -2610,7 +2756,7 @@
6646
16009
         def on_alarm(*args):
6647
16010
             # Will be called reentrantly from the same thread
6648
16011
             wio.write(data)
6761
16124
 
6762
16125
 def test_main():
6763
16126
     tests = [
 
16127
diff -r 8527427914a2 Lib/test/test_logging.py
 
16128
--- a/Lib/test/test_logging.py
 
16129
+++ b/Lib/test/test_logging.py
 
16130
@@ -272,6 +272,8 @@
 
16131
             ('INF.BADPARENT', 'INFO', '4'),
 
16132
         ])
 
16133
 
 
16134
+    def test_invalid_name(self):
 
16135
+        self.assertRaises(TypeError, logging.getLogger, any)
 
16136
 
 
16137
 class BasicFilterTest(BaseTest):
 
16138
 
6764
16139
diff -r 8527427914a2 Lib/test/test_mailbox.py
6765
16140
--- a/Lib/test/test_mailbox.py
6766
16141
+++ b/Lib/test/test_mailbox.py
6778
16153
     def test_iterkeys(self):
6779
16154
         # Get keys using iterkeys()
6780
16155
         self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False)
6781
 
@@ -1670,7 +1677,8 @@
 
16156
@@ -676,6 +683,25 @@
 
16157
                                           key1: os.path.join('new', key1),
 
16158
                                           key2: os.path.join('new', key2)})
 
16159
 
 
16160
+    def test_refresh_after_safety_period(self):
 
16161
+        # Issue #13254: Call _refresh after the "file system safety
 
16162
+        # period" of 2 seconds has passed; _toc should still be
 
16163
+        # updated because this is the first call to _refresh.
 
16164
+        key0 = self._box.add(self._template % 0)
 
16165
+        key1 = self._box.add(self._template % 1)
 
16166
+
 
16167
+        self._box = self._factory(self._path)
 
16168
+        self.assertEqual(self._box._toc, {})
 
16169
+
 
16170
+        # Emulate sleeping. Instead of sleeping for 2 seconds, use the
 
16171
+        # skew factor to make _refresh think that the filesystem
 
16172
+        # safety period has passed and re-reading the _toc is only
 
16173
+        # required if mtimes differ.
 
16174
+        self._box._skewfactor = -3
 
16175
+
 
16176
+        self._box._refresh()
 
16177
+        self.assertEqual(sorted(self._box._toc.keys()), sorted([key0, key1]))
 
16178
+
 
16179
     def test_lookup(self):
 
16180
         # Look up message subpaths in the TOC
 
16181
         self.assertRaises(KeyError, lambda: self._box._lookup('foo'))
 
16182
@@ -751,6 +777,8 @@
 
16183
         self.assertFalse((perms & 0111)) # Execute bits should all be off.
 
16184
 
 
16185
     def test_reread(self):
 
16186
+        # Do an initial unconditional refresh
 
16187
+        self._box._refresh()
 
16188
 
 
16189
         # Put the last modified times more than two seconds into the past
 
16190
         # (because mtime may have only a two second granularity).
 
16191
@@ -762,7 +790,12 @@
 
16192
         # refresh is done unconditionally if called for within
 
16193
         # two-second-plus-a-bit of the last one, just in case the mbox has
 
16194
         # changed; so now we have to wait for that interval to expire.
 
16195
-        time.sleep(2.01 + self._box._skewfactor)
 
16196
+        #
 
16197
+        # Because this is a test, emulate sleeping. Instead of
 
16198
+        # sleeping for 2 seconds, use the skew factor to make _refresh
 
16199
+        # think that 2 seconds have passed and re-reading the _toc is
 
16200
+        # only required if mtimes differ.
 
16201
+        self._box._skewfactor = -3
 
16202
 
 
16203
         # Re-reading causes the ._toc attribute to be assigned a new dictionary
 
16204
         # object, so we'll check that the ._toc attribute isn't a different
 
16205
@@ -775,7 +808,8 @@
 
16206
         self.assertFalse(refreshed())
 
16207
 
 
16208
         # Now, write something into cur and remove it.  This changes
 
16209
-        # the mtime and should cause a re-read.
 
16210
+        # the mtime and should cause a re-read. Note that "sleep
 
16211
+        # emulation" is still in effect, as skewfactor is -3.
 
16212
         filename = os.path.join(self._path, 'cur', 'stray-file')
 
16213
         f = open(filename, 'w')
 
16214
         f.close()
 
16215
@@ -1670,7 +1704,8 @@
6782
16216
     def _test_close(self, proxy):
6783
16217
         # Close a file
6784
16218
         proxy.close()
6788
16222
 
6789
16223
 
6790
16224
 class TestProxyFile(TestProxyFileBase):
 
16225
diff -r 8527427914a2 Lib/test/test_minidom.py
 
16226
--- a/Lib/test/test_minidom.py
 
16227
+++ b/Lib/test/test_minidom.py
 
16228
@@ -439,6 +439,40 @@
 
16229
         dom.unlink()
 
16230
         self.confirm(domstr == str.replace("\n", "\r\n"))
 
16231
 
 
16232
+    def test_toprettyxml_with_text_nodes(self):
 
16233
+        # see issue #4147, text nodes are not indented
 
16234
+        decl = '<?xml version="1.0" ?>\n'
 
16235
+        self.assertEqual(parseString('<B>A</B>').toprettyxml(),
 
16236
+                         decl + '<B>A</B>\n')
 
16237
+        self.assertEqual(parseString('<C>A<B>A</B></C>').toprettyxml(),
 
16238
+                         decl + '<C>\n\tA\n\t<B>A</B>\n</C>\n')
 
16239
+        self.assertEqual(parseString('<C><B>A</B>A</C>').toprettyxml(),
 
16240
+                         decl + '<C>\n\t<B>A</B>\n\tA\n</C>\n')
 
16241
+        self.assertEqual(parseString('<C><B>A</B><B>A</B></C>').toprettyxml(),
 
16242
+                         decl + '<C>\n\t<B>A</B>\n\t<B>A</B>\n</C>\n')
 
16243
+        self.assertEqual(parseString('<C><B>A</B>A<B>A</B></C>').toprettyxml(),
 
16244
+                         decl + '<C>\n\t<B>A</B>\n\tA\n\t<B>A</B>\n</C>\n')
 
16245
+
 
16246
+    def test_toprettyxml_with_adjacent_text_nodes(self):
 
16247
+        # see issue #4147, adjacent text nodes are indented normally
 
16248
+        dom = Document()
 
16249
+        elem = dom.createElement(u'elem')
 
16250
+        elem.appendChild(dom.createTextNode(u'TEXT'))
 
16251
+        elem.appendChild(dom.createTextNode(u'TEXT'))
 
16252
+        dom.appendChild(elem)
 
16253
+        decl = '<?xml version="1.0" ?>\n'
 
16254
+        self.assertEqual(dom.toprettyxml(),
 
16255
+                         decl + '<elem>\n\tTEXT\n\tTEXT\n</elem>\n')
 
16256
+
 
16257
+    def test_toprettyxml_preserves_content_of_text_node(self):
 
16258
+        # see issue #4147
 
16259
+        for str in ('<B>A</B>', '<A><B>C</B></A>'):
 
16260
+            dom = parseString(str)
 
16261
+            dom2 = parseString(dom.toprettyxml())
 
16262
+            self.assertEqual(
 
16263
+                dom.getElementsByTagName('B')[0].childNodes[0].toxml(),
 
16264
+                dom2.getElementsByTagName('B')[0].childNodes[0].toxml())
 
16265
+
 
16266
     def testProcessingInstruction(self):
 
16267
         dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
 
16268
         pi = dom.documentElement.firstChild
6791
16269
diff -r 8527427914a2 Lib/test/test_multibytecodec_support.py
6792
16270
--- a/Lib/test/test_multibytecodec_support.py
6793
16271
+++ b/Lib/test/test_multibytecodec_support.py
6860
16338
diff -r 8527427914a2 Lib/test/test_multiprocessing.py
6861
16339
--- a/Lib/test/test_multiprocessing.py
6862
16340
+++ b/Lib/test/test_multiprocessing.py
6863
 
@@ -1085,6 +1085,9 @@
 
16341
@@ -15,6 +15,7 @@
 
16342
 import socket
 
16343
 import random
 
16344
 import logging
 
16345
+import errno
 
16346
 from test import test_support
 
16347
 from StringIO import StringIO
 
16348
 _multiprocessing = test_support.import_module('_multiprocessing')
 
16349
@@ -35,11 +36,22 @@
 
16350
 from multiprocessing import util
 
16351
 
 
16352
 try:
 
16353
+    from multiprocessing import reduction
 
16354
+    HAS_REDUCTION = True
 
16355
+except ImportError:
 
16356
+    HAS_REDUCTION = False
 
16357
+
 
16358
+try:
 
16359
     from multiprocessing.sharedctypes import Value, copy
 
16360
     HAS_SHAREDCTYPES = True
 
16361
 except ImportError:
 
16362
     HAS_SHAREDCTYPES = False
 
16363
 
 
16364
+try:
 
16365
+    import msvcrt
 
16366
+except ImportError:
 
16367
+    msvcrt = None
 
16368
+
 
16369
 #
 
16370
 #
 
16371
 #
 
16372
@@ -68,6 +80,11 @@
 
16373
 
 
16374
 WIN32 = (sys.platform == "win32")
 
16375
 
 
16376
+try:
 
16377
+    MAXFD = os.sysconf("SC_OPEN_MAX")
 
16378
+except:
 
16379
+    MAXFD = 256
 
16380
+
 
16381
 #
 
16382
 # Some tests require ctypes
 
16383
 #
 
16384
@@ -78,6 +95,22 @@
 
16385
     Structure = object
 
16386
     c_int = c_double = None
 
16387
 
 
16388
+
 
16389
+def check_enough_semaphores():
 
16390
+    """Check that the system supports enough semaphores to run the test."""
 
16391
+    # minimum number of semaphores available according to POSIX
 
16392
+    nsems_min = 256
 
16393
+    try:
 
16394
+        nsems = os.sysconf("SC_SEM_NSEMS_MAX")
 
16395
+    except (AttributeError, ValueError):
 
16396
+        # sysconf not available or setting not available
 
16397
+        return
 
16398
+    if nsems == -1 or nsems >= nsems_min:
 
16399
+        return
 
16400
+    raise unittest.SkipTest("The OS doesn't support enough semaphores "
 
16401
+                            "to run the test (required: %d)." % nsems_min)
 
16402
+
 
16403
+
 
16404
 #
 
16405
 # Creates a wrapper for a function which records the time it takes to finish
 
16406
 #
 
16407
@@ -253,6 +286,7 @@
 
16408
         p = self.Process(target=time.sleep, args=(DELTA,))
 
16409
         self.assertNotIn(p, self.active_children())
 
16410
 
 
16411
+        p.daemon = True
 
16412
         p.start()
 
16413
         self.assertIn(p, self.active_children())
 
16414
 
 
16415
@@ -323,6 +357,7 @@
 
16416
 
 
16417
     def test_subclassing(self):
 
16418
         uppercaser = _UpperCaser()
 
16419
+        uppercaser.daemon = True
 
16420
         uppercaser.start()
 
16421
         self.assertEqual(uppercaser.submit('hello'), 'HELLO')
 
16422
         self.assertEqual(uppercaser.submit('world'), 'WORLD')
 
16423
@@ -501,6 +536,7 @@
 
16424
 
 
16425
         # fork process
 
16426
         p = self.Process(target=self._test_fork, args=(queue,))
 
16427
+        p.daemon = True
 
16428
         p.start()
 
16429
 
 
16430
         # check that all expected items are in the queue
 
16431
@@ -541,6 +577,7 @@
 
16432
                    for i in xrange(4)]
 
16433
 
 
16434
         for p in workers:
 
16435
+            p.daemon = True
 
16436
             p.start()
 
16437
 
 
16438
         for i in xrange(10):
 
16439
@@ -805,7 +842,9 @@
 
16440
 
 
16441
         #self.assertEqual(event.is_set(), False)
 
16442
 
 
16443
-        self.Process(target=self._test_event, args=(event,)).start()
 
16444
+        p = self.Process(target=self._test_event, args=(event,))
 
16445
+        p.daemon = True
 
16446
+        p.start()
 
16447
         self.assertEqual(wait(), True)
 
16448
 
 
16449
 #
 
16450
@@ -845,6 +884,7 @@
 
16451
             self.assertEqual(sv.value, cv[1])
 
16452
 
 
16453
         proc = self.Process(target=self._test, args=(values,))
 
16454
+        proc.daemon = True
 
16455
         proc.start()
 
16456
         proc.join()
 
16457
 
 
16458
@@ -908,6 +948,7 @@
 
16459
         self.f(seq)
 
16460
 
 
16461
         p = self.Process(target=self.f, args=(arr,))
 
16462
+        p.daemon = True
 
16463
         p.start()
 
16464
         p.join()
 
16465
 
 
16466
@@ -1085,6 +1126,9 @@
6864
16467
         self.assertEqual(sorted(it), map(sqr, range(1000)))
6865
16468
 
6866
16469
     def test_make_pool(self):
6870
16473
         p = multiprocessing.Pool(3)
6871
16474
         self.assertEqual(3, len(p._pool))
6872
16475
         p.close()
6873
 
@@ -1612,6 +1615,8 @@
 
16476
@@ -1140,6 +1184,20 @@
 
16477
         p.close()
 
16478
         p.join()
 
16479
 
 
16480
+    def test_pool_worker_lifetime_early_close(self):
 
16481
+        # Issue #10332: closing a pool whose workers have limited lifetimes
 
16482
+        # before all the tasks completed would make join() hang.
 
16483
+        p = multiprocessing.Pool(3, maxtasksperchild=1)
 
16484
+        results = []
 
16485
+        for i in range(6):
 
16486
+            results.append(p.apply_async(sqr, (i, 0.3)))
 
16487
+        p.close()
 
16488
+        p.join()
 
16489
+        # check the results
 
16490
+        for (j, res) in enumerate(results):
 
16491
+            self.assertEqual(res.get(), sqr(j))
 
16492
+
 
16493
+
 
16494
 #
 
16495
 # Test that manager has expected number of shared objects left
 
16496
 #
 
16497
@@ -1271,6 +1329,7 @@
 
16498
         manager.start()
 
16499
 
 
16500
         p = self.Process(target=self._putter, args=(manager.address, authkey))
 
16501
+        p.daemon = True
 
16502
         p.start()
 
16503
 
 
16504
         manager2 = QueueManager2(
 
16505
@@ -1312,6 +1371,7 @@
 
16506
         manager.start()
 
16507
 
 
16508
         p = self.Process(target=self._putter, args=(manager.address, authkey))
 
16509
+        p.daemon = True
 
16510
         p.start()
 
16511
         queue = manager.get_queue()
 
16512
         self.assertEqual(queue.get(), 'hello world')
 
16513
@@ -1435,6 +1495,7 @@
 
16514
         conn, child_conn = self.Pipe()
 
16515
 
 
16516
         p = self.Process(target=self._echo, args=(child_conn,))
 
16517
+        p.daemon = True
 
16518
         p.start()
 
16519
         child_conn.close()    # this might complete before child initializes
 
16520
 
 
16521
@@ -1478,6 +1539,98 @@
 
16522
 
 
16523
         self.assertRaises(ValueError, a.send_bytes, msg, 4, -1)
 
16524
 
 
16525
+    @classmethod
 
16526
+    def _is_fd_assigned(cls, fd):
 
16527
+        try:
 
16528
+            os.fstat(fd)
 
16529
+        except OSError as e:
 
16530
+            if e.errno == errno.EBADF:
 
16531
+                return False
 
16532
+            raise
 
16533
+        else:
 
16534
+            return True
 
16535
+
 
16536
+    @classmethod
 
16537
+    def _writefd(cls, conn, data, create_dummy_fds=False):
 
16538
+        if create_dummy_fds:
 
16539
+            for i in range(0, 256):
 
16540
+                if not cls._is_fd_assigned(i):
 
16541
+                    os.dup2(conn.fileno(), i)
 
16542
+        fd = reduction.recv_handle(conn)
 
16543
+        if msvcrt:
 
16544
+            fd = msvcrt.open_osfhandle(fd, os.O_WRONLY)
 
16545
+        os.write(fd, data)
 
16546
+        os.close(fd)
 
16547
+
 
16548
+    @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
 
16549
+    def test_fd_transfer(self):
 
16550
+        if self.TYPE != 'processes':
 
16551
+            self.skipTest("only makes sense with processes")
 
16552
+        conn, child_conn = self.Pipe(duplex=True)
 
16553
+
 
16554
+        p = self.Process(target=self._writefd, args=(child_conn, b"foo"))
 
16555
+        p.daemon = True
 
16556
+        p.start()
 
16557
+        with open(test_support.TESTFN, "wb") as f:
 
16558
+            fd = f.fileno()
 
16559
+            if msvcrt:
 
16560
+                fd = msvcrt.get_osfhandle(fd)
 
16561
+            reduction.send_handle(conn, fd, p.pid)
 
16562
+        p.join()
 
16563
+        with open(test_support.TESTFN, "rb") as f:
 
16564
+            self.assertEqual(f.read(), b"foo")
 
16565
+
 
16566
+    @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
 
16567
+    @unittest.skipIf(sys.platform == "win32",
 
16568
+                     "test semantics don't make sense on Windows")
 
16569
+    @unittest.skipIf(MAXFD <= 256,
 
16570
+                     "largest assignable fd number is too small")
 
16571
+    @unittest.skipUnless(hasattr(os, "dup2"),
 
16572
+                         "test needs os.dup2()")
 
16573
+    def test_large_fd_transfer(self):
 
16574
+        # With fd > 256 (issue #11657)
 
16575
+        if self.TYPE != 'processes':
 
16576
+            self.skipTest("only makes sense with processes")
 
16577
+        conn, child_conn = self.Pipe(duplex=True)
 
16578
+
 
16579
+        p = self.Process(target=self._writefd, args=(child_conn, b"bar", True))
 
16580
+        p.daemon = True
 
16581
+        p.start()
 
16582
+        with open(test_support.TESTFN, "wb") as f:
 
16583
+            fd = f.fileno()
 
16584
+            for newfd in range(256, MAXFD):
 
16585
+                if not self._is_fd_assigned(newfd):
 
16586
+                    break
 
16587
+            else:
 
16588
+                self.fail("could not find an unassigned large file descriptor")
 
16589
+            os.dup2(fd, newfd)
 
16590
+            try:
 
16591
+                reduction.send_handle(conn, newfd, p.pid)
 
16592
+            finally:
 
16593
+                os.close(newfd)
 
16594
+        p.join()
 
16595
+        with open(test_support.TESTFN, "rb") as f:
 
16596
+            self.assertEqual(f.read(), b"bar")
 
16597
+
 
16598
+    @classmethod
 
16599
+    def _send_data_without_fd(self, conn):
 
16600
+        os.write(conn.fileno(), b"\0")
 
16601
+
 
16602
+    @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction")
 
16603
+    @unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows")
 
16604
+    def test_missing_fd_transfer(self):
 
16605
+        # Check that exception is raised when received data is not
 
16606
+        # accompanied by a file descriptor in ancillary data.
 
16607
+        if self.TYPE != 'processes':
 
16608
+            self.skipTest("only makes sense with processes")
 
16609
+        conn, child_conn = self.Pipe(duplex=True)
 
16610
+
 
16611
+        p = self.Process(target=self._send_data_without_fd, args=(child_conn,))
 
16612
+        p.daemon = True
 
16613
+        p.start()
 
16614
+        self.assertRaises(RuntimeError, reduction.recv_handle, conn)
 
16615
+        p.join()
 
16616
+
 
16617
 class _TestListenerClient(BaseTestCase):
 
16618
 
 
16619
     ALLOWED_TYPES = ('processes', 'threads')
 
16620
@@ -1548,11 +1701,13 @@
 
16621
 
 
16622
         lconn, lconn0 = self.Pipe()
 
16623
         lp = self.Process(target=self._listener, args=(lconn0, families))
 
16624
+        lp.daemon = True
 
16625
         lp.start()
 
16626
         lconn0.close()
 
16627
 
 
16628
         rconn, rconn0 = self.Pipe()
 
16629
         rp = self.Process(target=self._remote, args=(rconn0,))
 
16630
+        rp.daemon = True
 
16631
         rp.start()
 
16632
         rconn0.close()
 
16633
 
 
16634
@@ -1612,6 +1767,8 @@
6874
16635
         # verify the state of the heap
6875
16636
         all = []
6876
16637
         occupied = 0
6879
16640
         for L in heap._len_to_seq.values():
6880
16641
             for arena, start, stop in L:
6881
16642
                 all.append((heap._arenas.index(arena), start, stop,
6882
 
@@ -1629,6 +1634,28 @@
 
16643
@@ -1629,6 +1786,28 @@
6883
16644
             self.assertTrue((arena != narena and nstart == 0) or
6884
16645
                             (stop == nstart))
6885
16646
 
6908
16669
 #
6909
16670
 #
6910
16671
 #
 
16672
@@ -1666,6 +1845,7 @@
 
16673
         string.value = latin('hello')
 
16674
 
 
16675
         p = self.Process(target=self._double, args=(x, y, foo, arr, string))
 
16676
+        p.daemon = True
 
16677
         p.start()
 
16678
         p.join()
 
16679
 
 
16680
@@ -1738,6 +1918,7 @@
 
16681
         conn, child_conn = self.Pipe()
 
16682
 
 
16683
         p = self.Process(target=self._test_finalize, args=(child_conn,))
 
16684
+        p.daemon = True
 
16685
         p.start()
 
16686
         p.join()
 
16687
 
 
16688
@@ -1757,10 +1938,12 @@
 
16689
             'multiprocessing', 'multiprocessing.connection',
 
16690
             'multiprocessing.heap', 'multiprocessing.managers',
 
16691
             'multiprocessing.pool', 'multiprocessing.process',
 
16692
-            'multiprocessing.reduction',
 
16693
             'multiprocessing.synchronize', 'multiprocessing.util'
 
16694
             ]
 
16695
 
 
16696
+        if HAS_REDUCTION:
 
16697
+            modules.append('multiprocessing.reduction')
 
16698
+
 
16699
         if c_int is not None:
 
16700
             # This module requires _ctypes
 
16701
             modules.append('multiprocessing.sharedctypes')
 
16702
@@ -1807,12 +1990,16 @@
 
16703
         reader, writer = multiprocessing.Pipe(duplex=False)
 
16704
 
 
16705
         logger.setLevel(LEVEL1)
 
16706
-        self.Process(target=self._test_level, args=(writer,)).start()
 
16707
+        p = self.Process(target=self._test_level, args=(writer,))
 
16708
+        p.daemon = True
 
16709
+        p.start()
 
16710
         self.assertEqual(LEVEL1, reader.recv())
 
16711
 
 
16712
         logger.setLevel(logging.NOTSET)
 
16713
         root_logger.setLevel(LEVEL2)
 
16714
-        self.Process(target=self._test_level, args=(writer,)).start()
 
16715
+        p = self.Process(target=self._test_level, args=(writer,))
 
16716
+        p.daemon = True
 
16717
+        p.start()
 
16718
         self.assertEqual(LEVEL2, reader.recv())
 
16719
 
 
16720
         root_logger.setLevel(root_level)
 
16721
@@ -1998,6 +2185,7 @@
 
16722
 def _TestProcess(q):
 
16723
     queue = multiprocessing.Queue()
 
16724
     subProc = multiprocessing.Process(target=_ThisSubProcess, args=(queue,))
 
16725
+    subProc.daemon = True
 
16726
     subProc.start()
 
16727
     subProc.join()
 
16728
 
 
16729
@@ -2064,6 +2252,8 @@
 
16730
         except OSError:
 
16731
             raise unittest.SkipTest("OSError raises on RLock creation, see issue 3111!")
 
16732
 
 
16733
+    check_enough_semaphores()
 
16734
+
 
16735
     if run is None:
 
16736
         from test.test_support import run_unittest as run
 
16737
 
 
16738
diff -r 8527427914a2 Lib/test/test_os.py
 
16739
--- a/Lib/test/test_os.py
 
16740
+++ b/Lib/test/test_os.py
 
16741
@@ -361,6 +361,20 @@
 
16742
                 value = popen.read().strip()
 
16743
                 self.assertEqual(value, "World")
 
16744
 
 
16745
+    # On FreeBSD < 7 and OS X < 10.6, unsetenv() doesn't return a value (issue
 
16746
+    # #13415).
 
16747
+    @unittest.skipIf(sys.platform.startswith(('freebsd', 'darwin')),
 
16748
+                     "due to known OS bug: see issue #13415")
 
16749
+    def test_unset_error(self):
 
16750
+        if sys.platform == "win32":
 
16751
+            # an environment variable is limited to 32,767 characters
 
16752
+            key = 'x' * 50000
 
16753
+            self.assertRaises(ValueError, os.environ.__delitem__, key)
 
16754
+        else:
 
16755
+            # "=" is not allowed in a variable name
 
16756
+            key = 'key='
 
16757
+            self.assertRaises(OSError, os.environ.__delitem__, key)
 
16758
+
 
16759
 class WalkTests(unittest.TestCase):
 
16760
     """Tests for os.walk()."""
 
16761
 
 
16762
diff -r 8527427914a2 Lib/test/test_pdb.py
 
16763
--- a/Lib/test/test_pdb.py
 
16764
+++ b/Lib/test/test_pdb.py
 
16765
@@ -3,6 +3,9 @@
 
16766
 
 
16767
 import imp
 
16768
 import sys
 
16769
+import os
 
16770
+import unittest
 
16771
+import subprocess
 
16772
 
 
16773
 from test import test_support
 
16774
 # This little helper class is essential for testing pdb under doctest.
 
16775
@@ -277,6 +280,29 @@
 
16776
     4
 
16777
     """
 
16778
 
 
16779
+class Tester7750(unittest.TestCase):
 
16780
+    # if the filename has something that resolves to a python
 
16781
+    #  escape character (such as \t), it will fail
 
16782
+    test_fn = '.\\test7750.py'
 
16783
+
 
16784
+    msg = "issue7750 only applies when os.sep is a backslash"
 
16785
+    @unittest.skipUnless(os.path.sep == '\\', msg)
 
16786
+    def test_issue7750(self):
 
16787
+        with open(self.test_fn, 'w') as f:
 
16788
+            f.write('print("hello world")')
 
16789
+        cmd = [sys.executable, '-m', 'pdb', self.test_fn,]
 
16790
+        proc = subprocess.Popen(cmd,
 
16791
+            stdout=subprocess.PIPE,
 
16792
+            stdin=subprocess.PIPE,
 
16793
+            stderr=subprocess.STDOUT,
 
16794
+            )
 
16795
+        stdout, stderr = proc.communicate('quit\n')
 
16796
+        self.assertNotIn('IOError', stdout, "pdb munged the filename")
 
16797
+
 
16798
+    def tearDown(self):
 
16799
+        if os.path.isfile(self.test_fn):
 
16800
+            os.remove(self.test_fn)
 
16801
+
 
16802
 
 
16803
 def test_main():
 
16804
     from test import test_pdb
 
16805
@@ -285,3 +311,4 @@
 
16806
 
 
16807
 if __name__ == '__main__':
 
16808
     test_main()
 
16809
+    unittest.main()
 
16810
diff -r 8527427914a2 Lib/test/test_pkgutil.py
 
16811
--- a/Lib/test/test_pkgutil.py
 
16812
+++ b/Lib/test/test_pkgutil.py
 
16813
@@ -15,11 +15,11 @@
 
16814
 
 
16815
     def setUp(self):
 
16816
         self.dirname = tempfile.mkdtemp()
 
16817
+        self.addCleanup(shutil.rmtree, self.dirname)
 
16818
         sys.path.insert(0, self.dirname)
 
16819
 
 
16820
     def tearDown(self):
 
16821
         del sys.path[0]
 
16822
-        shutil.rmtree(self.dirname)
 
16823
 
 
16824
     def test_getdata_filesys(self):
 
16825
         pkg = 'test_getdata_filesys'
 
16826
@@ -78,6 +78,17 @@
 
16827
 
 
16828
         del sys.modules[pkg]
 
16829
 
 
16830
+    def test_unreadable_dir_on_syspath(self):
 
16831
+        # issue7367 - walk_packages failed if unreadable dir on sys.path
 
16832
+        package_name = "unreadable_package"
 
16833
+        d = os.path.join(self.dirname, package_name)
 
16834
+        # this does not appear to create an unreadable dir on Windows
 
16835
+        #   but the test should not fail anyway
 
16836
+        os.mkdir(d, 0)
 
16837
+        self.addCleanup(os.rmdir, d)
 
16838
+        for t in pkgutil.walk_packages(path=[self.dirname]):
 
16839
+            self.fail("unexpected package found")
 
16840
+
 
16841
 class PkgutilPEP302Tests(unittest.TestCase):
 
16842
 
 
16843
     class MyTestLoader(object):
6911
16844
diff -r 8527427914a2 Lib/test/test_platform.py
6912
16845
--- a/Lib/test/test_platform.py
6913
16846
+++ b/Lib/test/test_platform.py
7019
16952
 
7020
16953
     def test_getcwd_long_pathnames(self):
7021
16954
         if hasattr(posix, 'getcwd'):
 
16955
diff -r 8527427914a2 Lib/test/test_py_compile.py
 
16956
--- /dev/null
 
16957
+++ b/Lib/test/test_py_compile.py
 
16958
@@ -0,0 +1,54 @@
 
16959
+import imp
 
16960
+import os
 
16961
+import py_compile
 
16962
+import shutil
 
16963
+import tempfile
 
16964
+import unittest
 
16965
+
 
16966
+from test import test_support
 
16967
+
 
16968
+class PyCompileTests(unittest.TestCase):
 
16969
+
 
16970
+    def setUp(self):
 
16971
+        self.directory = tempfile.mkdtemp()
 
16972
+        self.source_path = os.path.join(self.directory, '_test.py')
 
16973
+        self.pyc_path = self.source_path + 'c'
 
16974
+        self.cwd_drive = os.path.splitdrive(os.getcwd())[0]
 
16975
+        # In these tests we compute relative paths.  When using Windows, the
 
16976
+        # current working directory path and the 'self.source_path' might be
 
16977
+        # on different drives.  Therefore we need to switch to the drive where
 
16978
+        # the temporary source file lives.
 
16979
+        drive = os.path.splitdrive(self.source_path)[0]
 
16980
+        if drive:
 
16981
+            os.chdir(drive)
 
16982
+
 
16983
+        with open(self.source_path, 'w') as file:
 
16984
+            file.write('x = 123\n')
 
16985
+
 
16986
+    def tearDown(self):
 
16987
+        shutil.rmtree(self.directory)
 
16988
+        if self.cwd_drive:
 
16989
+            os.chdir(self.cwd_drive)
 
16990
+
 
16991
+    def test_absolute_path(self):
 
16992
+        py_compile.compile(self.source_path, self.pyc_path)
 
16993
+        self.assertTrue(os.path.exists(self.pyc_path))
 
16994
+
 
16995
+    def test_cwd(self):
 
16996
+        cwd = os.getcwd()
 
16997
+        os.chdir(self.directory)
 
16998
+        py_compile.compile(os.path.basename(self.source_path),
 
16999
+                           os.path.basename(self.pyc_path))
 
17000
+        os.chdir(cwd)
 
17001
+        self.assertTrue(os.path.exists(self.pyc_path))
 
17002
+
 
17003
+    def test_relative_path(self):
 
17004
+        py_compile.compile(os.path.relpath(self.source_path),
 
17005
+                           os.path.relpath(self.pyc_path))
 
17006
+        self.assertTrue(os.path.exists(self.pyc_path))
 
17007
+
 
17008
+def test_main():
 
17009
+    test_support.run_unittest(PyCompileTests)
 
17010
+
 
17011
+if __name__ == "__main__":
 
17012
+    test_main()
7022
17013
diff -r 8527427914a2 Lib/test/test_pydoc.py
7023
17014
--- a/Lib/test/test_pydoc.py
7024
17015
+++ b/Lib/test/test_pydoc.py
7025
 
@@ -1,8 +1,8 @@
 
17016
@@ -1,8 +1,7 @@
7026
17017
+import os
7027
17018
 import sys
7028
17019
-import os
7029
17020
-import os.path
7030
17021
 import difflib
7031
 
 import subprocess
 
17022
-import subprocess
7032
17023
+import __builtin__
7033
17024
 import re
7034
17025
 import pydoc
7035
17026
 import inspect
7036
 
@@ -357,6 +357,23 @@
 
17027
@@ -10,10 +9,10 @@
 
17028
 import unittest
 
17029
 import xml.etree
 
17030
 import test.test_support
 
17031
-from contextlib import contextmanager
 
17032
 from collections import namedtuple
 
17033
+from test.script_helper import assert_python_ok
 
17034
 from test.test_support import (
 
17035
-    TESTFN, forget, rmtree, EnvironmentVarGuard, reap_children, captured_stdout)
 
17036
+    TESTFN, rmtree, reap_children, captured_stdout)
 
17037
 
 
17038
 from test import pydoc_mod
 
17039
 
 
17040
@@ -176,17 +175,15 @@
 
17041
 # output pattern for module with bad imports
 
17042
 badimport_pattern = "problem in %s - <type 'exceptions.ImportError'>: No module named %s"
 
17043
 
 
17044
-def run_pydoc(module_name, *args):
 
17045
+def run_pydoc(module_name, *args, **env):
 
17046
     """
 
17047
     Runs pydoc on the specified module. Returns the stripped
 
17048
     output of pydoc.
 
17049
     """
 
17050
-    cmd = [sys.executable, pydoc.__file__, " ".join(args), module_name]
 
17051
-    try:
 
17052
-        output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]
 
17053
-        return output.strip()
 
17054
-    finally:
 
17055
-        reap_children()
 
17056
+    args = args + (module_name,)
 
17057
+    # do not write bytecode files to avoid caching errors
 
17058
+    rc, out, err = assert_python_ok('-B', pydoc.__file__, *args, **env)
 
17059
+    return out.strip()
 
17060
 
 
17061
 def get_pydoc_html(module):
 
17062
     "Returns pydoc generated output as html"
 
17063
@@ -259,42 +256,6 @@
 
17064
         self.assertEqual(expected, result,
 
17065
             "documentation for missing module found")
 
17066
 
 
17067
-    def test_badimport(self):
 
17068
-        # This tests the fix for issue 5230, where if pydoc found the module
 
17069
-        # but the module had an internal import error pydoc would report no doc
 
17070
-        # found.
 
17071
-        modname = 'testmod_xyzzy'
 
17072
-        testpairs = (
 
17073
-            ('i_am_not_here', 'i_am_not_here'),
 
17074
-            ('test.i_am_not_here_either', 'i_am_not_here_either'),
 
17075
-            ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
 
17076
-            ('i_am_not_here.{}'.format(modname), 'i_am_not_here.{}'.format(modname)),
 
17077
-            ('test.{}'.format(modname), modname),
 
17078
-            )
 
17079
-
 
17080
-        @contextmanager
 
17081
-        def newdirinpath(dir):
 
17082
-            os.mkdir(dir)
 
17083
-            sys.path.insert(0, dir)
 
17084
-            yield
 
17085
-            sys.path.pop(0)
 
17086
-            rmtree(dir)
 
17087
-
 
17088
-        with newdirinpath(TESTFN), EnvironmentVarGuard() as env:
 
17089
-            env['PYTHONPATH'] = TESTFN
 
17090
-            fullmodname = os.path.join(TESTFN, modname)
 
17091
-            sourcefn = fullmodname + os.extsep + "py"
 
17092
-            for importstring, expectedinmsg in testpairs:
 
17093
-                f = open(sourcefn, 'w')
 
17094
-                f.write("import {}\n".format(importstring))
 
17095
-                f.close()
 
17096
-                try:
 
17097
-                    result = run_pydoc(modname)
 
17098
-                finally:
 
17099
-                    forget(modname)
 
17100
-                expected = badimport_pattern % (modname, expectedinmsg)
 
17101
-                self.assertEqual(expected, result)
 
17102
-
 
17103
     def test_input_strip(self):
 
17104
         missing_module = " test.i_am_not_here "
 
17105
         result = run_pydoc(missing_module)
 
17106
@@ -317,6 +278,55 @@
 
17107
                          "<type 'exceptions.Exception'>")
 
17108
 
 
17109
 
 
17110
+class PydocImportTest(unittest.TestCase):
 
17111
+
 
17112
+    def setUp(self):
 
17113
+        self.test_dir = os.mkdir(TESTFN)
 
17114
+        self.addCleanup(rmtree, TESTFN)
 
17115
+
 
17116
+    def test_badimport(self):
 
17117
+        # This tests the fix for issue 5230, where if pydoc found the module
 
17118
+        # but the module had an internal import error pydoc would report no doc
 
17119
+        # found.
 
17120
+        modname = 'testmod_xyzzy'
 
17121
+        testpairs = (
 
17122
+            ('i_am_not_here', 'i_am_not_here'),
 
17123
+            ('test.i_am_not_here_either', 'i_am_not_here_either'),
 
17124
+            ('test.i_am_not_here.neither_am_i', 'i_am_not_here.neither_am_i'),
 
17125
+            ('i_am_not_here.{}'.format(modname),
 
17126
+             'i_am_not_here.{}'.format(modname)),
 
17127
+            ('test.{}'.format(modname), modname),
 
17128
+            )
 
17129
+
 
17130
+        sourcefn = os.path.join(TESTFN, modname) + os.extsep + "py"
 
17131
+        for importstring, expectedinmsg in testpairs:
 
17132
+            with open(sourcefn, 'w') as f:
 
17133
+                f.write("import {}\n".format(importstring))
 
17134
+            result = run_pydoc(modname, PYTHONPATH=TESTFN)
 
17135
+            expected = badimport_pattern % (modname, expectedinmsg)
 
17136
+            self.assertEqual(expected, result)
 
17137
+
 
17138
+    def test_apropos_with_bad_package(self):
 
17139
+        # Issue 7425 - pydoc -k failed when bad package on path
 
17140
+        pkgdir = os.path.join(TESTFN, "syntaxerr")
 
17141
+        os.mkdir(pkgdir)
 
17142
+        badsyntax = os.path.join(pkgdir, "__init__") + os.extsep + "py"
 
17143
+        with open(badsyntax, 'w') as f:
 
17144
+            f.write("invalid python syntax = $1\n")
 
17145
+        result = run_pydoc('nothing', '-k', PYTHONPATH=TESTFN)
 
17146
+        self.assertEqual('', result)
 
17147
+
 
17148
+    def test_apropos_with_unreadable_dir(self):
 
17149
+        # Issue 7367 - pydoc -k failed when unreadable dir on path
 
17150
+        self.unreadable_dir = os.path.join(TESTFN, "unreadable")
 
17151
+        os.mkdir(self.unreadable_dir, 0)
 
17152
+        self.addCleanup(os.rmdir, self.unreadable_dir)
 
17153
+        # Note, on Windows the directory appears to be still
 
17154
+        #   readable so this is not really testing the issue there
 
17155
+        result = run_pydoc('nothing', '-k', PYTHONPATH=TESTFN)
 
17156
+        self.assertEqual('', result)
 
17157
+
 
17158
+
 
17159
 class TestDescriptions(unittest.TestCase):
 
17160
 
 
17161
     def test_module(self):
 
17162
@@ -357,11 +367,32 @@
7037
17163
         self.assertEqual(sorted(pydoc.Helper.keywords),
7038
17164
                          sorted(keyword.kwlist))
7039
17165
 
7056
17182
+
7057
17183
 
7058
17184
 def test_main():
7059
 
     test.test_support.run_unittest(PyDocDocTest,
 
17185
-    test.test_support.run_unittest(PyDocDocTest,
 
17186
-                                   TestDescriptions,
 
17187
-                                   TestHelper)
 
17188
+    try:
 
17189
+        test.test_support.run_unittest(PyDocDocTest,
 
17190
+                                       PydocImportTest,
 
17191
+                                       TestDescriptions,
 
17192
+                                       TestHelper)
 
17193
+    finally:
 
17194
+        reap_children()
 
17195
 
 
17196
 if __name__ == "__main__":
 
17197
     test_main()
7060
17198
diff -r 8527427914a2 Lib/test/test_robotparser.py
7061
17199
--- a/Lib/test/test_robotparser.py
7062
17200
+++ b/Lib/test/test_robotparser.py
7096
17234
 
7097
17235
     def testPythonOrg(self):
7098
17236
         test_support.requires('network')
 
17237
diff -r 8527427914a2 Lib/test/test_shutil.py
 
17238
--- a/Lib/test/test_shutil.py
 
17239
+++ b/Lib/test/test_shutil.py
 
17240
@@ -349,6 +349,8 @@
 
17241
         self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
 
17242
 
 
17243
         tmpdir2 = self.mkdtemp()
 
17244
+        # force shutil to create the directory
 
17245
+        os.rmdir(tmpdir2)
 
17246
         unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
 
17247
                             "source and target should be on same drive")
 
17248
 
 
17249
@@ -464,6 +466,8 @@
 
17250
         self.write_file([tmpdir, 'file2'], 'xxx')
 
17251
 
 
17252
         tmpdir2 = self.mkdtemp()
 
17253
+        # force shutil to create the directory
 
17254
+        os.rmdir(tmpdir2)
 
17255
         base_name = os.path.join(tmpdir2, 'archive')
 
17256
         _make_zipfile(base_name, tmpdir)
 
17257
 
 
17258
diff -r 8527427914a2 Lib/test/test_site.py
 
17259
--- a/Lib/test/test_site.py
 
17260
+++ b/Lib/test/test_site.py
 
17261
@@ -24,7 +24,7 @@
 
17262
 else:
 
17263
     raise unittest.SkipTest("importation of site.py suppressed")
 
17264
 
 
17265
-if not os.path.isdir(site.USER_SITE):
 
17266
+if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE):
 
17267
     # need to add user site directory for tests
 
17268
     os.makedirs(site.USER_SITE)
 
17269
     site.addsitedir(site.USER_SITE)
 
17270
@@ -161,6 +161,8 @@
 
17271
         finally:
 
17272
             pth_file.cleanup()
 
17273
 
 
17274
+    @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 "
 
17275
+                          "user-site (site.ENABLE_USER_SITE)")
 
17276
     def test_s_option(self):
 
17277
         usersite = site.USER_SITE
 
17278
         self.assertIn(usersite, sys.path)
7099
17279
diff -r 8527427914a2 Lib/test/test_smtplib.py
7100
17280
--- a/Lib/test/test_smtplib.py
7101
17281
+++ b/Lib/test/test_smtplib.py
7128
17308
         self.assertEqual(smtp.vrfy(u), expected_unknown)
7129
17309
         smtp.quit()
7130
17310
 
 
17311
diff -r 8527427914a2 Lib/test/test_socket.py
 
17312
--- a/Lib/test/test_socket.py
 
17313
+++ b/Lib/test/test_socket.py
 
17314
@@ -145,11 +145,10 @@
 
17315
 
 
17316
     def clientRun(self, test_func):
 
17317
         self.server_ready.wait()
 
17318
+        self.clientSetUp()
 
17319
         self.client_ready.set()
 
17320
-        self.clientSetUp()
 
17321
-        with test_support.check_py3k_warnings():
 
17322
-            if not callable(test_func):
 
17323
-                raise TypeError("test_func must be a callable function.")
 
17324
+        if not callable(test_func):
 
17325
+            raise TypeError("test_func must be a callable function.")
 
17326
         try:
 
17327
             test_func()
 
17328
         except Exception, strerror:
 
17329
@@ -1380,7 +1379,7 @@
 
17330
             # no alarm can be pending.  Safe to restore old handler.
 
17331
             signal.signal(signal.SIGALRM, old_alarm)
 
17332
 
 
17333
-class UDPTimeoutTest(SocketTCPTest):
 
17334
+class UDPTimeoutTest(SocketUDPTest):
 
17335
 
 
17336
     def testUDPTimeout(self):
 
17337
         def raise_timeout(*args, **kwargs):
7131
17338
diff -r 8527427914a2 Lib/test/test_socketserver.py
7132
17339
--- a/Lib/test/test_socketserver.py
7133
17340
+++ b/Lib/test/test_socketserver.py
7140
17347
         self.port_seed = 0
7141
17348
         self.test_files = []
7142
17349
 
7143
 
@@ -281,4 +281,3 @@
 
17350
@@ -123,7 +123,6 @@
 
17351
         self.assertEqual(server.server_address, server.socket.getsockname())
 
17352
         return server
 
17353
 
 
17354
-    @unittest.skipUnless(threading, 'Threading required for this test.')
 
17355
     @reap_threads
 
17356
     def run_server(self, svrcls, hdlrbase, testfunc):
 
17357
         server = self.make_server(self.pickaddr(svrcls.address_family),
 
17358
@@ -281,4 +280,3 @@
7144
17359
 
7145
17360
 if __name__ == "__main__":
7146
17361
     test_main()
7147
17362
-    signal_alarm(3)  # Shutdown shouldn't take more than 3 seconds.
 
17363
diff -r 8527427914a2 Lib/test/test_ssl.py
 
17364
--- a/Lib/test/test_ssl.py
 
17365
+++ b/Lib/test/test_ssl.py
 
17366
@@ -110,6 +110,23 @@
 
17367
         p = ssl._ssl._test_decode_cert(CERTFILE, False)
 
17368
         if test_support.verbose:
 
17369
             sys.stdout.write("\n" + pprint.pformat(p) + "\n")
 
17370
+        self.assertEqual(p['subject'],
 
17371
+                         ((('countryName', u'US'),),
 
17372
+                          (('stateOrProvinceName', u'Delaware'),),
 
17373
+                          (('localityName', u'Wilmington'),),
 
17374
+                          (('organizationName', u'Python Software Foundation'),),
 
17375
+                          (('organizationalUnitName', u'SSL'),),
 
17376
+                          (('commonName', u'somemachine.python.org'),)),
 
17377
+                        )
 
17378
+        # Issue #13034: the subjectAltName in some certificates
 
17379
+        # (notably projects.developer.nokia.com:443) wasn't parsed
 
17380
+        p = ssl._ssl._test_decode_cert(NOKIACERT)
 
17381
+        if test_support.verbose:
 
17382
+            sys.stdout.write("\n" + pprint.pformat(p) + "\n")
 
17383
+        self.assertEqual(p['subjectAltName'],
 
17384
+                         (('DNS', 'projects.developer.nokia.com'),
 
17385
+                          ('DNS', 'projects.forum.nokia.com'))
 
17386
+                        )
 
17387
 
 
17388
     def test_DER_to_PEM(self):
 
17389
         with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
 
17390
@@ -966,6 +983,8 @@
 
17391
             """Connecting to an SSLv2 server with various client options"""
 
17392
             if test_support.verbose:
 
17393
                 sys.stdout.write("\n")
 
17394
+            if not hasattr(ssl, 'PROTOCOL_SSLv2'):
 
17395
+                self.skipTest("PROTOCOL_SSLv2 needed")
 
17396
             try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True)
 
17397
             try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL)
 
17398
             try_protocol_combo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED)
 
17399
@@ -978,14 +997,6 @@
 
17400
             """Connecting to an SSLv23 server with various client options"""
 
17401
             if test_support.verbose:
 
17402
                 sys.stdout.write("\n")
 
17403
-            try:
 
17404
-                try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True)
 
17405
-            except (ssl.SSLError, socket.error), x:
 
17406
-                # this fails on some older versions of OpenSSL (0.9.7l, for instance)
 
17407
-                if test_support.verbose:
 
17408
-                    sys.stdout.write(
 
17409
-                        " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n"
 
17410
-                        % str(x))
 
17411
             try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True)
 
17412
             try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True)
 
17413
             try_protocol_combo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True)
 
17414
@@ -1008,7 +1019,6 @@
 
17415
             try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED)
 
17416
             if hasattr(ssl, 'PROTOCOL_SSLv2'):
 
17417
                 try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False)
 
17418
-            try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False)
 
17419
             try_protocol_combo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False)
 
17420
 
 
17421
         @skip_if_broken_ubuntu_ssl
 
17422
@@ -1022,7 +1032,6 @@
 
17423
             if hasattr(ssl, 'PROTOCOL_SSLv2'):
 
17424
                 try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False)
 
17425
             try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False)
 
17426
-            try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False)
 
17427
 
 
17428
         def test_starttls(self):
 
17429
             """Switching from clear text to encrypted and back again."""
 
17430
@@ -1329,15 +1338,18 @@
 
17431
 
 
17432
 
 
17433
 def test_main(verbose=False):
 
17434
-    global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT
 
17435
+    global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT
 
17436
     CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
 
17437
                             "keycert.pem")
 
17438
     SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
 
17439
         os.path.dirname(__file__) or os.curdir,
 
17440
         "https_svn_python_org_root.pem")
 
17441
+    NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir,
 
17442
+                             "nokia.pem")
 
17443
 
 
17444
     if (not os.path.exists(CERTFILE) or
 
17445
-        not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)):
 
17446
+        not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or
 
17447
+        not os.path.exists(NOKIACERT)):
 
17448
         raise test_support.TestFailed("Can't read certificate files!")
 
17449
 
 
17450
     tests = [BasicTests, BasicSocketTests]
7148
17451
diff -r 8527427914a2 Lib/test/test_subprocess.py
7149
17452
--- a/Lib/test/test_subprocess.py
7150
17453
+++ b/Lib/test/test_subprocess.py
7255
17558
     def test_wait_when_sigchild_ignored(self):
7256
17559
         # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
7257
17560
         sigchild_ignore = test_support.findfile("sigchild_ignore.py",
 
17561
@@ -859,6 +945,87 @@
 
17562
         self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
 
17563
                          " non-zero with this error:\n%s" % stderr)
 
17564
 
 
17565
+    def test_zombie_fast_process_del(self):
 
17566
+        # Issue #12650: on Unix, if Popen.__del__() was called before the
 
17567
+        # process exited, it wouldn't be added to subprocess._active, and would
 
17568
+        # remain a zombie.
 
17569
+        # spawn a Popen, and delete its reference before it exits
 
17570
+        p = subprocess.Popen([sys.executable, "-c",
 
17571
+                              'import sys, time;'
 
17572
+                              'time.sleep(0.2)'],
 
17573
+                             stdout=subprocess.PIPE,
 
17574
+                             stderr=subprocess.PIPE)
 
17575
+        self.addCleanup(p.stdout.close)
 
17576
+        self.addCleanup(p.stderr.close)
 
17577
+        ident = id(p)
 
17578
+        pid = p.pid
 
17579
+        del p
 
17580
+        # check that p is in the active processes list
 
17581
+        self.assertIn(ident, [id(o) for o in subprocess._active])
 
17582
+
 
17583
+    def test_leak_fast_process_del_killed(self):
 
17584
+        # Issue #12650: on Unix, if Popen.__del__() was called before the
 
17585
+        # process exited, and the process got killed by a signal, it would never
 
17586
+        # be removed from subprocess._active, which triggered a FD and memory
 
17587
+        # leak.
 
17588
+        # spawn a Popen, delete its reference and kill it
 
17589
+        p = subprocess.Popen([sys.executable, "-c",
 
17590
+                              'import time;'
 
17591
+                              'time.sleep(3)'],
 
17592
+                             stdout=subprocess.PIPE,
 
17593
+                             stderr=subprocess.PIPE)
 
17594
+        self.addCleanup(p.stdout.close)
 
17595
+        self.addCleanup(p.stderr.close)
 
17596
+        ident = id(p)
 
17597
+        pid = p.pid
 
17598
+        del p
 
17599
+        os.kill(pid, signal.SIGKILL)
 
17600
+        # check that p is in the active processes list
 
17601
+        self.assertIn(ident, [id(o) for o in subprocess._active])
 
17602
+
 
17603
+        # let some time for the process to exit, and create a new Popen: this
 
17604
+        # should trigger the wait() of p
 
17605
+        time.sleep(0.2)
 
17606
+        with self.assertRaises(EnvironmentError) as c:
 
17607
+            with subprocess.Popen(['nonexisting_i_hope'],
 
17608
+                                  stdout=subprocess.PIPE,
 
17609
+                                  stderr=subprocess.PIPE) as proc:
 
17610
+                pass
 
17611
+        # p should have been wait()ed on, and removed from the _active list
 
17612
+        self.assertRaises(OSError, os.waitpid, pid, 0)
 
17613
+        self.assertNotIn(ident, [id(o) for o in subprocess._active])
 
17614
+
 
17615
+    def test_pipe_cloexec(self):
 
17616
+        # Issue 12786: check that the communication pipes' FDs are set CLOEXEC,
 
17617
+        # and are not inherited by another child process.
 
17618
+        p1 = subprocess.Popen([sys.executable, "-c",
 
17619
+                               'import os;'
 
17620
+                               'os.read(0, 1)'
 
17621
+                              ],
 
17622
+                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 
17623
+                              stderr=subprocess.PIPE)
 
17624
+
 
17625
+        p2 = subprocess.Popen([sys.executable, "-c", """if True:
 
17626
+                               import os, errno, sys
 
17627
+                               for fd in %r:
 
17628
+                                   try:
 
17629
+                                       os.close(fd)
 
17630
+                                   except OSError as e:
 
17631
+                                       if e.errno != errno.EBADF:
 
17632
+                                           raise
 
17633
+                                   else:
 
17634
+                                       sys.exit(1)
 
17635
+                               sys.exit(0)
 
17636
+                               """ % [f.fileno() for f in (p1.stdin, p1.stdout,
 
17637
+                                                           p1.stderr)]
 
17638
+                              ],
 
17639
+                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
 
17640
+                              stderr=subprocess.PIPE, close_fds=False)
 
17641
+        p1.communicate('foo')
 
17642
+        _, stderr = p2.communicate()
 
17643
+
 
17644
+        self.assertEqual(p2.returncode, 0, "Unexpected error: " + repr(stderr))
 
17645
+
 
17646
 
 
17647
 @unittest.skipUnless(mswindows, "Windows specific tests")
 
17648
 class Win32ProcessTestCase(BaseTestCase):
 
17649
@@ -994,7 +1161,6 @@
 
17650
                          subprocess._eintr_retry_call(fake_os_func, 666))
 
17651
         self.assertEqual([(256, 999), (666,), (666,)], record_calls)
 
17652
 
 
17653
-
 
17654
 @unittest.skipUnless(mswindows, "mswindows only")
 
17655
 class CommandsWithSpaces (BaseTestCase):
 
17656
 
7258
17657
diff -r 8527427914a2 Lib/test/test_support.py
7259
17658
--- a/Lib/test/test_support.py
7260
17659
+++ b/Lib/test/test_support.py
7276
17675
 def captured_stdin():
7277
17676
     return captured_output("stdin")
7278
17677
 
 
17678
diff -r 8527427914a2 Lib/test/test_sys_settrace.py
 
17679
--- a/Lib/test/test_sys_settrace.py
 
17680
+++ b/Lib/test/test_sys_settrace.py
 
17681
@@ -282,11 +282,11 @@
 
17682
         self.compare_events(func.func_code.co_firstlineno,
 
17683
                             tracer.events, func.events)
 
17684
 
 
17685
-    def set_and_retrieve_none(self):
 
17686
+    def test_set_and_retrieve_none(self):
 
17687
         sys.settrace(None)
 
17688
         assert sys.gettrace() is None
 
17689
 
 
17690
-    def set_and_retrieve_func(self):
 
17691
+    def test_set_and_retrieve_func(self):
 
17692
         def fn(*args):
 
17693
             pass
 
17694
 
 
17695
diff -r 8527427914a2 Lib/test/test_sysconfig.py
 
17696
--- a/Lib/test/test_sysconfig.py
 
17697
+++ b/Lib/test/test_sysconfig.py
 
17698
@@ -1,9 +1,5 @@
 
17699
-"""Tests for 'site'.
 
17700
+"""Tests for sysconfig."""
 
17701
 
 
17702
-Tests assume the initial paths in sys.path once the interpreter has begun
 
17703
-executing have not been removed.
 
17704
-
 
17705
-"""
 
17706
 import unittest
 
17707
 import sys
 
17708
 import os
 
17709
@@ -255,14 +251,21 @@
 
17710
             unlink(link)
 
17711
 
 
17712
     def test_user_similar(self):
 
17713
-        # Issue 8759 : make sure the posix scheme for the users
 
17714
+        # Issue #8759: make sure the posix scheme for the users
 
17715
         # is similar to the global posix_prefix one
 
17716
         base = get_config_var('base')
 
17717
         user = get_config_var('userbase')
 
17718
+        # the global scheme mirrors the distinction between prefix and
 
17719
+        # exec-prefix but not the user scheme, so we have to adapt the paths
 
17720
+        # before comparing (issue #9100)
 
17721
+        adapt = sys.prefix != sys.exec_prefix
 
17722
         for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
 
17723
             global_path = get_path(name, 'posix_prefix')
 
17724
+            if adapt:
 
17725
+                global_path = global_path.replace(sys.exec_prefix, sys.prefix)
 
17726
+                base = base.replace(sys.exec_prefix, sys.prefix)
 
17727
             user_path = get_path(name, 'posix_user')
 
17728
-            self.assertEqual(user_path, global_path.replace(base, user))
 
17729
+            self.assertEqual(user_path, global_path.replace(base, user, 1))
 
17730
 
 
17731
     @unittest.skipUnless(sys.platform == "darwin", "test only relevant on MacOSX")
 
17732
     def test_platform_in_subprocess(self):
 
17733
diff -r 8527427914a2 Lib/test/test_telnetlib.py
 
17734
--- a/Lib/test/test_telnetlib.py
 
17735
+++ b/Lib/test/test_telnetlib.py
 
17736
@@ -15,7 +15,6 @@
 
17737
         1) set evt to true to let the parent know we are ready
 
17738
         2) [optional] if is not False, write the list of data from dataq.get()
 
17739
            to the socket.
 
17740
-        3) set evt to true to let the parent know we're done
 
17741
     """
 
17742
     serv.listen(5)
 
17743
     evt.set()
 
17744
@@ -34,29 +33,25 @@
 
17745
                     data += item
 
17746
                 written = conn.send(data)
 
17747
                 data = data[written:]
 
17748
+        conn.close()
 
17749
     except socket.timeout:
 
17750
         pass
 
17751
-    else:
 
17752
-        conn.close()
 
17753
     finally:
 
17754
         serv.close()
 
17755
-        evt.set()
 
17756
 
 
17757
 class GeneralTests(TestCase):
 
17758
 
 
17759
     def setUp(self):
 
17760
         self.evt = threading.Event()
 
17761
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
17762
-        self.sock.settimeout(3)
 
17763
+        self.sock.settimeout(60)  # Safety net. Look issue 11812
 
17764
         self.port = test_support.bind_port(self.sock)
 
17765
         self.thread = threading.Thread(target=server, args=(self.evt,self.sock))
 
17766
+        self.thread.setDaemon(True)
 
17767
         self.thread.start()
 
17768
         self.evt.wait()
 
17769
-        self.evt.clear()
 
17770
-        time.sleep(.1)
 
17771
 
 
17772
     def tearDown(self):
 
17773
-        self.evt.wait()
 
17774
         self.thread.join()
 
17775
 
 
17776
     def testBasic(self):
 
17777
@@ -68,7 +63,7 @@
 
17778
         self.assertTrue(socket.getdefaulttimeout() is None)
 
17779
         socket.setdefaulttimeout(30)
 
17780
         try:
 
17781
-            telnet = telnetlib.Telnet("localhost", self.port)
 
17782
+            telnet = telnetlib.Telnet(HOST, self.port)
 
17783
         finally:
 
17784
             socket.setdefaulttimeout(None)
 
17785
         self.assertEqual(telnet.sock.gettimeout(), 30)
 
17786
@@ -86,13 +81,13 @@
 
17787
         telnet.sock.close()
 
17788
 
 
17789
     def testTimeoutValue(self):
 
17790
-        telnet = telnetlib.Telnet("localhost", self.port, timeout=30)
 
17791
+        telnet = telnetlib.Telnet(HOST, self.port, timeout=30)
 
17792
         self.assertEqual(telnet.sock.gettimeout(), 30)
 
17793
         telnet.sock.close()
 
17794
 
 
17795
     def testTimeoutOpen(self):
 
17796
         telnet = telnetlib.Telnet()
 
17797
-        telnet.open("localhost", self.port, timeout=30)
 
17798
+        telnet.open(HOST, self.port, timeout=30)
 
17799
         self.assertEqual(telnet.sock.gettimeout(), 30)
 
17800
         telnet.sock.close()
 
17801
 
 
17802
@@ -105,11 +100,8 @@
 
17803
     self.thread = threading.Thread(target=server, args=(self.evt,self.sock, self.dataq))
 
17804
     self.thread.start()
 
17805
     self.evt.wait()
 
17806
-    self.evt.clear()
 
17807
-    time.sleep(.1)
 
17808
 
 
17809
 def _read_tearDown(self):
 
17810
-    self.evt.wait()
 
17811
     self.thread.join()
 
17812
 
 
17813
 class ReadTests(TestCase):
 
17814
diff -r 8527427914a2 Lib/test/test_tempfile.py
 
17815
--- a/Lib/test/test_tempfile.py
 
17816
+++ b/Lib/test/test_tempfile.py
 
17817
@@ -1,6 +1,7 @@
 
17818
 # tempfile.py unit tests.
 
17819
 import tempfile
 
17820
 import os
 
17821
+import signal
 
17822
 import sys
 
17823
 import re
 
17824
 import warnings
 
17825
@@ -126,6 +127,37 @@
 
17826
         except:
 
17827
             self.failOnException("iteration")
 
17828
 
 
17829
+    @unittest.skipUnless(hasattr(os, 'fork'),
 
17830
+        "os.fork is required for this test")
 
17831
+    def test_process_awareness(self):
 
17832
+        # ensure that the random source differs between
 
17833
+        # child and parent.
 
17834
+        read_fd, write_fd = os.pipe()
 
17835
+        pid = None
 
17836
+        try:
 
17837
+            pid = os.fork()
 
17838
+            if not pid:
 
17839
+                os.close(read_fd)
 
17840
+                os.write(write_fd, next(self.r).encode("ascii"))
 
17841
+                os.close(write_fd)
 
17842
+                # bypass the normal exit handlers- leave those to
 
17843
+                # the parent.
 
17844
+                os._exit(0)
 
17845
+            parent_value = next(self.r)
 
17846
+            child_value = os.read(read_fd, len(parent_value)).decode("ascii")
 
17847
+        finally:
 
17848
+            if pid:
 
17849
+                # best effort to ensure the process can't bleed out
 
17850
+                # via any bugs above
 
17851
+                try:
 
17852
+                    os.kill(pid, signal.SIGKILL)
 
17853
+                except EnvironmentError:
 
17854
+                    pass
 
17855
+            os.close(read_fd)
 
17856
+            os.close(write_fd)
 
17857
+        self.assertNotEqual(child_value, parent_value)
 
17858
+
 
17859
+
 
17860
 test_classes.append(test__RandomNameSequence)
 
17861
 
 
17862
 
7279
17863
diff -r 8527427914a2 Lib/test/test_threading.py
7280
17864
--- a/Lib/test/test_threading.py
7281
17865
+++ b/Lib/test/test_threading.py
7434
18018
diff -r 8527427914a2 Lib/test/test_unicode.py
7435
18019
--- a/Lib/test/test_unicode.py
7436
18020
+++ b/Lib/test/test_unicode.py
7437
 
@@ -269,6 +269,25 @@
 
18021
@@ -5,9 +5,16 @@
 
18022
 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
 
18023
 
 
18024
 """#"
 
18025
-import sys, struct, codecs
 
18026
+import sys
 
18027
+import struct
 
18028
+import codecs
 
18029
+import unittest
 
18030
 from test import test_support, string_tests
 
18031
 
 
18032
+# decorator to skip tests on narrow builds
 
18033
+requires_wide_build = unittest.skipIf(sys.maxunicode == 65535,
 
18034
+                                      'requires wide build')
 
18035
+
 
18036
 # Error handling (bad decoder return)
 
18037
 def search_function(encoding):
 
18038
     def decode1(input, errors="strict"):
 
18039
@@ -269,30 +276,106 @@
7438
18040
         # Surrogates on both sides, no fixup required
7439
18041
         self.assertTrue(u'\ud800\udc02' < u'\ud84d\udc56')
7440
18042
 
7460
18062
     def test_islower(self):
7461
18063
         string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
7462
18064
         self.checkequalnofix(False, u'\u1FFc', 'islower')
 
18065
 
 
18066
+    @requires_wide_build
 
18067
+    def test_islower_non_bmp(self):
 
18068
+        # non-BMP, uppercase
 
18069
+        self.assertFalse(u'\U00010401'.islower())
 
18070
+        self.assertFalse(u'\U00010427'.islower())
 
18071
+        # non-BMP, lowercase
 
18072
+        self.assertTrue(u'\U00010429'.islower())
 
18073
+        self.assertTrue(u'\U0001044E'.islower())
 
18074
+        # non-BMP, non-cased
 
18075
+        self.assertFalse(u'\U0001F40D'.islower())
 
18076
+        self.assertFalse(u'\U0001F46F'.islower())
 
18077
+
 
18078
     def test_isupper(self):
 
18079
         string_tests.MixinStrUnicodeUserStringTest.test_isupper(self)
 
18080
         if not sys.platform.startswith('java'):
 
18081
             self.checkequalnofix(False, u'\u1FFc', 'isupper')
 
18082
 
 
18083
+    @requires_wide_build
 
18084
+    def test_isupper_non_bmp(self):
 
18085
+        # non-BMP, uppercase
 
18086
+        self.assertTrue(u'\U00010401'.isupper())
 
18087
+        self.assertTrue(u'\U00010427'.isupper())
 
18088
+        # non-BMP, lowercase
 
18089
+        self.assertFalse(u'\U00010429'.isupper())
 
18090
+        self.assertFalse(u'\U0001044E'.isupper())
 
18091
+        # non-BMP, non-cased
 
18092
+        self.assertFalse(u'\U0001F40D'.isupper())
 
18093
+        self.assertFalse(u'\U0001F46F'.isupper())
 
18094
+
 
18095
     def test_istitle(self):
 
18096
-        string_tests.MixinStrUnicodeUserStringTest.test_title(self)
 
18097
+        string_tests.MixinStrUnicodeUserStringTest.test_istitle(self)
 
18098
         self.checkequalnofix(True, u'\u1FFc', 'istitle')
 
18099
         self.checkequalnofix(True, u'Greek \u1FFcitlecases ...', 'istitle')
 
18100
 
 
18101
+    @requires_wide_build
 
18102
+    def test_istitle_non_bmp(self):
 
18103
+        # non-BMP, uppercase + lowercase
 
18104
+        self.assertTrue(u'\U00010401\U00010429'.istitle())
 
18105
+        self.assertTrue(u'\U00010427\U0001044E'.istitle())
 
18106
+        # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
 
18107
+        for ch in [u'\U00010429', u'\U0001044E', u'\U0001F40D', u'\U0001F46F']:
 
18108
+            self.assertFalse(ch.istitle(), '{!r} is not title'.format(ch))
 
18109
+
 
18110
     def test_isspace(self):
 
18111
         string_tests.MixinStrUnicodeUserStringTest.test_isspace(self)
 
18112
         self.checkequalnofix(True, u'\u2000', 'isspace')
 
18113
         self.checkequalnofix(True, u'\u200a', 'isspace')
 
18114
         self.checkequalnofix(False, u'\u2014', 'isspace')
 
18115
 
 
18116
+    @requires_wide_build
 
18117
+    def test_isspace_non_bmp(self):
 
18118
+        # apparently there are no non-BMP spaces chars in Unicode 6
 
18119
+        for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
 
18120
+                   u'\U0001F40D', u'\U0001F46F']:
 
18121
+            self.assertFalse(ch.isspace(), '{!r} is not space.'.format(ch))
 
18122
+
 
18123
+    @requires_wide_build
 
18124
+    def test_isalnum_non_bmp(self):
 
18125
+        for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
 
18126
+                   u'\U0001D7F6', u'\U000104A0', u'\U000104A0', u'\U0001F107']:
 
18127
+            self.assertTrue(ch.isalnum(), '{!r} is alnum.'.format(ch))
 
18128
+
 
18129
     def test_isalpha(self):
 
18130
         string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self)
 
18131
         self.checkequalnofix(True, u'\u1FFc', 'isalpha')
 
18132
 
 
18133
+    @requires_wide_build
 
18134
+    def test_isalpha_non_bmp(self):
 
18135
+        # non-BMP, cased
 
18136
+        self.assertTrue(u'\U00010401'.isalpha())
 
18137
+        self.assertTrue(u'\U00010427'.isalpha())
 
18138
+        self.assertTrue(u'\U00010429'.isalpha())
 
18139
+        self.assertTrue(u'\U0001044E'.isalpha())
 
18140
+        # non-BMP, non-cased
 
18141
+        self.assertFalse(u'\U0001F40D'.isalpha())
 
18142
+        self.assertFalse(u'\U0001F46F'.isalpha())
 
18143
+
 
18144
     def test_isdecimal(self):
 
18145
         self.checkequalnofix(False, u'', 'isdecimal')
 
18146
         self.checkequalnofix(False, u'a', 'isdecimal')
 
18147
@@ -305,12 +388,28 @@
 
18148
 
 
18149
         self.checkraises(TypeError, 'abc', 'isdecimal', 42)
 
18150
 
 
18151
+    @requires_wide_build
 
18152
+    def test_isdecimal_non_bmp(self):
 
18153
+        for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
 
18154
+                   u'\U0001F40D', u'\U0001F46F', u'\U00011065', u'\U0001F107']:
 
18155
+            self.assertFalse(ch.isdecimal(), '{!r} is not decimal.'.format(ch))
 
18156
+        for ch in [u'\U0001D7F6', u'\U000104A0', u'\U000104A0']:
 
18157
+            self.assertTrue(ch.isdecimal(), '{!r} is decimal.'.format(ch))
 
18158
+
 
18159
     def test_isdigit(self):
 
18160
         string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self)
 
18161
         self.checkequalnofix(True, u'\u2460', 'isdigit')
 
18162
         self.checkequalnofix(False, u'\xbc', 'isdigit')
 
18163
         self.checkequalnofix(True, u'\u0660', 'isdigit')
 
18164
 
 
18165
+    @requires_wide_build
 
18166
+    def test_isdigit_non_bmp(self):
 
18167
+        for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
 
18168
+                   u'\U0001F40D', u'\U0001F46F', u'\U00011065']:
 
18169
+            self.assertFalse(ch.isdigit(), '{!r} is not a digit.'.format(ch))
 
18170
+        for ch in [u'\U0001D7F6', u'\U000104A0', u'\U000104A0', u'\U0001F107']:
 
18171
+            self.assertTrue(ch.isdigit(), '{!r} is a digit.'.format(ch))
 
18172
+
 
18173
     def test_isnumeric(self):
 
18174
         self.checkequalnofix(False, u'', 'isnumeric')
 
18175
         self.checkequalnofix(False, u'a', 'isnumeric')
 
18176
@@ -323,6 +422,109 @@
 
18177
 
 
18178
         self.assertRaises(TypeError, u"abc".isnumeric, 42)
 
18179
 
 
18180
+    @requires_wide_build
 
18181
+    def test_isnumeric_non_bmp(self):
 
18182
+        for ch in [u'\U00010401', u'\U00010427', u'\U00010429', u'\U0001044E',
 
18183
+                   u'\U0001F40D', u'\U0001F46F']:
 
18184
+            self.assertFalse(ch.isnumeric(), '{!r} is not numeric.'.format(ch))
 
18185
+        for ch in [u'\U00010107', u'\U0001D7F6', u'\U00023b1b',
 
18186
+                   u'\U000104A0', u'\U0001F107']:
 
18187
+            self.assertTrue(ch.isnumeric(), '{!r} is numeric.'.format(ch))
 
18188
+
 
18189
+    @requires_wide_build
 
18190
+    def test_surrogates(self):
 
18191
+        # this test actually passes on narrow too, but it's just by accident.
 
18192
+        # Surrogates are seen as non-cased chars, so u'X\uD800X' is as
 
18193
+        # uppercase as 'X X'
 
18194
+        for s in (u'a\uD800b\uDFFF', u'a\uDFFFb\uD800',
 
18195
+                  u'a\uD800b\uDFFFa', u'a\uDFFFb\uD800a'):
 
18196
+            self.assertTrue(s.islower())
 
18197
+            self.assertFalse(s.isupper())
 
18198
+            self.assertFalse(s.istitle())
 
18199
+        for s in (u'A\uD800B\uDFFF', u'A\uDFFFB\uD800',
 
18200
+                  u'A\uD800B\uDFFFA', u'A\uDFFFB\uD800A'):
 
18201
+            self.assertFalse(s.islower())
 
18202
+            self.assertTrue(s.isupper())
 
18203
+            self.assertTrue(s.istitle())
 
18204
+
 
18205
+        for meth_name in ('islower', 'isupper', 'istitle'):
 
18206
+            meth = getattr(unicode, meth_name)
 
18207
+            for s in (u'\uD800', u'\uDFFF', u'\uD800\uD800', u'\uDFFF\uDFFF'):
 
18208
+                self.assertFalse(meth(s), '%r.%s() is False' % (s, meth_name))
 
18209
+
 
18210
+        for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
 
18211
+                          'isdecimal', 'isnumeric'):
 
18212
+            meth = getattr(unicode, meth_name)
 
18213
+            for s in (u'\uD800', u'\uDFFF', u'\uD800\uD800', u'\uDFFF\uDFFF',
 
18214
+                      u'a\uD800b\uDFFF', u'a\uDFFFb\uD800',
 
18215
+                      u'a\uD800b\uDFFFa', u'a\uDFFFb\uD800a'):
 
18216
+                self.assertFalse(meth(s), '%r.%s() is False' % (s, meth_name))
 
18217
+
 
18218
+
 
18219
+    @requires_wide_build
 
18220
+    def test_lower(self):
 
18221
+        string_tests.CommonTest.test_lower(self)
 
18222
+        self.assertEqual(u'\U00010427'.lower(), u'\U0001044F')
 
18223
+        self.assertEqual(u'\U00010427\U00010427'.lower(),
 
18224
+                         u'\U0001044F\U0001044F')
 
18225
+        self.assertEqual(u'\U00010427\U0001044F'.lower(),
 
18226
+                         u'\U0001044F\U0001044F')
 
18227
+        self.assertEqual(u'X\U00010427x\U0001044F'.lower(),
 
18228
+                         u'x\U0001044Fx\U0001044F')
 
18229
+
 
18230
+    @requires_wide_build
 
18231
+    def test_upper(self):
 
18232
+        string_tests.CommonTest.test_upper(self)
 
18233
+        self.assertEqual(u'\U0001044F'.upper(), u'\U00010427')
 
18234
+        self.assertEqual(u'\U0001044F\U0001044F'.upper(),
 
18235
+                         u'\U00010427\U00010427')
 
18236
+        self.assertEqual(u'\U00010427\U0001044F'.upper(),
 
18237
+                         u'\U00010427\U00010427')
 
18238
+        self.assertEqual(u'X\U00010427x\U0001044F'.upper(),
 
18239
+                         u'X\U00010427X\U00010427')
 
18240
+
 
18241
+    @requires_wide_build
 
18242
+    def test_capitalize(self):
 
18243
+        string_tests.CommonTest.test_capitalize(self)
 
18244
+        self.assertEqual(u'\U0001044F'.capitalize(), u'\U00010427')
 
18245
+        self.assertEqual(u'\U0001044F\U0001044F'.capitalize(),
 
18246
+                         u'\U00010427\U0001044F')
 
18247
+        self.assertEqual(u'\U00010427\U0001044F'.capitalize(),
 
18248
+                         u'\U00010427\U0001044F')
 
18249
+        self.assertEqual(u'\U0001044F\U00010427'.capitalize(),
 
18250
+                         u'\U00010427\U0001044F')
 
18251
+        self.assertEqual(u'X\U00010427x\U0001044F'.capitalize(),
 
18252
+                         u'X\U0001044Fx\U0001044F')
 
18253
+
 
18254
+    @requires_wide_build
 
18255
+    def test_title(self):
 
18256
+        string_tests.MixinStrUnicodeUserStringTest.test_title(self)
 
18257
+        self.assertEqual(u'\U0001044F'.title(), u'\U00010427')
 
18258
+        self.assertEqual(u'\U0001044F\U0001044F'.title(),
 
18259
+                         u'\U00010427\U0001044F')
 
18260
+        self.assertEqual(u'\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
 
18261
+                         u'\U00010427\U0001044F \U00010427\U0001044F')
 
18262
+        self.assertEqual(u'\U00010427\U0001044F \U00010427\U0001044F'.title(),
 
18263
+                         u'\U00010427\U0001044F \U00010427\U0001044F')
 
18264
+        self.assertEqual(u'\U0001044F\U00010427 \U0001044F\U00010427'.title(),
 
18265
+                         u'\U00010427\U0001044F \U00010427\U0001044F')
 
18266
+        self.assertEqual(u'X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
 
18267
+                         u'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
 
18268
+
 
18269
+    @requires_wide_build
 
18270
+    def test_swapcase(self):
 
18271
+        string_tests.CommonTest.test_swapcase(self)
 
18272
+        self.assertEqual(u'\U0001044F'.swapcase(), u'\U00010427')
 
18273
+        self.assertEqual(u'\U00010427'.swapcase(), u'\U0001044F')
 
18274
+        self.assertEqual(u'\U0001044F\U0001044F'.swapcase(),
 
18275
+                         u'\U00010427\U00010427')
 
18276
+        self.assertEqual(u'\U00010427\U0001044F'.swapcase(),
 
18277
+                         u'\U0001044F\U00010427')
 
18278
+        self.assertEqual(u'\U0001044F\U00010427'.swapcase(),
 
18279
+                         u'\U00010427\U0001044F')
 
18280
+        self.assertEqual(u'X\U00010427x\U0001044F'.swapcase(),
 
18281
+                         u'x\U0001044FX\U00010427')
 
18282
+
 
18283
     def test_contains(self):
 
18284
         # Testing Unicode contains method
 
18285
         self.assertIn('a', u'abdb')
 
18286
@@ -569,10 +771,18 @@
 
18287
         for (x, y) in utfTests:
 
18288
             self.assertEqual(x.encode('utf-7'), y)
 
18289
 
 
18290
-        # Unpaired surrogates not supported
 
18291
-        self.assertRaises(UnicodeError, unicode, '+3ADYAA-', 'utf-7')
 
18292
+        # Unpaired surrogates are passed through
 
18293
+        self.assertEqual(u'\uD801'.encode('utf-7'), '+2AE-')
 
18294
+        self.assertEqual(u'\uD801x'.encode('utf-7'), '+2AE-x')
 
18295
+        self.assertEqual(u'\uDC01'.encode('utf-7'), '+3AE-')
 
18296
+        self.assertEqual(u'\uDC01x'.encode('utf-7'), '+3AE-x')
 
18297
+        self.assertEqual('+2AE-'.decode('utf-7'), u'\uD801')
 
18298
+        self.assertEqual('+2AE-x'.decode('utf-7'), u'\uD801x')
 
18299
+        self.assertEqual('+3AE-'.decode('utf-7'), u'\uDC01')
 
18300
+        self.assertEqual('+3AE-x'.decode('utf-7'), u'\uDC01x')
 
18301
 
 
18302
-        self.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u'\ufffd\ufffd')
 
18303
+        self.assertEqual(u'\uD801\U000abcde'.encode('utf-7'), '+2AHab9ze-')
 
18304
+        self.assertEqual('+2AHab9ze-'.decode('utf-7'), u'\uD801\U000abcde')
 
18305
 
 
18306
         # Direct encoded characters
 
18307
         set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
 
18308
@@ -1396,6 +1606,31 @@
 
18309
         self.assertEqual("%s" % u, u'__unicode__ overridden')
 
18310
         self.assertEqual("{}".format(u), '__unicode__ overridden')
 
18311
 
 
18312
+    def test_encode_decimal(self):
 
18313
+        from _testcapi import unicode_encodedecimal
 
18314
+        self.assertEqual(unicode_encodedecimal(u'123'),
 
18315
+                         b'123')
 
18316
+        self.assertEqual(unicode_encodedecimal(u'\u0663.\u0661\u0664'),
 
18317
+                         b'3.14')
 
18318
+        self.assertEqual(unicode_encodedecimal(u"\N{EM SPACE}3.14\N{EN SPACE}"),
 
18319
+                         b' 3.14 ')
 
18320
+        self.assertRaises(UnicodeEncodeError,
 
18321
+                          unicode_encodedecimal, u"123\u20ac", "strict")
 
18322
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac", "replace"),
 
18323
+                         b'123?')
 
18324
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac", "ignore"),
 
18325
+                         b'123')
 
18326
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac", "xmlcharrefreplace"),
 
18327
+                         b'123&#8364;')
 
18328
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac", "backslashreplace"),
 
18329
+                         b'123\\u20ac')
 
18330
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac\N{EM SPACE}", "replace"),
 
18331
+                         b'123? ')
 
18332
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac\u20ac", "replace"),
 
18333
+                         b'123??')
 
18334
+        self.assertEqual(unicode_encodedecimal(u"123\u20ac\u0660", "replace"),
 
18335
+                         b'123?0')
 
18336
+
 
18337
 
 
18338
 def test_main():
 
18339
     test_support.run_unittest(__name__)
7463
18340
diff -r 8527427914a2 Lib/test/test_urllib.py
7464
18341
--- a/Lib/test/test_urllib.py
7465
18342
+++ b/Lib/test/test_urllib.py
7466
 
@@ -114,6 +114,9 @@
 
18343
@@ -17,6 +17,36 @@
 
18344
         hex_repr = "0%s" % hex_repr
 
18345
     return "%" + hex_repr
 
18346
 
 
18347
+
 
18348
+class FakeHTTPMixin(object):
 
18349
+    def fakehttp(self, fakedata):
 
18350
+        class FakeSocket(StringIO.StringIO):
 
18351
+
 
18352
+            def sendall(self, str):
 
18353
+                pass
 
18354
+            def makefile(self, *args, **kwds):
 
18355
+                return self
 
18356
+
 
18357
+            def read(self, amt=None):
 
18358
+                if self.closed:
 
18359
+                    return ""
 
18360
+                return StringIO.StringIO.read(self, amt)
 
18361
+
 
18362
+            def readline(self, length=None):
 
18363
+                if self.closed:
 
18364
+                    return ""
 
18365
+                return StringIO.StringIO.readline(self, length)
 
18366
+
 
18367
+        class FakeHTTPConnection(httplib.HTTPConnection):
 
18368
+            def connect(self):
 
18369
+                self.sock = FakeSocket(fakedata)
 
18370
+        assert httplib.HTTP._connection_class == httplib.HTTPConnection
 
18371
+        httplib.HTTP._connection_class = FakeHTTPConnection
 
18372
+
 
18373
+    def unfakehttp(self):
 
18374
+        httplib.HTTP._connection_class = httplib.HTTPConnection
 
18375
+
 
18376
+
 
18377
 class urlopen_FileTests(unittest.TestCase):
 
18378
     """Test urlopen() opening a temporary file.
 
18379
 
 
18380
@@ -114,30 +144,14 @@
7467
18381
         proxies = urllib.getproxies_environment()
7468
18382
         # getproxies_environment use lowered case truncated (no '_proxy') keys
7469
18383
         self.assertEqual('localhost', proxies['no'])
7472
18386
+        self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com'))
7473
18387
 
7474
18388
 
7475
 
 class urlopen_HttpTests(unittest.TestCase):
 
18389
-class urlopen_HttpTests(unittest.TestCase):
 
18390
+class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin):
 
18391
     """Test urlopen() opening a fake http connection."""
 
18392
 
 
18393
-    def fakehttp(self, fakedata):
 
18394
-        class FakeSocket(StringIO.StringIO):
 
18395
-            def sendall(self, str): pass
 
18396
-            def makefile(self, mode, name): return self
 
18397
-            def read(self, amt=None):
 
18398
-                if self.closed: return ''
 
18399
-                return StringIO.StringIO.read(self, amt)
 
18400
-            def readline(self, length=None):
 
18401
-                if self.closed: return ''
 
18402
-                return StringIO.StringIO.readline(self, length)
 
18403
-        class FakeHTTPConnection(httplib.HTTPConnection):
 
18404
-            def connect(self):
 
18405
-                self.sock = FakeSocket(fakedata)
 
18406
-        assert httplib.HTTP._connection_class == httplib.HTTPConnection
 
18407
-        httplib.HTTP._connection_class = FakeHTTPConnection
 
18408
-
 
18409
-    def unfakehttp(self):
 
18410
-        httplib.HTTP._connection_class = httplib.HTTPConnection
 
18411
-
 
18412
     def test_read(self):
 
18413
         self.fakehttp('Hello!')
 
18414
         try:
 
18415
@@ -327,6 +341,45 @@
 
18416
         self.assertEqual(report[0][1], 8192)
 
18417
         self.assertEqual(report[0][2], 8193)
 
18418
 
 
18419
+
 
18420
+class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin):
 
18421
+    """Test urllib.urlretrieve() using fake http connections"""
 
18422
+
 
18423
+    def test_short_content_raises_ContentTooShortError(self):
 
18424
+        self.fakehttp('''HTTP/1.1 200 OK
 
18425
+Date: Wed, 02 Jan 2008 03:03:54 GMT
 
18426
+Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
 
18427
+Connection: close
 
18428
+Content-Length: 100
 
18429
+Content-Type: text/html; charset=iso-8859-1
 
18430
+
 
18431
+FF
 
18432
+''')
 
18433
+
 
18434
+        def _reporthook(par1, par2, par3):
 
18435
+            pass
 
18436
+
 
18437
+        try:
 
18438
+            self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve,
 
18439
+                    'http://example.com', reporthook=_reporthook)
 
18440
+        finally:
 
18441
+            self.unfakehttp()
 
18442
+
 
18443
+    def test_short_content_raises_ContentTooShortError_without_reporthook(self):
 
18444
+        self.fakehttp('''HTTP/1.1 200 OK
 
18445
+Date: Wed, 02 Jan 2008 03:03:54 GMT
 
18446
+Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
 
18447
+Connection: close
 
18448
+Content-Length: 100
 
18449
+Content-Type: text/html; charset=iso-8859-1
 
18450
+
 
18451
+FF
 
18452
+''')
 
18453
+        try:
 
18454
+            self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve, 'http://example.com/')
 
18455
+        finally:
 
18456
+            self.unfakehttp()
 
18457
+
 
18458
 class QuotingTests(unittest.TestCase):
 
18459
     """Tests for urllib.quote() and urllib.quote_plus()
 
18460
 
 
18461
@@ -404,6 +457,7 @@
 
18462
         result = urllib.quote(partial_quote)
 
18463
         self.assertEqual(expected, result,
 
18464
                          "using quote(): %s != %s" % (expected, result))
 
18465
+        result = urllib.quote_plus(partial_quote)
 
18466
         self.assertEqual(expected, result,
 
18467
                          "using quote_plus(): %s != %s" % (expected, result))
 
18468
         self.assertRaises(TypeError, urllib.quote, None)
 
18469
@@ -770,6 +824,7 @@
 
18470
             urlopen_FileTests,
 
18471
             urlopen_HttpTests,
 
18472
             urlretrieve_FileTests,
 
18473
+            urlretrieve_HttpTests,
 
18474
             ProxyTests,
 
18475
             QuotingTests,
 
18476
             UnquotingTests,
7476
18477
diff -r 8527427914a2 Lib/test/test_urllib2.py
7477
18478
--- a/Lib/test/test_urllib2.py
7478
18479
+++ b/Lib/test/test_urllib2.py
7555
18556
diff -r 8527427914a2 Lib/test/test_urlparse.py
7556
18557
--- a/Lib/test/test_urlparse.py
7557
18558
+++ b/Lib/test/test_urlparse.py
 
18559
@@ -9,7 +9,7 @@
 
18560
 RFC3986_BASE = 'http://a/b/c/d;p?q'
 
18561
 SIMPLE_BASE  = 'http://a/b/c/d'
 
18562
 
 
18563
-# A list of test cases.  Each test case is a a two-tuple that contains
 
18564
+# A list of test cases.  Each test case is a two-tuple that contains
 
18565
 # a string with the query and a dictionary with the expected result.
 
18566
 
 
18567
 parse_qsl_test_cases = [
7558
18568
@@ -82,7 +82,12 @@
7559
18569
     def test_qsl(self):
7560
18570
         for orig, expect in parse_qsl_test_cases:
7611
18621
 
7612
18622
 class WarningsDisplayTests(unittest.TestCase):
7613
18623
 
 
18624
diff -r 8527427914a2 Lib/test/test_xml_etree.py
 
18625
--- a/Lib/test/test_xml_etree.py
 
18626
+++ b/Lib/test/test_xml_etree.py
 
18627
@@ -738,6 +738,7 @@
 
18628
     ...     print action, elem.tag
 
18629
     ... except ET.ParseError, v:
 
18630
     ...   print v
 
18631
+    end document
 
18632
     junk after document element: line 1, column 12
 
18633
     """
 
18634
 
 
18635
diff -r 8527427914a2 Lib/test/test_xmlrpc.py
 
18636
--- a/Lib/test/test_xmlrpc.py
 
18637
+++ b/Lib/test/test_xmlrpc.py
 
18638
@@ -308,7 +308,7 @@
 
18639
         global ADDR, PORT, URL
 
18640
         ADDR, PORT = serv.socket.getsockname()
 
18641
         #connect to IP address directly.  This avoids socket.create_connection()
 
18642
-        #trying to connect to to "localhost" using all address families, which
 
18643
+        #trying to connect to "localhost" using all address families, which
 
18644
         #causes slowdown e.g. on vista which supports AF_INET6.  The server listens
 
18645
         #on AF_INET only.
 
18646
         URL = "http://%s:%d"%(ADDR, PORT)
 
18647
@@ -367,7 +367,7 @@
 
18648
         global ADDR, PORT, URL
 
18649
         ADDR, PORT = serv.socket.getsockname()
 
18650
         #connect to IP address directly.  This avoids socket.create_connection()
 
18651
-        #trying to connect to to "localhost" using all address families, which
 
18652
+        #trying to connect to "localhost" using all address families, which
 
18653
         #causes slowdown e.g. on vista which supports AF_INET6.  The server listens
 
18654
         #on AF_INET only.
 
18655
         URL = "http://%s:%d"%(ADDR, PORT)
 
18656
@@ -472,6 +472,9 @@
 
18657
                 # protocol error; provide additional information in test output
 
18658
                 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
 
18659
 
 
18660
+    def test_unicode_host(self):
 
18661
+        server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
 
18662
+        self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
 
18663
 
 
18664
     # [ch] The test 404 is causing lots of false alarms.
 
18665
     def XXXtest_404(self):
 
18666
diff -r 8527427914a2 Lib/test/test_xpickle.py
 
18667
--- a/Lib/test/test_xpickle.py
 
18668
+++ b/Lib/test/test_xpickle.py
 
18669
@@ -154,6 +154,10 @@
 
18670
     def test_unicode_high_plane(self):
 
18671
         pass
 
18672
 
 
18673
+    # This tests a fix that's in 2.7 only
 
18674
+    def test_dynamic_class(self):
 
18675
+        pass
 
18676
+
 
18677
     if test_support.have_unicode:
 
18678
         # This is a cut-down version of pickletester's test_unicode. Backwards
 
18679
         # compatibility was explicitly broken in r67934 to fix a bug.
7614
18680
diff -r 8527427914a2 Lib/test/test_zipfile.py
7615
18681
--- a/Lib/test/test_zipfile.py
7616
18682
+++ b/Lib/test/test_zipfile.py
7639
18705
     def test_write_default_name(self):
7640
18706
         """Check that calling ZipFile.write without arcname specified
7641
18707
         produces the expected result."""
 
18708
@@ -459,6 +477,12 @@
 
18709
         except zipfile.BadZipfile:
 
18710
             self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
 
18711
 
 
18712
+    def test_add_file_before_1980(self):
 
18713
+        # Set atime and mtime to 1970-01-01
 
18714
+        os.utime(TESTFN, (0, 0))
 
18715
+        with zipfile.ZipFile(TESTFN2, "w") as zipfp:
 
18716
+            self.assertRaises(ValueError, zipfp.write, TESTFN)
 
18717
+
 
18718
     def tearDown(self):
 
18719
         unlink(TESTFN)
 
18720
         unlink(TESTFN2)
 
18721
@@ -972,6 +996,10 @@
 
18722
             pass
 
18723
         self.assertRaises(zipfile.BadZipfile, zipfile.ZipFile, TESTFN, 'r')
 
18724
 
 
18725
+    def test_create_zipinfo_before_1980(self):
 
18726
+        self.assertRaises(ValueError,
 
18727
+                          zipfile.ZipInfo, 'seventies', (1979, 1, 1, 0, 0, 0))
 
18728
+
 
18729
     def tearDown(self):
 
18730
         unlink(TESTFN)
 
18731
         unlink(TESTFN2)
7642
18732
diff -r 8527427914a2 Lib/timeit.py
7643
18733
--- a/Lib/timeit.py
7644
18734
+++ b/Lib/timeit.py
7657
18747
         return timing
7658
18748
 
7659
18749
     def repeat(self, repeat=default_repeat, number=default_number):
 
18750
diff -r 8527427914a2 Lib/trace.py
 
18751
--- a/Lib/trace.py
 
18752
+++ b/Lib/trace.py
 
18753
@@ -502,15 +502,7 @@
 
18754
     def run(self, cmd):
 
18755
         import __main__
 
18756
         dict = __main__.__dict__
 
18757
-        if not self.donothing:
 
18758
-            threading.settrace(self.globaltrace)
 
18759
-            sys.settrace(self.globaltrace)
 
18760
-        try:
 
18761
-            exec cmd in dict, dict
 
18762
-        finally:
 
18763
-            if not self.donothing:
 
18764
-                sys.settrace(None)
 
18765
-                threading.settrace(None)
 
18766
+        self.runctx(cmd, dict, dict)
 
18767
 
 
18768
     def runctx(self, cmd, globals=None, locals=None):
 
18769
         if globals is None: globals = {}
7660
18770
diff -r 8527427914a2 Lib/unittest/case.py
7661
18771
--- a/Lib/unittest/case.py
7662
18772
+++ b/Lib/unittest/case.py
7722
18832
diff -r 8527427914a2 Lib/urllib.py
7723
18833
--- a/Lib/urllib.py
7724
18834
+++ b/Lib/urllib.py
 
18835
@@ -257,9 +257,9 @@
 
18836
                 size = -1
 
18837
                 read = 0
 
18838
                 blocknum = 0
 
18839
+                if "content-length" in headers:
 
18840
+                    size = int(headers["Content-Length"])
 
18841
                 if reporthook:
 
18842
-                    if "content-length" in headers:
 
18843
-                        size = int(headers["Content-Length"])
 
18844
                     reporthook(blocknum, bs, size)
 
18845
                 while 1:
 
18846
                     block = fp.read(bs)
7725
18847
@@ -850,13 +850,16 @@
7726
18848
     """Class used by open_ftp() for cache of open FTP connections."""
7727
18849
 
7928
19050
             # remote invocation has (hopefully) started a new instance.
7929
19051
             time.sleep(1)
7930
19052
             rc = p.poll()
 
19053
diff -r 8527427914a2 Lib/whichdb.py
 
19054
--- a/Lib/whichdb.py
 
19055
+++ b/Lib/whichdb.py
 
19056
@@ -91,7 +91,7 @@
 
19057
         return ""
 
19058
 
 
19059
     # Check for GNU dbm
 
19060
-    if magic == 0x13579ace:
 
19061
+    if magic in (0x13579ace, 0x13579acd, 0x13579acf):
 
19062
         return "gdbm"
 
19063
 
 
19064
     # Check for old Berkeley db hash file format v2
 
19065
diff -r 8527427914a2 Lib/xml/dom/minidom.py
 
19066
--- a/Lib/xml/dom/minidom.py
 
19067
+++ b/Lib/xml/dom/minidom.py
 
19068
@@ -806,10 +806,16 @@
 
19069
             _write_data(writer, attrs[a_name].value)
 
19070
             writer.write("\"")
 
19071
         if self.childNodes:
 
19072
-            writer.write(">%s"%(newl))
 
19073
-            for node in self.childNodes:
 
19074
-                node.writexml(writer,indent+addindent,addindent,newl)
 
19075
-            writer.write("%s</%s>%s" % (indent,self.tagName,newl))
 
19076
+            writer.write(">")
 
19077
+            if (len(self.childNodes) == 1 and
 
19078
+                self.childNodes[0].nodeType == Node.TEXT_NODE):
 
19079
+                self.childNodes[0].writexml(writer, '', '', '')
 
19080
+            else:
 
19081
+                writer.write(newl)
 
19082
+                for node in self.childNodes:
 
19083
+                    node.writexml(writer, indent+addindent, addindent, newl)
 
19084
+                writer.write(indent)
 
19085
+            writer.write("</%s>%s" % (self.tagName, newl))
 
19086
         else:
 
19087
             writer.write("/>%s"%(newl))
 
19088
 
 
19089
@@ -1031,7 +1037,7 @@
 
19090
         return newText
 
19091
 
 
19092
     def writexml(self, writer, indent="", addindent="", newl=""):
 
19093
-        _write_data(writer, "%s%s%s"%(indent, self.data, newl))
 
19094
+        _write_data(writer, "%s%s%s" % (indent, self.data, newl))
 
19095
 
 
19096
     # DOM Level 3 (WD 9 April 2002)
 
19097
 
 
19098
diff -r 8527427914a2 Lib/xml/etree/ElementTree.py
 
19099
--- a/Lib/xml/etree/ElementTree.py
 
19100
+++ b/Lib/xml/etree/ElementTree.py
 
19101
@@ -642,17 +642,23 @@
 
19102
     # @exception ParseError If the parser fails to parse the document.
 
19103
 
 
19104
     def parse(self, source, parser=None):
 
19105
+        close_source = False
 
19106
         if not hasattr(source, "read"):
 
19107
             source = open(source, "rb")
 
19108
-        if not parser:
 
19109
-            parser = XMLParser(target=TreeBuilder())
 
19110
-        while 1:
 
19111
-            data = source.read(65536)
 
19112
-            if not data:
 
19113
-                break
 
19114
-            parser.feed(data)
 
19115
-        self._root = parser.close()
 
19116
-        return self._root
 
19117
+            close_source = True
 
19118
+        try:
 
19119
+            if not parser:
 
19120
+                parser = XMLParser(target=TreeBuilder())
 
19121
+            while 1:
 
19122
+                data = source.read(65536)
 
19123
+                if not data:
 
19124
+                    break
 
19125
+                parser.feed(data)
 
19126
+            self._root = parser.close()
 
19127
+            return self._root
 
19128
+        finally:
 
19129
+            if close_source:
 
19130
+                source.close()
 
19131
 
 
19132
     ##
 
19133
     # Creates a tree iterator for the root element.  The iterator loops
 
19134
@@ -1189,18 +1195,22 @@
 
19135
 # @return A (event, elem) iterator.
 
19136
 
 
19137
 def iterparse(source, events=None, parser=None):
 
19138
+    close_source = False
 
19139
     if not hasattr(source, "read"):
 
19140
         source = open(source, "rb")
 
19141
+        close_source = True
 
19142
     if not parser:
 
19143
         parser = XMLParser(target=TreeBuilder())
 
19144
-    return _IterParseIterator(source, events, parser)
 
19145
+    return _IterParseIterator(source, events, parser, close_source)
 
19146
 
 
19147
 class _IterParseIterator(object):
 
19148
 
 
19149
-    def __init__(self, source, events, parser):
 
19150
+    def __init__(self, source, events, parser, close_source=False):
 
19151
         self._file = source
 
19152
+        self._close_file = close_source
 
19153
         self._events = []
 
19154
         self._index = 0
 
19155
+        self._error = None
 
19156
         self.root = self._root = None
 
19157
         self._parser = parser
 
19158
         # wire up the parser for event reporting
 
19159
@@ -1246,22 +1256,31 @@
 
19160
         while 1:
 
19161
             try:
 
19162
                 item = self._events[self._index]
 
19163
+                self._index += 1
 
19164
+                return item
 
19165
             except IndexError:
 
19166
-                if self._parser is None:
 
19167
-                    self.root = self._root
 
19168
-                    raise StopIteration
 
19169
-                # load event buffer
 
19170
-                del self._events[:]
 
19171
-                self._index = 0
 
19172
-                data = self._file.read(16384)
 
19173
-                if data:
 
19174
+                pass
 
19175
+            if self._error:
 
19176
+                e = self._error
 
19177
+                self._error = None
 
19178
+                raise e
 
19179
+            if self._parser is None:
 
19180
+                self.root = self._root
 
19181
+                if self._close_file:
 
19182
+                    self._file.close()
 
19183
+                raise StopIteration
 
19184
+            # load event buffer
 
19185
+            del self._events[:]
 
19186
+            self._index = 0
 
19187
+            data = self._file.read(16384)
 
19188
+            if data:
 
19189
+                try:
 
19190
                     self._parser.feed(data)
 
19191
-                else:
 
19192
-                    self._root = self._parser.close()
 
19193
-                    self._parser = None
 
19194
+                except SyntaxError as exc:
 
19195
+                    self._error = exc
 
19196
             else:
 
19197
-                self._index = self._index + 1
 
19198
-                return item
 
19199
+                self._root = self._parser.close()
 
19200
+                self._parser = None
 
19201
 
 
19202
     def __iter__(self):
 
19203
         return self
7931
19204
diff -r 8527427914a2 Lib/xml/parsers/expat.py
7932
19205
--- a/Lib/xml/parsers/expat.py
7933
19206
+++ b/Lib/xml/parsers/expat.py
7937
19210
+__version__ = '$Revision: 17640 $'
7938
19211
 
7939
19212
 from pyexpat import *
 
19213
diff -r 8527427914a2 Lib/xmlrpclib.py
 
19214
--- a/Lib/xmlrpclib.py
 
19215
+++ b/Lib/xmlrpclib.py
 
19216
@@ -1539,6 +1539,9 @@
 
19217
                  allow_none=0, use_datetime=0):
 
19218
         # establish a "logical" server connection
 
19219
 
 
19220
+        if isinstance(uri, unicode):
 
19221
+            uri = uri.encode('ISO-8859-1')
 
19222
+
 
19223
         # get the url
 
19224
         import urllib
 
19225
         type, uri = urllib.splittype(uri)
7940
19226
diff -r 8527427914a2 Lib/zipfile.py
7941
19227
--- a/Lib/zipfile.py
7942
19228
+++ b/Lib/zipfile.py
7964
19250
 
7965
19251
     # Unable to find a valid end of central directory structure
7966
19252
     return
 
19253
@@ -292,6 +290,10 @@
 
19254
 
 
19255
         self.filename = filename        # Normalized file name
 
19256
         self.date_time = date_time      # year, month, day, hour, min, sec
 
19257
+
 
19258
+        if date_time[0] < 1980:
 
19259
+            raise ValueError('ZIP does not support timestamps before 1980')
 
19260
+
 
19261
         # Standard values:
 
19262
         self.compress_type = ZIP_STORED # Type of compression for the file
 
19263
         self.comment = ""               # Comment for each file
7967
19264
diff -r 8527427914a2 Makefile.pre.in
7968
19265
--- a/Makefile.pre.in
7969
19266
+++ b/Makefile.pre.in
7987
19284
        PYTHONPATH=$(DESTDIR)$(LIBDEST)  $(RUNSHARED) \
7988
19285
                ./$(BUILDPYTHON) -Wi -tt $(DESTDIR)$(LIBDEST)/compileall.py \
7989
19286
                -d $(LIBDEST) -f \
 
19287
@@ -1218,7 +1222,7 @@
 
19288
 
 
19289
 # Find files with funny names
 
19290
 funny:
 
19291
-       find $(DISTDIRS) -type d \
 
19292
+       find $(SUBDIRS) $(SUBDIRSTOO) -type d \
 
19293
                -o -name '*.[chs]' \
 
19294
                -o -name '*.py' \
 
19295
                -o -name '*.doc' \
7990
19296
diff -r 8527427914a2 Misc/ACKS
7991
19297
--- a/Misc/ACKS
7992
19298
+++ b/Misc/ACKS
7993
 
@@ -162,6 +162,7 @@
 
19299
@@ -147,6 +147,7 @@
 
19300
 Tom Christiansen
 
19301
 Vadim Chugunov
 
19302
 David Cinege
 
19303
+Craig Citro
 
19304
 Mike Clarkson
 
19305
 Andrew Clegg
 
19306
 Brad Clements
 
19307
@@ -162,6 +163,7 @@
7994
19308
 Juan José Conti
7995
19309
 Matt Conway
7996
19310
 David M. Cooke
7998
19312
 Greg Copeland
7999
19313
 Aldo Cortesi
8000
19314
 David Costanzo
8001
 
@@ -193,6 +194,7 @@
 
19315
@@ -193,6 +195,7 @@
8002
19316
 Vincent Delft
8003
19317
 Arnaud Delobelle
8004
19318
 Erik Demaine
8006
19320
 Roger Dev
8007
19321
 Raghuram Devarakonda
8008
19322
 Catherine Devlin
8009
 
@@ -307,6 +309,7 @@
 
19323
@@ -307,6 +310,7 @@
8010
19324
 Eddy De Greef
8011
19325
 Duncan Grisby
8012
19326
 Fabian Groffen
8014
19328
 Dag Gruneau
8015
19329
 Filip Gruszczyński
8016
19330
 Michael Guravage
8017
 
@@ -431,6 +434,7 @@
 
19331
@@ -399,6 +403,7 @@
 
19332
 Geert Jansen
 
19333
 Jack Jansen
 
19334
 Bill Janssen
 
19335
+Thomas Jarosch
 
19336
 Drew Jenkins
 
19337
 Flemming Kjær Jensen
 
19338
 Jiba
 
19339
@@ -431,6 +436,7 @@
8018
19340
 Randall Kern
8019
19341
 Magnus Kessler
8020
19342
 Lawrence Kesteloot
8022
19344
 Vivek Khera
8023
19345
 Akira Kitada
8024
19346
 Mads Kiilerich
8025
 
@@ -608,6 +612,7 @@
 
19347
@@ -443,6 +449,8 @@
 
19348
 Bastian Kleineidam
 
19349
 Bob Kline
 
19350
 Matthias Klose
 
19351
+Jeremy Kloth
 
19352
+Thomas Kluyver
 
19353
 Kim Knapp
 
19354
 Lenny Kneler
 
19355
 Pat Knight
 
19356
@@ -461,6 +469,7 @@
 
19357
 Andrew Kuchling
 
19358
 Ralf W. Grosse-Kunstleve
 
19359
 Vladimir Kushnir
 
19360
+Kirill Kuzminykh (Кирилл Кузьминых)
 
19361
 Ross Lagerwall
 
19362
 Cameron Laird
 
19363
 Łukasz Langa
 
19364
@@ -502,6 +511,7 @@
 
19365
 Stephanie Lockwood
 
19366
 Anne Lord
 
19367
 Tom Loredo
 
19368
+Justin Love
 
19369
 Jason Lowe
 
19370
 Tony Lownds
 
19371
 Ray Loyzaga
 
19372
@@ -546,6 +556,7 @@
 
19373
 Ezio Melotti
 
19374
 Brian Merrell
 
19375
 Luke Mewburn
 
19376
+Carl Meyer
 
19377
 Mike Meyer
 
19378
 Steven Miale
 
19379
 Trent Mick
 
19380
@@ -608,6 +619,7 @@
8026
19381
 Jason Orendorff
8027
19382
 Douglas Orr
8028
19383
 Michele Orrù
8030
19385
 Denis S. Otkidach
8031
19386
 Michael Otteneder
8032
19387
 R. M. Oudkerk
8033
 
@@ -669,6 +674,7 @@
 
19388
@@ -669,6 +681,7 @@
8034
19389
 Marc Recht
8035
19390
 John Redford
8036
19391
 Terry Reedy
8038
19393
 Steve Reeves
8039
19394
 Lennart Regebro
8040
19395
 Ofir Reichenberg
8041
 
@@ -683,7 +689,9 @@
 
19396
@@ -683,7 +696,9 @@
8042
19397
 Armin Rigo
8043
19398
 Nicholas Riley
8044
19399
 Jean-Claude Rimbault
8048
19403
 Anthony Roach
8049
19404
 Mark Roberts
8050
19405
 Jim Robinson
8051
 
@@ -766,6 +774,7 @@
 
19406
@@ -711,6 +726,7 @@
 
19407
 Mark Russell
 
19408
 Nick Russo
 
19409
 Sébastien Sablé
 
19410
+Suman Saha
 
19411
 Hajime Saitou
 
19412
 George Sakkis
 
19413
 Rich Salz
 
19414
@@ -719,6 +735,7 @@
 
19415
 Mark Sapiro
 
19416
 Ty Sarna
 
19417
 Ben Sayer
 
19418
+sbt
 
19419
 Michael Scharf
 
19420
 Neil Schemenauer
 
19421
 David Scherer
 
19422
@@ -766,6 +783,7 @@
8052
19423
 Paul Sokolovsky
8053
19424
 Cody Somerville
8054
19425
 Clay Spence
8056
19427
 Per Spilling
8057
19428
 Joshua Spoerri
8058
19429
 Noah Spurrier
8059
 
@@ -806,6 +815,7 @@
 
19430
@@ -803,9 +821,12 @@
 
19431
 Amy Taylor
 
19432
 Anatoly Techtonik
 
19433
 Mikhail Terekhov
 
19434
+Richard M. Tew
8060
19435
 Tobias Thelen
 
19436
+Nicolas M. Thiéry
8061
19437
 James Thomas
8062
19438
 Robin Thomas
8063
19439
+Stephen Thorne
8064
19440
 Eric Tiedemann
8065
19441
 Tracy Tims
8066
19442
 Oren Tirosh
 
19443
@@ -904,6 +925,7 @@
 
19444
 Danny Yoo
 
19445
 George Yoshida
 
19446
 Masazumi Yoshikawa
 
19447
+Arnaud Ysmal
 
19448
 Bernard Yue
 
19449
 Moshe Zadka
 
19450
 Milan Zamazal
8067
19451
diff -r 8527427914a2 Misc/NEWS
8068
19452
--- a/Misc/NEWS
8069
19453
+++ b/Misc/NEWS
8070
 
@@ -1,6 +1,211 @@
 
19454
@@ -1,6 +1,438 @@
8071
19455
 Python News
8072
19456
 +++++++++++
8073
19457
 
8079
19463
+Core and Builtins
8080
19464
+-----------------
8081
19465
+
 
19466
+- Issue #13333: The UTF-7 decoder now accepts lone surrogates (the encoder
 
19467
+  already accepts them).
 
19468
+
 
19469
+- Remove Py3k warning for callable.
 
19470
+
 
19471
+- Issue #10519: Avoid unnecessary recursive function calls in
 
19472
+  setobject.c.
 
19473
+
 
19474
+- Issue #13268: Fix the assert statement when a tuple is passed as the message.
 
19475
+
 
19476
+- Issue #13018: Fix reference leaks in error paths in dictobject.c.
 
19477
+  Patch by Suman Saha.
 
19478
+
 
19479
+- Issue #12604: VTRACE macro expanded to no-op in _sre.c to avoid compiler
 
19480
+  warnings. Patch by Josh Triplett and Petri Lehtinen.
 
19481
+
 
19482
+- Issue #7833: Extension modules built using distutils on Windows will no
 
19483
+  longer include a "manifest" to prevent them failing at import time in some
 
19484
+  embedded situations.
 
19485
+
 
19486
+- Issue #13186: Fix __delitem__ on old-style instances when invoked through
 
19487
+  PySequence_DelItem.
 
19488
+
 
19489
+- Issue #13156: Revert the patch for issue #10517 (reset TLS upon fork()),
 
19490
+  which was only relevant for the native pthread TLS implementation.
 
19491
+
 
19492
+- Issue #7732: Fix a crash on importing a module if a directory has the same
 
19493
+  name than a Python module (e.g. "__init__.py"): don't close the file twice.
 
19494
+
 
19495
+- Issue #12973: Fix overflow checks that invoked undefined behaviour in
 
19496
+  int.__pow__.  These overflow checks were causing int.__pow__ to produce
 
19497
+  incorrect results with recent versions of Clang, as a result of the
 
19498
+  compiler optimizing the check away.  Also fix similar overflow checks
 
19499
+  in list_repeat (listobject.c) and islice_next (itertoolsmodule.c).  These
 
19500
+  bugs caused test failures with recent versions of Clang.
 
19501
+
8082
19502
+- Issue #12266: Fix str.capitalize() to correctly uppercase/lowercase
8083
19503
+  titlecased and cased non-letter characters.
8084
19504
+
8104
19524
+  the following case: sys.stdin.read() stopped with CTRL+d (end of file),
8105
19525
+  raw_input() interrupted by CTRL+c.
8106
19526
+
 
19527
+- Issue #10860: httplib now correctly handles an empty port after port
 
19528
+  delimiter in URLs.
 
19529
+
8107
19530
+- dict_proxy objects now display their contents rather than just the class
8108
19531
+  name.
8109
19532
+
8110
19533
+Library
8111
19534
+-------
8112
19535
+
 
19536
+- Issue #12856: Ensure child processes do not inherit the parent's random
 
19537
+  seed for filename generation in the tempfile module.  Patch by Brian
 
19538
+  Harring.
 
19539
+
 
19540
+- Issue #13458: Fix a memory leak in the ssl module when decoding a
 
19541
+  certificate with a subjectAltName.  Patch by Robert Xiao.
 
19542
+
 
19543
+- Issue #13415: os.unsetenv() doesn't ignore errors anymore.
 
19544
+
 
19545
+- Issue #13322: Fix BufferedWriter.write() to ensure that BlockingIOError is
 
19546
+  raised when the wrapped raw file is non-blocking and the write would block.
 
19547
+  Previous code assumed that the raw write() would raise BlockingIOError, but
 
19548
+  RawIOBase.write() is defined to returned None when the call would block.
 
19549
+  Patch by sbt.
 
19550
+
 
19551
+- Issue #13358: HTMLParser now calls handle_data only once for each CDATA.
 
19552
+
 
19553
+- Issue #4147: minidom's toprettyxml no longer adds whitespace around a text
 
19554
+  node when it is the only child of an element.  Initial patch by Dan
 
19555
+  Kenigsberg.
 
19556
+
 
19557
+- Issue #8793: Prevent IDLE crash when given strings with invalid hex escape
 
19558
+  sequences.
 
19559
+
 
19560
+- Issues #1745761, #755670, #13357, #12629, #1200313: HTMLParser now correctly
 
19561
+  handles non-valid attributes, including adjacent and unquoted attributes.
 
19562
+
 
19563
+- Issue #13193: Fix distutils.filelist.FileList under Windows.  The
 
19564
+  "recursive-include" directive now recognizes both legal path separators.
 
19565
+
 
19566
+- Issue #13373: multiprocessing.Queue.get() could sometimes block indefinitely
 
19567
+  when called with a timeout.  Patch by Arnaud Ysmal.
 
19568
+
 
19569
+- Issue #3067: Enhance the documentation and docstring of
 
19570
+  locale.setlocale().
 
19571
+
 
19572
+- Issue #13254: Fix Maildir initialization so that maildir contents
 
19573
+  are read correctly.
 
19574
+
 
19575
+- Issue #13140: Fix the daemon_threads attribute of ThreadingMixIn.
 
19576
+
 
19577
+- Issue #2892: preserve iterparse events in case of SyntaxError.
 
19578
+
 
19579
+- Issue #670664: Fix HTMLParser to correctly handle the content of
 
19580
+  ``<script>...</script>`` and ``<style>...</style>``.
 
19581
+
 
19582
+- Issue #10817: Fix urlretrieve function to raise ContentTooShortError even
 
19583
+  when reporthook is None. Patch by Jyrki Pulliainen.
 
19584
+
 
19585
+- Issue #13296: Fix IDLE to clear compile __future__ flags on shell restart.
 
19586
+  (Patch by Roger Serwy)
 
19587
+
 
19588
+- Issue #7334: close source files on ElementTree.parse and iterparse.
 
19589
+
 
19590
+- Issue #13232: logging: Improved logging of exceptions in the presence of
 
19591
+  multiple encodings.
 
19592
+
 
19593
+- Issue #10332: multiprocessing: fix a race condition when a Pool is closed
 
19594
+  before all tasks have completed.
 
19595
+
 
19596
+- Issue #1548891: The cStringIO.StringIO() constructor now encodes unicode
 
19597
+  arguments with the system default encoding just like the write() method
 
19598
+  does, instead of converting it to a raw buffer.  This also fixes handling of
 
19599
+  unicode input in the shlex module (#6988, #1170).
 
19600
+
 
19601
+- Issue #9168: now smtpd is able to bind privileged port.
 
19602
+
 
19603
+- Issue #12529: fix cgi.parse_header issue on strings with double-quotes and
 
19604
+  semicolons together. Patch by Ben Darnell and Petri Lehtinen.
 
19605
+
 
19606
+- Issue #6090: zipfile raises a ValueError when a document with a timestamp
 
19607
+  earlier than 1980 is provided. Patch contributed by Petri Lehtinen.
 
19608
+
 
19609
+- Issue #13194: zlib.compressobj().copy() and zlib.decompressobj().copy() are
 
19610
+  now available on Windows.
 
19611
+
 
19612
+- Issue #13114: Fix the distutils commands check and register when the
 
19613
+  long description is a Unicode string with non-ASCII characters.
 
19614
+
 
19615
+- Issue #7367: Fix pkgutil.walk_paths to skip directories whose
 
19616
+  contents cannot be read.
 
19617
+
 
19618
+- Issue #7425: Prevent pydoc -k failures due to module import errors.
 
19619
+  (Backport to 2.7 of existing 3.x fix)
 
19620
+
 
19621
+- Issue #13099: Fix sqlite3.Cursor.lastrowid under a Turkish locale.
 
19622
+  Reported and diagnosed by Thomas Kluyver.
 
19623
+
 
19624
+- Issue #7689: Allow pickling of dynamically created classes when their
 
19625
+  metaclass is registered with copy_reg.  Patch by Nicolas M. Thiéry and
 
19626
+  Craig Citro.
 
19627
+
 
19628
+- Issue #13058: ossaudiodev: fix a file descriptor leak on error. Patch by
 
19629
+  Thomas Jarosch.
 
19630
+
 
19631
+- Issue #12931: xmlrpclib now encodes Unicode URI to ISO-8859-1, instead of
 
19632
+  failing with a UnicodeDecodeError.
 
19633
+
 
19634
+- Issue #8933: distutils' PKG-INFO files will now correctly report
 
19635
+  Metadata-Version: 1.1 instead of 1.0 if a Classifier or Download-URL field is
 
19636
+  present.
 
19637
+
 
19638
+- Issue #8286: The distutils command sdist will print a warning message instead
 
19639
+  of crashing when an invalid path is given in the manifest template.
 
19640
+
 
19641
+- Issue #12841: tarfile unnecessarily checked the existence of numerical user
 
19642
+  and group ids on extraction. If one of them did not exist the respective id
 
19643
+  of the current user (i.e. root) was used for the file and ownership
 
19644
+  information was lost.
 
19645
+
 
19646
+- Issue #10946: The distutils commands bdist_dumb, bdist_wininst and bdist_msi
 
19647
+  now respect a --skip-build option given to bdist.
 
19648
+
 
19649
+- Issue #12287: Fix a stack corruption in ossaudiodev module when the FD is
 
19650
+  greater than FD_SETSIZE.
 
19651
+
 
19652
+- Issue #12839: Fix crash in zlib module due to version mismatch.
 
19653
+  Fix by Richard M. Tew.
 
19654
+
 
19655
+- Issue #12786: Set communication pipes used by subprocess.Popen CLOEXEC to
 
19656
+  avoid them being inherited by other subprocesses.
 
19657
+
 
19658
+- Issue #4106: Fix occasional exceptions printed out by multiprocessing on
 
19659
+  interpreter shutdown.
 
19660
+
 
19661
+- Issue #11657: Fix sending file descriptors over 255 over a multiprocessing
 
19662
+  Pipe.
 
19663
+
 
19664
+- Issue #12213: Fix a buffering bug with interleaved reads and writes that
 
19665
+  could appear on io.BufferedRandom streams.
 
19666
+
 
19667
+- Issue #12326: sys.platform is now always 'linux2' on Linux, even if Python
 
19668
+  is compiled on Linux 3.
 
19669
+
 
19670
+- Issue #13007: whichdb should recognize gdbm 1.9 magic numbers.
 
19671
+
 
19672
+- Issue #9173: Let shutil._make_archive work if the logger argument is None.
 
19673
+
 
19674
+- Issue #12650: Fix a race condition where a subprocess.Popen could leak
 
19675
+  resources (FD/zombie) when killed at the wrong time.
 
19676
+
8113
19677
+- Issue #12752: Fix regression which prevented locale.normalize() from
8114
19678
+  accepting unicode strings.
8115
19679
+
8221
19785
+Extension Modules
8222
19786
+-----------------
8223
19787
+
 
19788
+- Issue #13159: FileIO, BZ2File, and the built-in file class now use a
 
19789
+  linear-time buffer growth strategy instead of a quadratic one.
 
19790
+
 
19791
+- Issue #13070: Fix a crash when a TextIOWrapper caught in a reference cycle
 
19792
+  would be finalized after the reference to its underlying BufferedRWPair's
 
19793
+  writer got cleared by the GC.
 
19794
+
 
19795
+- Issue #12881: ctypes: Fix segfault with large structure field names.
 
19796
+
 
19797
+- Issue #13013: ctypes: Fix a reference leak in PyCArrayType_from_ctype.
 
19798
+  Thanks to Suman Saha for finding the bug and providing a patch.
 
19799
+
 
19800
+- Issue #13022: Fix: _multiprocessing.recvfd() doesn't check that
 
19801
+  file descriptor was actually received.
 
19802
+
 
19803
+- Issue #12483: ctypes: Fix a crash when the destruction of a callback
 
19804
+  object triggers the garbage collector.
 
19805
+
 
19806
+- Issue #12950: Fix passing file descriptors in multiprocessing, under
 
19807
+  OpenIndiana/Illumos.
 
19808
+
 
19809
+- Issue #12764: Fix a crash in ctypes when the name of a Structure field is not
 
19810
+  a string.
 
19811
+
 
19812
+- Issue #9651: Fix a crash when ctypes.create_string_buffer(0) was passed to
 
19813
+  some functions like file.write().
 
19814
+
8224
19815
+- Issue #10309: Define _GNU_SOURCE so that mremap() gets the proper
8225
19816
+  signature.  Without this, architectures where sizeof void* != sizeof int are
8226
19817
+  broken.  Patch given by Hallvard B Furuseth.
8242
19833
+Tests
8243
19834
+-----
8244
19835
+
 
19836
+- Issue #13304: Skip test case if user site-packages disabled (-s or
 
19837
+  PYTHONNOUSERSITE).  (Patch by Carl Meyer)
 
19838
+
 
19839
+- Issue #13218: Fix test_ssl failures on Debian/Ubuntu.
 
19840
+
 
19841
+- Issue #12821: Fix test_fcntl failures on OpenBSD 5.
 
19842
+
8245
19843
+- Issue #12331: The test suite for lib2to3 can now run from an installed
8246
19844
+  Python.
8247
19845
+
8251
19849
+- Skip network tests when getaddrinfo() returns EAI_AGAIN, meaning a temporary
8252
19850
+  failure in name resolution.
8253
19851
+
 
19852
+- Issue #11812: Solve transient socket failure to connect to 'localhost'
 
19853
+  in test_telnetlib.py.
 
19854
+
 
19855
+- Solved a potential deadlock in test_telnetlib.py. Related to issue #11812.
 
19856
+
8254
19857
+- Avoid failing in test_robotparser when mueblesmoraleda.com is flaky and
8255
19858
+  an overzealous DNS service (e.g. OpenDNS) redirects to a placeholder
8256
19859
+  Web site.
8276
19879
+- Issue #12057: Add tests for ISO 2022 codecs (iso2022_jp, iso2022_jp_2,
8277
19880
+  iso2022_kr).
8278
19881
+
 
19882
+Documentation
 
19883
+-------------
 
19884
+
 
19885
+- Issue #13237: Reorganise subprocess documentation to emphasise convenience
 
19886
+  functions and the most commonly needed arguments to Popen.
 
19887
+
 
19888
+- Issue #13141: Demonstrate recommended style for SocketServer examples.
 
19889
+
8279
19890
 
8280
19891
 What's New in Python 2.7.2?
8281
19892
 ===========================
8282
 
@@ -106,6 +311,9 @@
 
19893
@@ -106,6 +538,9 @@
8283
19894
 Library
8284
19895
 -------
8285
19896
 
8289
19900
 - Issue #12161: Cause StringIO.getvalue() to raise a ValueError when used on a
8290
19901
   closed StringIO instance.
8291
19902
 
 
19903
diff -r 8527427914a2 Modules/_bsddb.c
 
19904
--- a/Modules/_bsddb.c
 
19905
+++ b/Modules/_bsddb.c
 
19906
@@ -8795,7 +8795,7 @@
 
19907
     {"txn_recover",     (PyCFunction)DBEnv_txn_recover,     METH_NOARGS},
 
19908
 #if (DBVER < 48)
 
19909
     {"set_rpc_server",  (PyCFunction)DBEnv_set_rpc_server,
 
19910
-        METH_VARARGS||METH_KEYWORDS},
 
19911
+        METH_VARARGS|METH_KEYWORDS},
 
19912
 #endif
 
19913
 #if (DBVER >= 43)
 
19914
     {"set_mp_max_openfd", (PyCFunction)DBEnv_set_mp_max_openfd, METH_VARARGS},
 
19915
diff -r 8527427914a2 Modules/_ctypes/_ctypes.c
 
19916
--- a/Modules/_ctypes/_ctypes.c
 
19917
+++ b/Modules/_ctypes/_ctypes.c
 
19918
@@ -2576,8 +2576,10 @@
 
19919
     view->ndim = dict->ndim;
 
19920
     view->shape = dict->shape;
 
19921
     view->itemsize = self->b_size;
 
19922
-    for (i = 0; i < view->ndim; ++i) {
 
19923
-        view->itemsize /= dict->shape[i];
 
19924
+    if (view->itemsize) {
 
19925
+        for (i = 0; i < view->ndim; ++i) {
 
19926
+            view->itemsize /= dict->shape[i];
 
19927
+        }
 
19928
     }
 
19929
     view->strides = NULL;
 
19930
     view->suboffsets = NULL;
 
19931
@@ -4676,6 +4678,7 @@
 
19932
     if (!PyType_Check(itemtype)) {
 
19933
         PyErr_SetString(PyExc_TypeError,
 
19934
                         "Expected a type object");
 
19935
+        Py_DECREF(key);
 
19936
         return NULL;
 
19937
     }
 
19938
 #ifdef MS_WIN64
 
19939
diff -r 8527427914a2 Modules/_ctypes/callbacks.c
 
19940
--- a/Modules/_ctypes/callbacks.c
 
19941
+++ b/Modules/_ctypes/callbacks.c
 
19942
@@ -18,6 +18,7 @@
 
19943
 CThunkObject_dealloc(PyObject *_self)
 
19944
 {
 
19945
     CThunkObject *self = (CThunkObject *)_self;
 
19946
+    PyObject_GC_UnTrack(self);
 
19947
     Py_XDECREF(self->converters);
 
19948
     Py_XDECREF(self->callable);
 
19949
     Py_XDECREF(self->restype);
8292
19950
diff -r 8527427914a2 Modules/_ctypes/libffi/src/dlmalloc.c
8293
19951
--- a/Modules/_ctypes/libffi/src/dlmalloc.c
8294
19952
+++ b/Modules/_ctypes/libffi/src/dlmalloc.c
8304
19962
 #endif  /* WIN32 */
8305
19963
 
8306
19964
 #if defined(DARWIN) || defined(_DARWIN)
 
19965
diff -r 8527427914a2 Modules/_ctypes/stgdict.c
 
19966
--- a/Modules/_ctypes/stgdict.c
 
19967
+++ b/Modules/_ctypes/stgdict.c
 
19968
@@ -494,14 +494,33 @@
 
19969
             char *fieldfmt = dict->format ? dict->format : "B";
 
19970
             char *fieldname = PyString_AsString(name);
 
19971
             char *ptr;
 
19972
-            Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
 
19973
-            char *buf = alloca(len + 2 + 1);
 
19974
+            Py_ssize_t len; 
 
19975
+            char *buf;
 
19976
 
 
19977
+            if (fieldname == NULL)
 
19978
+            {
 
19979
+                PyErr_Format(PyExc_TypeError,
 
19980
+                             "structure field name must be string not %s",
 
19981
+                             name->ob_type->tp_name);
 
19982
+                                
 
19983
+                Py_DECREF(pair);
 
19984
+                return -1;
 
19985
+            }
 
19986
+
 
19987
+            len = strlen(fieldname) + strlen(fieldfmt);
 
19988
+
 
19989
+            buf = PyMem_Malloc(len + 2 + 1);
 
19990
+            if (buf == NULL) {
 
19991
+                Py_DECREF(pair);
 
19992
+                PyErr_NoMemory();
 
19993
+                return -1;
 
19994
+            }
 
19995
             sprintf(buf, "%s:%s:", fieldfmt, fieldname);
 
19996
 
 
19997
             ptr = stgdict->format;
 
19998
             stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
 
19999
             PyMem_Free(ptr);
 
20000
+            PyMem_Free(buf);
 
20001
 
 
20002
             if (stgdict->format == NULL) {
 
20003
                 Py_DECREF(pair);
 
20004
diff -r 8527427914a2 Modules/_elementtree.c
 
20005
--- a/Modules/_elementtree.c
 
20006
+++ b/Modules/_elementtree.c
 
20007
@@ -2915,19 +2915,25 @@
 
20008
 
 
20009
         "class ElementTree(ET.ElementTree):\n" /* public */
 
20010
         "  def parse(self, source, parser=None):\n"
 
20011
+        "    close_source = False\n"
 
20012
         "    if not hasattr(source, 'read'):\n"
 
20013
         "      source = open(source, 'rb')\n"
 
20014
-        "    if parser is not None:\n"
 
20015
-        "      while 1:\n"
 
20016
-        "        data = source.read(65536)\n"
 
20017
-        "        if not data:\n"
 
20018
-        "          break\n"
 
20019
-        "        parser.feed(data)\n"
 
20020
-        "      self._root = parser.close()\n"
 
20021
-        "    else:\n" 
 
20022
-        "      parser = cElementTree.XMLParser()\n"
 
20023
-        "      self._root = parser._parse(source)\n"
 
20024
-        "    return self._root\n"
 
20025
+        "      close_source = False\n"
 
20026
+        "    try:\n"
 
20027
+        "      if parser is not None:\n"
 
20028
+        "        while 1:\n"
 
20029
+        "          data = source.read(65536)\n"
 
20030
+        "          if not data:\n"
 
20031
+        "            break\n"
 
20032
+        "          parser.feed(data)\n"
 
20033
+        "        self._root = parser.close()\n"
 
20034
+        "      else:\n" 
 
20035
+        "        parser = cElementTree.XMLParser()\n"
 
20036
+        "        self._root = parser._parse(source)\n"
 
20037
+        "      return self._root\n"
 
20038
+        "    finally:\n"
 
20039
+        "      if close_source:\n"
 
20040
+        "        source.close()\n"
 
20041
         "cElementTree.ElementTree = ElementTree\n"
 
20042
 
 
20043
         "def iter(node, tag=None):\n" /* helper */
 
20044
@@ -2957,11 +2963,14 @@
 
20045
         "class iterparse(object):\n"
 
20046
         " root = None\n"
 
20047
         " def __init__(self, file, events=None):\n"
 
20048
+        "  self._close_file = False\n"
 
20049
         "  if not hasattr(file, 'read'):\n"
 
20050
         "    file = open(file, 'rb')\n"
 
20051
+        "    self._close_file = True\n"
 
20052
         "  self._file = file\n"
 
20053
         "  self._events = []\n"
 
20054
         "  self._index = 0\n"
 
20055
+        "  self._error = None\n"
 
20056
         "  self.root = self._root = None\n"
 
20057
         "  b = cElementTree.TreeBuilder()\n"
 
20058
         "  self._parser = cElementTree.XMLParser(b)\n"
 
20059
@@ -2970,22 +2979,31 @@
 
20060
         "  while 1:\n"
 
20061
         "    try:\n"
 
20062
         "      item = self._events[self._index]\n"
 
20063
+        "      self._index += 1\n"
 
20064
+        "      return item\n"
 
20065
         "    except IndexError:\n"
 
20066
-        "      if self._parser is None:\n"
 
20067
-        "        self.root = self._root\n"
 
20068
-        "        raise StopIteration\n"
 
20069
-        "      # load event buffer\n"
 
20070
-        "      del self._events[:]\n"
 
20071
-        "      self._index = 0\n"
 
20072
-        "      data = self._file.read(16384)\n"
 
20073
-        "      if data:\n"
 
20074
+        "      pass\n"
 
20075
+        "    if self._error:\n"
 
20076
+        "      e = self._error\n"
 
20077
+        "      self._error = None\n"
 
20078
+        "      raise e\n"
 
20079
+        "    if self._parser is None:\n"
 
20080
+        "      self.root = self._root\n"
 
20081
+        "      if self._close_file:\n"
 
20082
+        "        self._file.close()\n"
 
20083
+        "      raise StopIteration\n"
 
20084
+        "    # load event buffer\n"
 
20085
+        "    del self._events[:]\n"
 
20086
+        "    self._index = 0\n"
 
20087
+        "    data = self._file.read(16384)\n"
 
20088
+        "    if data:\n"
 
20089
+        "      try:\n"
 
20090
         "        self._parser.feed(data)\n"
 
20091
-        "      else:\n"
 
20092
-        "        self._root = self._parser.close()\n"
 
20093
-        "        self._parser = None\n"
 
20094
+        "      except SyntaxError as exc:\n"
 
20095
+        "        self._error = exc\n"
 
20096
         "    else:\n"
 
20097
-        "      self._index = self._index + 1\n"
 
20098
-        "      return item\n"
 
20099
+        "      self._root = self._parser.close()\n"
 
20100
+        "      self._parser = None\n"
 
20101
         " def __iter__(self):\n"
 
20102
         "  return self\n"
 
20103
         "cElementTree.iterparse = iterparse\n"
 
20104
diff -r 8527427914a2 Modules/_io/bufferedio.c
 
20105
--- a/Modules/_io/bufferedio.c
 
20106
+++ b/Modules/_io/bufferedio.c
 
20107
@@ -550,7 +550,7 @@
 
20108
 
 
20109
 /* Forward decls */
 
20110
 static PyObject *
 
20111
-_bufferedwriter_flush_unlocked(buffered *, int);
 
20112
+_bufferedwriter_flush_unlocked(buffered *);
 
20113
 static Py_ssize_t
 
20114
 _bufferedreader_fill_buffer(buffered *self);
 
20115
 static void
 
20116
@@ -571,6 +571,18 @@
 
20117
  * Helpers
 
20118
  */
 
20119
 
 
20120
+/* Sets the current error to BlockingIOError */
 
20121
+static void
 
20122
+_set_BlockingIOError(char *msg, Py_ssize_t written)
 
20123
+{
 
20124
+    PyObject *err;
 
20125
+    err = PyObject_CallFunction(PyExc_BlockingIOError, "isn",
 
20126
+                                errno, msg, written);
 
20127
+    if (err)
 
20128
+        PyErr_SetObject(PyExc_BlockingIOError, err);
 
20129
+    Py_XDECREF(err);
 
20130
+}
 
20131
+
 
20132
 /* Returns the address of the `written` member if a BlockingIOError was
 
20133
    raised, NULL otherwise. The error is always re-raised. */
 
20134
 static Py_ssize_t *
 
20135
@@ -721,6 +733,28 @@
 
20136
  */
 
20137
 
 
20138
 static PyObject *
 
20139
+buffered_flush_and_rewind_unlocked(buffered *self)
 
20140
+{
 
20141
+    PyObject *res;
 
20142
+
 
20143
+    res = _bufferedwriter_flush_unlocked(self);
 
20144
+    if (res == NULL)
 
20145
+        return NULL;
 
20146
+    Py_DECREF(res);
 
20147
+
 
20148
+    if (self->readable) {
 
20149
+        /* Rewind the raw stream so that its position corresponds to
 
20150
+           the current logical position. */
 
20151
+        Py_off_t n;
 
20152
+        n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
 
20153
+        _bufferedreader_reset_buf(self);
 
20154
+        if (n == -1)
 
20155
+            return NULL;
 
20156
+    }
 
20157
+    Py_RETURN_NONE;
 
20158
+}
 
20159
+
 
20160
+static PyObject *
 
20161
 buffered_flush(buffered *self, PyObject *args)
 
20162
 {
 
20163
     PyObject *res;
 
20164
@@ -730,16 +764,7 @@
 
20165
 
 
20166
     if (!ENTER_BUFFERED(self))
 
20167
         return NULL;
 
20168
-    res = _bufferedwriter_flush_unlocked(self, 0);
 
20169
-    if (res != NULL && self->readable) {
 
20170
-        /* Rewind the raw stream so that its position corresponds to
 
20171
-           the current logical position. */
 
20172
-        Py_off_t n;
 
20173
-        n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
 
20174
-        if (n == -1)
 
20175
-            Py_CLEAR(res);
 
20176
-        _bufferedreader_reset_buf(self);
 
20177
-    }
 
20178
+    res = buffered_flush_and_rewind_unlocked(self);
 
20179
     LEAVE_BUFFERED(self)
 
20180
 
 
20181
     return res;
 
20182
@@ -760,7 +785,7 @@
 
20183
         return NULL;
 
20184
 
 
20185
     if (self->writable) {
 
20186
-        res = _bufferedwriter_flush_unlocked(self, 1);
 
20187
+        res = buffered_flush_and_rewind_unlocked(self);
 
20188
         if (res == NULL)
 
20189
             goto end;
 
20190
         Py_CLEAR(res);
 
20191
@@ -795,19 +820,18 @@
 
20192
         if (!ENTER_BUFFERED(self))
 
20193
             return NULL;
 
20194
         res = _bufferedreader_read_all(self);
 
20195
-        LEAVE_BUFFERED(self)
 
20196
     }
 
20197
     else {
 
20198
         res = _bufferedreader_read_fast(self, n);
 
20199
-        if (res == Py_None) {
 
20200
-            Py_DECREF(res);
 
20201
-            if (!ENTER_BUFFERED(self))
 
20202
-                return NULL;
 
20203
-            res = _bufferedreader_read_generic(self, n);
 
20204
-            LEAVE_BUFFERED(self)
 
20205
-        }
 
20206
+        if (res != Py_None)
 
20207
+            return res;
 
20208
+        Py_DECREF(res);
 
20209
+        if (!ENTER_BUFFERED(self))
 
20210
+            return NULL;
 
20211
+        res = _bufferedreader_read_generic(self, n);
 
20212
     }
 
20213
 
 
20214
+    LEAVE_BUFFERED(self)
 
20215
     return res;
 
20216
 }
 
20217
 
 
20218
@@ -833,13 +857,6 @@
 
20219
     if (!ENTER_BUFFERED(self))
 
20220
         return NULL;
 
20221
     
 
20222
-    if (self->writable) {
 
20223
-        res = _bufferedwriter_flush_unlocked(self, 1);
 
20224
-        if (res == NULL)
 
20225
-            goto end;
 
20226
-        Py_CLEAR(res);
 
20227
-    }
 
20228
-
 
20229
     /* Return up to n bytes.  If at least one byte is buffered, we
 
20230
        only return buffered bytes.  Otherwise, we do one raw read. */
 
20231
 
 
20232
@@ -859,6 +876,13 @@
 
20233
         goto end;
 
20234
     }
 
20235
 
 
20236
+    if (self->writable) {
 
20237
+        res = buffered_flush_and_rewind_unlocked(self);
 
20238
+        if (res == NULL)
 
20239
+            goto end;
 
20240
+        Py_DECREF(res);
 
20241
+    }
 
20242
+
 
20243
     /* Fill the buffer from the raw stream, and copy it to the result. */
 
20244
     _bufferedreader_reset_buf(self);
 
20245
     r = _bufferedreader_fill_buffer(self);
 
20246
@@ -881,24 +905,10 @@
 
20247
 static PyObject *
 
20248
 buffered_readinto(buffered *self, PyObject *args)
 
20249
 {
 
20250
-    PyObject *res = NULL;
 
20251
-
 
20252
     CHECK_INITIALIZED(self)
 
20253
     
 
20254
-    /* TODO: use raw.readinto() instead! */
 
20255
-    if (self->writable) {
 
20256
-        if (!ENTER_BUFFERED(self))
 
20257
-            return NULL;
 
20258
-        res = _bufferedwriter_flush_unlocked(self, 0);
 
20259
-        LEAVE_BUFFERED(self)
 
20260
-        if (res == NULL)
 
20261
-            goto end;
 
20262
-        Py_DECREF(res);
 
20263
-    }
 
20264
-    res = bufferediobase_readinto((PyObject *)self, args);
 
20265
-
 
20266
-end:
 
20267
-    return res;
 
20268
+    /* TODO: use raw.readinto() (or a direct copy from our buffer) instead! */
 
20269
+    return bufferediobase_readinto((PyObject *)self, args);
 
20270
 }
 
20271
 
 
20272
 static PyObject *
 
20273
@@ -936,12 +946,6 @@
 
20274
         goto end_unlocked;
 
20275
 
 
20276
     /* Now we try to get some more from the raw stream */
 
20277
-    if (self->writable) {
 
20278
-        res = _bufferedwriter_flush_unlocked(self, 1);
 
20279
-        if (res == NULL)
 
20280
-            goto end;
 
20281
-        Py_CLEAR(res);
 
20282
-    }
 
20283
     chunks = PyList_New(0);
 
20284
     if (chunks == NULL)
 
20285
         goto end;
 
20286
@@ -955,9 +959,16 @@
 
20287
         }
 
20288
         Py_CLEAR(res);
 
20289
         written += n;
 
20290
+        self->pos += n;
 
20291
         if (limit >= 0)
 
20292
             limit -= n;
 
20293
     }
 
20294
+    if (self->writable) {
 
20295
+        PyObject *r = buffered_flush_and_rewind_unlocked(self);
 
20296
+        if (r == NULL)
 
20297
+            goto end;
 
20298
+        Py_DECREF(r);
 
20299
+    }
 
20300
 
 
20301
     for (;;) {
 
20302
         _bufferedreader_reset_buf(self);
 
20303
@@ -1088,7 +1099,7 @@
 
20304
 
 
20305
     /* Fallback: invoke raw seek() method and clear buffer */
 
20306
     if (self->writable) {
 
20307
-        res = _bufferedwriter_flush_unlocked(self, 0);
 
20308
+        res = _bufferedwriter_flush_unlocked(self);
 
20309
         if (res == NULL)
 
20310
             goto end;
 
20311
         Py_CLEAR(res);
 
20312
@@ -1126,20 +1137,11 @@
 
20313
         return NULL;
 
20314
 
 
20315
     if (self->writable) {
 
20316
-        res = _bufferedwriter_flush_unlocked(self, 0);
 
20317
+        res = buffered_flush_and_rewind_unlocked(self);
 
20318
         if (res == NULL)
 
20319
             goto end;
 
20320
         Py_CLEAR(res);
 
20321
     }
 
20322
-    if (self->readable) {
 
20323
-        if (pos == Py_None) {
 
20324
-            /* Rewind the raw stream so that its position corresponds to
 
20325
-               the current logical position. */
 
20326
-            if (_buffered_raw_seek(self, -RAW_OFFSET(self), 1) == -1)
 
20327
-                goto end;
 
20328
-        }
 
20329
-        _bufferedreader_reset_buf(self);
 
20330
-    }
 
20331
     res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_truncate, pos, NULL);
 
20332
     if (res == NULL)
 
20333
         goto end;
 
20334
@@ -1341,17 +1343,18 @@
 
20335
             Py_DECREF(chunks);
 
20336
             return NULL;
 
20337
         }
 
20338
+        self->pos += current_size;
 
20339
     }
 
20340
-    _bufferedreader_reset_buf(self);
 
20341
     /* We're going past the buffer's bounds, flush it */
 
20342
     if (self->writable) {
 
20343
-        res = _bufferedwriter_flush_unlocked(self, 1);
 
20344
+        res = buffered_flush_and_rewind_unlocked(self);
 
20345
         if (res == NULL) {
 
20346
             Py_DECREF(chunks);
 
20347
             return NULL;
 
20348
         }
 
20349
         Py_CLEAR(res);
 
20350
     }
 
20351
+    _bufferedreader_reset_buf(self);
 
20352
     while (1) {
 
20353
         if (data) {
 
20354
             if (PyList_Append(chunks, data) < 0) {
 
20355
@@ -1434,6 +1437,14 @@
 
20356
         memcpy(out, self->buffer + self->pos, current_size);
 
20357
         remaining -= current_size;
 
20358
         written += current_size;
 
20359
+        self->pos += current_size;
 
20360
+    }
 
20361
+    /* Flush the write buffer if necessary */
 
20362
+    if (self->writable) {
 
20363
+        PyObject *r = buffered_flush_and_rewind_unlocked(self);
 
20364
+        if (r == NULL)
 
20365
+            goto error;
 
20366
+        Py_DECREF(r);
 
20367
     }
 
20368
     _bufferedreader_reset_buf(self);
 
20369
     while (remaining > 0) {
 
20370
@@ -1684,6 +1695,7 @@
 
20371
     Py_buffer buf;
 
20372
     PyObject *memobj, *res;
 
20373
     Py_ssize_t n;
 
20374
+    int errnum;
 
20375
     /* NOTE: the buffer needn't be released as its object is NULL. */
 
20376
     if (PyBuffer_FillInfo(&buf, NULL, start, len, 1, PyBUF_CONTIG_RO) == -1)
 
20377
         return -1;
 
20378
@@ -1696,11 +1708,21 @@
 
20379
        raised (see issue #10956).
 
20380
     */
 
20381
     do {
 
20382
+        errno = 0;
 
20383
         res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_write, memobj, NULL);
 
20384
+        errnum = errno;
 
20385
     } while (res == NULL && _trap_eintr());
 
20386
     Py_DECREF(memobj);
 
20387
     if (res == NULL)
 
20388
         return -1;
 
20389
+    if (res == Py_None) {
 
20390
+        /* Non-blocking stream would have blocked. Special return code!
 
20391
+           Being paranoid we reset errno in case it is changed by code
 
20392
+           triggered by a decref.  errno is used by _set_BlockingIOError(). */
 
20393
+        Py_DECREF(res);
 
20394
+        errno = errnum;
 
20395
+        return -2;
 
20396
+    }
 
20397
     n = PyNumber_AsSsize_t(res, PyExc_ValueError);
 
20398
     Py_DECREF(res);
 
20399
     if (n < 0 || n > len) {
 
20400
@@ -1717,7 +1739,7 @@
 
20401
 /* `restore_pos` is 1 if we need to restore the raw stream position at
 
20402
    the end, 0 otherwise. */
 
20403
 static PyObject *
 
20404
-_bufferedwriter_flush_unlocked(buffered *self, int restore_pos)
 
20405
+_bufferedwriter_flush_unlocked(buffered *self)
 
20406
 {
 
20407
     Py_ssize_t written = 0;
 
20408
     Py_off_t n, rewind;
 
20409
@@ -1739,14 +1761,11 @@
 
20410
             Py_SAFE_DOWNCAST(self->write_end - self->write_pos,
 
20411
                              Py_off_t, Py_ssize_t));
 
20412
         if (n == -1) {
 
20413
-            Py_ssize_t *w = _buffered_check_blocking_error();
 
20414
-            if (w == NULL)
 
20415
-                goto error;
 
20416
-            self->write_pos += *w;
 
20417
-            self->raw_pos = self->write_pos;
 
20418
-            written += *w;
 
20419
-            *w = written;
 
20420
-            /* Already re-raised */
 
20421
+            goto error;
 
20422
+        }
 
20423
+        else if (n == -2) {
 
20424
+            _set_BlockingIOError("write could not complete without blocking",
 
20425
+                                 0);
 
20426
             goto error;
 
20427
         }
 
20428
         self->write_pos += n;
 
20429
@@ -1759,16 +1778,6 @@
 
20430
             goto error;
 
20431
     }
 
20432
 
 
20433
-    if (restore_pos) {
 
20434
-        Py_off_t forward = rewind - written;
 
20435
-        if (forward != 0) {
 
20436
-            n = _buffered_raw_seek(self, forward, 1);
 
20437
-            if (n < 0) {
 
20438
-                goto error;
 
20439
-            }
 
20440
-            self->raw_pos += forward;
 
20441
-        }
 
20442
-    }
 
20443
     _bufferedwriter_reset_buf(self);
 
20444
 
 
20445
 end:
 
20446
@@ -1821,7 +1830,7 @@
 
20447
     }
 
20448
 
 
20449
     /* First write the current buffer */
 
20450
-    res = _bufferedwriter_flush_unlocked(self, 0);
 
20451
+    res = _bufferedwriter_flush_unlocked(self);
 
20452
     if (res == NULL) {
 
20453
         Py_ssize_t *w = _buffered_check_blocking_error();
 
20454
         if (w == NULL)
 
20455
@@ -1844,14 +1853,19 @@
 
20456
             PyErr_Clear();
 
20457
             memcpy(self->buffer + self->write_end, buf.buf, buf.len);
 
20458
             self->write_end += buf.len;
 
20459
+            self->pos += buf.len;
 
20460
             written = buf.len;
 
20461
             goto end;
 
20462
         }
 
20463
         /* Buffer as much as possible. */
 
20464
         memcpy(self->buffer + self->write_end, buf.buf, avail);
 
20465
         self->write_end += avail;
 
20466
-        /* Already re-raised */
 
20467
-        *w = avail;
 
20468
+        self->pos += avail;
 
20469
+        /* XXX Modifying the existing exception e using the pointer w
 
20470
+           will change e.characters_written but not e.args[2].
 
20471
+           Therefore we just replace with a new error. */
 
20472
+        _set_BlockingIOError("write could not complete without blocking",
 
20473
+                             avail);
 
20474
         goto error;
 
20475
     }
 
20476
     Py_CLEAR(res);
 
20477
@@ -1876,11 +1890,9 @@
 
20478
         Py_ssize_t n = _bufferedwriter_raw_write(
 
20479
             self, (char *) buf.buf + written, buf.len - written);
 
20480
         if (n == -1) {
 
20481
-            Py_ssize_t *w = _buffered_check_blocking_error();
 
20482
-            if (w == NULL)
 
20483
-                goto error;
 
20484
-            written += *w;
 
20485
-            remaining -= *w;
 
20486
+            goto error;
 
20487
+        } else if (n == -2) {
 
20488
+            /* Write failed because raw file is non-blocking */
 
20489
             if (remaining > self->buffer_size) {
 
20490
                 /* Can't buffer everything, still buffer as much as possible */
 
20491
                 memcpy(self->buffer,
 
20492
@@ -1888,8 +1900,9 @@
 
20493
                 self->raw_pos = 0;
 
20494
                 ADJUST_POSITION(self, self->buffer_size);
 
20495
                 self->write_end = self->buffer_size;
 
20496
-                *w = written + self->buffer_size;
 
20497
-                /* Already re-raised */
 
20498
+                written += self->buffer_size;
 
20499
+                _set_BlockingIOError("write could not complete without "
 
20500
+                                     "blocking", written);
 
20501
                 goto error;
 
20502
             }
 
20503
             PyErr_Clear();
 
20504
@@ -2180,6 +2193,11 @@
 
20505
 static PyObject *
 
20506
 bufferedrwpair_closed_get(rwpair *self, void *context)
 
20507
 {
 
20508
+    if (self->writer == NULL) {
 
20509
+        PyErr_SetString(PyExc_RuntimeError,
 
20510
+                "the BufferedRWPair object is being garbage-collected");
 
20511
+        return NULL;
 
20512
+    }
 
20513
     return PyObject_GetAttr((PyObject *) self->writer, _PyIO_str_closed);
 
20514
 }
 
20515
 
8307
20516
diff -r 8527427914a2 Modules/_io/fileio.c
8308
20517
--- a/Modules/_io/fileio.c
8309
20518
+++ b/Modules/_io/fileio.c
8310
 
@@ -474,7 +474,7 @@
 
20519
@@ -42,12 +42,6 @@
 
20520
 #define SMALLCHUNK BUFSIZ
 
20521
 #endif
 
20522
 
 
20523
-#if SIZEOF_INT < 4
 
20524
-#define BIGCHUNK  (512 * 32)
 
20525
-#else
 
20526
-#define BIGCHUNK  (512 * 1024)
 
20527
-#endif
 
20528
-
 
20529
 typedef struct {
 
20530
     PyObject_HEAD
 
20531
     int fd;
 
20532
@@ -474,7 +468,7 @@
8311
20533
 fileio_readinto(fileio *self, PyObject *args)
8312
20534
 {
8313
20535
     Py_buffer pbuf;
8316
20538
 
8317
20539
     if (self->fd < 0)
8318
20540
         return err_closed();
8319
 
@@ -485,9 +485,16 @@
 
20541
@@ -485,9 +479,16 @@
8320
20542
         return NULL;
8321
20543
 
8322
20544
     if (_PyVerify_fd(self->fd)) {
8334
20556
         Py_END_ALLOW_THREADS
8335
20557
     } else
8336
20558
         n = -1;
8337
 
@@ -620,6 +627,10 @@
 
20559
@@ -521,15 +522,10 @@
 
20560
         }
 
20561
     }
 
20562
 #endif
 
20563
-    if (currentsize > SMALLCHUNK) {
 
20564
-        /* Keep doubling until we reach BIGCHUNK;
 
20565
-           then keep adding BIGCHUNK. */
 
20566
-        if (currentsize <= BIGCHUNK)
 
20567
-            return currentsize + currentsize;
 
20568
-        else
 
20569
-            return currentsize + BIGCHUNK;
 
20570
-    }
 
20571
-    return currentsize + SMALLCHUNK;
 
20572
+    /* Expand the buffer by an amount proportional to the current size,
 
20573
+       giving us amortized linear-time behavior. Use a less-than-double
 
20574
+       growth factor to avoid excessive allocation. */
 
20575
+    return currentsize + (currentsize >> 3) + 6;
 
20576
 }
 
20577
 
 
20578
 static PyObject *
 
20579
@@ -620,6 +616,10 @@
8338
20580
         return fileio_readall(self);
8339
20581
     }
8340
20582
 
8345
20587
     bytes = PyBytes_FromStringAndSize(NULL, size);
8346
20588
     if (bytes == NULL)
8347
20589
         return NULL;
8348
 
@@ -628,7 +639,11 @@
 
20590
@@ -628,7 +628,11 @@
8349
20591
     if (_PyVerify_fd(self->fd)) {
8350
20592
         Py_BEGIN_ALLOW_THREADS
8351
20593
         errno = 0;
8357
20599
         Py_END_ALLOW_THREADS
8358
20600
     } else
8359
20601
         n = -1;
8360
 
@@ -655,7 +670,7 @@
 
20602
@@ -655,7 +659,7 @@
8361
20603
 fileio_write(fileio *self, PyObject *args)
8362
20604
 {
8363
20605
     Py_buffer pbuf;
8366
20608
 
8367
20609
     if (self->fd < 0)
8368
20610
         return err_closed();
8369
 
@@ -668,7 +683,14 @@
 
20611
@@ -668,7 +672,14 @@
8370
20612
     if (_PyVerify_fd(self->fd)) {
8371
20613
         Py_BEGIN_ALLOW_THREADS
8372
20614
         errno = 0;
8394
20636
                      Py_TYPE(obj)->tp_name);
8395
20637
         return NULL;
8396
20638
     }
 
20639
diff -r 8527427914a2 Modules/_multiprocessing/multiprocessing.c
 
20640
--- a/Modules/_multiprocessing/multiprocessing.c
 
20641
+++ b/Modules/_multiprocessing/multiprocessing.c
 
20642
@@ -97,32 +97,38 @@
 
20643
 /* Functions for transferring file descriptors between processes.
 
20644
    Reimplements some of the functionality of the fdcred
 
20645
    module at http://www.mca-ltd.com/resources/fdcred_1.tgz. */
 
20646
+/* Based in http://resin.csoft.net/cgi-bin/man.cgi?section=3&topic=CMSG_DATA */
 
20647
 
 
20648
 static PyObject *
 
20649
 multiprocessing_sendfd(PyObject *self, PyObject *args)
 
20650
 {
 
20651
     int conn, fd, res;
 
20652
+    struct iovec dummy_iov;
 
20653
     char dummy_char;
 
20654
-    char buf[CMSG_SPACE(sizeof(int))];
 
20655
-    struct msghdr msg = {0};
 
20656
-    struct iovec dummy_iov;
 
20657
+    struct msghdr msg;
 
20658
     struct cmsghdr *cmsg;
 
20659
+    union {
 
20660
+        struct cmsghdr hdr;
 
20661
+        unsigned char buf[CMSG_SPACE(sizeof(int))];
 
20662
+    } cmsgbuf;
 
20663
 
 
20664
     if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
 
20665
         return NULL;
 
20666
 
 
20667
     dummy_iov.iov_base = &dummy_char;
 
20668
     dummy_iov.iov_len = 1;
 
20669
-    msg.msg_control = buf;
 
20670
-    msg.msg_controllen = sizeof(buf);
 
20671
+
 
20672
+    memset(&msg, 0, sizeof(msg));
 
20673
+    msg.msg_control = &cmsgbuf.buf;
 
20674
+    msg.msg_controllen = sizeof(cmsgbuf.buf);
 
20675
     msg.msg_iov = &dummy_iov;
 
20676
     msg.msg_iovlen = 1;
 
20677
+
 
20678
     cmsg = CMSG_FIRSTHDR(&msg);
 
20679
+    cmsg->cmsg_len = CMSG_LEN(sizeof(int));
 
20680
     cmsg->cmsg_level = SOL_SOCKET;
 
20681
     cmsg->cmsg_type = SCM_RIGHTS;
 
20682
-    cmsg->cmsg_len = CMSG_LEN(sizeof(int));
 
20683
-    msg.msg_controllen = cmsg->cmsg_len;
 
20684
-    *CMSG_DATA(cmsg) = fd;
 
20685
+    * (int *) CMSG_DATA(cmsg) = fd;
 
20686
 
 
20687
     Py_BEGIN_ALLOW_THREADS
 
20688
     res = sendmsg(conn, &msg, 0);
 
20689
@@ -138,20 +144,26 @@
 
20690
 {
 
20691
     int conn, fd, res;
 
20692
     char dummy_char;
 
20693
-    char buf[CMSG_SPACE(sizeof(int))];
 
20694
+    struct iovec dummy_iov;
 
20695
     struct msghdr msg = {0};
 
20696
-    struct iovec dummy_iov;
 
20697
     struct cmsghdr *cmsg;
 
20698
+    union {
 
20699
+        struct cmsghdr hdr;
 
20700
+        unsigned char buf[CMSG_SPACE(sizeof(int))];
 
20701
+    } cmsgbuf;
 
20702
 
 
20703
     if (!PyArg_ParseTuple(args, "i", &conn))
 
20704
         return NULL;
 
20705
 
 
20706
     dummy_iov.iov_base = &dummy_char;
 
20707
     dummy_iov.iov_len = 1;
 
20708
-    msg.msg_control = buf;
 
20709
-    msg.msg_controllen = sizeof(buf);
 
20710
+
 
20711
+    memset(&msg, 0, sizeof(msg));
 
20712
+    msg.msg_control = &cmsgbuf.buf;
 
20713
+    msg.msg_controllen = sizeof(cmsgbuf.buf);
 
20714
     msg.msg_iov = &dummy_iov;
 
20715
     msg.msg_iovlen = 1;
 
20716
+
 
20717
     cmsg = CMSG_FIRSTHDR(&msg);
 
20718
     cmsg->cmsg_level = SOL_SOCKET;
 
20719
     cmsg->cmsg_type = SCM_RIGHTS;
 
20720
@@ -165,7 +177,18 @@
 
20721
     if (res < 0)
 
20722
         return PyErr_SetFromErrno(PyExc_OSError);
 
20723
 
 
20724
-    fd = *CMSG_DATA(cmsg);
 
20725
+    if (msg.msg_controllen < CMSG_LEN(sizeof(int)) ||
 
20726
+        (cmsg = CMSG_FIRSTHDR(&msg)) == NULL ||
 
20727
+        cmsg->cmsg_level != SOL_SOCKET ||
 
20728
+        cmsg->cmsg_type != SCM_RIGHTS ||
 
20729
+        cmsg->cmsg_len < CMSG_LEN(sizeof(int))) {
 
20730
+        /* If at least one control message is present, there should be
 
20731
+           no room for any further data in the buffer. */
 
20732
+        PyErr_SetString(PyExc_RuntimeError, "No file descriptor received");
 
20733
+        return NULL;
 
20734
+    }
 
20735
+
 
20736
+    fd = * (int *) CMSG_DATA(cmsg);
 
20737
     return Py_BuildValue("i", fd);
 
20738
 }
 
20739
 
 
20740
diff -r 8527427914a2 Modules/_sqlite/cursor.c
 
20741
--- a/Modules/_sqlite/cursor.c
 
20742
+++ b/Modules/_sqlite/cursor.c
 
20743
@@ -55,8 +55,8 @@
 
20744
 
 
20745
     dst = buf;
 
20746
     *dst = 0;
 
20747
-    while (isalpha(*src) && dst - buf < sizeof(buf) - 2) {
 
20748
-        *dst++ = tolower(*src++);
 
20749
+    while (Py_ISALPHA(*src) && dst - buf < sizeof(buf) - 2) {
 
20750
+        *dst++ = Py_TOLOWER(*src++);
 
20751
     }
 
20752
 
 
20753
     *dst = 0;
 
20754
diff -r 8527427914a2 Modules/_sre.c
 
20755
--- a/Modules/_sre.c
 
20756
+++ b/Modules/_sre.c
 
20757
@@ -2744,7 +2744,7 @@
 
20758
 #if defined(VVERBOSE)
 
20759
 #define VTRACE(v) printf v
 
20760
 #else
 
20761
-#define VTRACE(v)
 
20762
+#define VTRACE(v) do {} while(0)  /* do nothing */
 
20763
 #endif
 
20764
 
 
20765
 /* Report failure */
 
20766
diff -r 8527427914a2 Modules/_ssl.c
 
20767
--- a/Modules/_ssl.c
 
20768
+++ b/Modules/_ssl.c
 
20769
@@ -702,7 +702,7 @@
 
20770
     /* get a memory buffer */
 
20771
     biobuf = BIO_new(BIO_s_mem());
 
20772
 
 
20773
-    i = 0;
 
20774
+    i = -1;
 
20775
     while ((i = X509_get_ext_by_NID(
 
20776
                     certificate, NID_subject_alt_name, i)) >= 0) {
 
20777
 
 
20778
@@ -798,6 +798,7 @@
 
20779
             }
 
20780
             Py_DECREF(t);
 
20781
         }
 
20782
+        sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
 
20783
     }
 
20784
     BIO_free(biobuf);
 
20785
     if (peer_alt_names != Py_None) {
 
20786
@@ -1145,10 +1146,8 @@
 
20787
 #endif
 
20788
 
 
20789
     /* Guard against socket too large for select*/
 
20790
-#ifndef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
 
20791
-    if (s->sock_fd >= FD_SETSIZE)
 
20792
+    if (!_PyIsSelectable_fd(s->sock_fd))
 
20793
         return SOCKET_TOO_LARGE_FOR_SELECT;
 
20794
-#endif
 
20795
 
 
20796
     /* Construct the arguments to select */
 
20797
     tv.tv_sec = (int)s->sock_timeout;
 
20798
diff -r 8527427914a2 Modules/_testcapimodule.c
 
20799
--- a/Modules/_testcapimodule.c
 
20800
+++ b/Modules/_testcapimodule.c
 
20801
@@ -1106,6 +1106,41 @@
 
20802
 }
 
20803
 
 
20804
 static PyObject *
 
20805
+unicode_encodedecimal(PyObject *self, PyObject *args)
 
20806
+{
 
20807
+    Py_UNICODE *unicode;
 
20808
+    int length;
 
20809
+    char *errors = NULL;
 
20810
+    PyObject *decimal;
 
20811
+    Py_ssize_t decimal_length, new_length;
 
20812
+    int res;
 
20813
+
 
20814
+    if (!PyArg_ParseTuple(args, "u#|s", &unicode, &length, &errors))
 
20815
+        return NULL;
 
20816
+
 
20817
+    decimal_length = length * 7; /* len('&#8364;') */
 
20818
+    decimal = PyBytes_FromStringAndSize(NULL, decimal_length);
 
20819
+    if (decimal == NULL)
 
20820
+        return NULL;
 
20821
+
 
20822
+    res = PyUnicode_EncodeDecimal(unicode, length,
 
20823
+                                  PyBytes_AS_STRING(decimal),
 
20824
+                                  errors);
 
20825
+    if (res < 0) {
 
20826
+        Py_DECREF(decimal);
 
20827
+        return NULL;
 
20828
+    }
 
20829
+
 
20830
+    new_length = strlen(PyBytes_AS_STRING(decimal));
 
20831
+    assert(new_length <= decimal_length);
 
20832
+    res = _PyBytes_Resize(&decimal, new_length);
 
20833
+    if (res < 0)
 
20834
+        return NULL;
 
20835
+
 
20836
+    return decimal;
 
20837
+}
 
20838
+
 
20839
+static PyObject *
 
20840
 test_empty_argparse(PyObject *self)
 
20841
 {
 
20842
     /* Test that formats can begin with '|'. See issue #4720. */
 
20843
@@ -1639,6 +1674,19 @@
 
20844
     return PyErr_NewExceptionWithDoc(name, doc, base, dict);
 
20845
 }
 
20846
 
 
20847
+static PyObject *
 
20848
+sequence_delitem(PyObject *self, PyObject *args)
 
20849
+{
 
20850
+    PyObject *seq;
 
20851
+    Py_ssize_t i;
 
20852
+
 
20853
+    if (!PyArg_ParseTuple(args, "On", &seq, &i))
 
20854
+        return NULL;
 
20855
+    if (PySequence_DelItem(seq, i) < 0)
 
20856
+        return NULL;
 
20857
+    Py_RETURN_NONE;
 
20858
+}
 
20859
+
 
20860
 static PyMethodDef TestMethods[] = {
 
20861
     {"raise_exception",         raise_exception,                 METH_VARARGS},
 
20862
     {"test_config",             (PyCFunction)test_config,        METH_NOARGS},
 
20863
@@ -1685,6 +1733,7 @@
 
20864
 #ifdef Py_USING_UNICODE
 
20865
     {"test_u_code",             (PyCFunction)test_u_code,        METH_NOARGS},
 
20866
     {"test_widechar",           (PyCFunction)test_widechar,      METH_NOARGS},
 
20867
+    {"unicode_encodedecimal",   unicode_encodedecimal,           METH_VARARGS},
 
20868
 #endif
 
20869
 #ifdef WITH_THREAD
 
20870
     {"_test_thread_state",  test_thread_state,                   METH_VARARGS},
 
20871
@@ -1695,6 +1744,7 @@
 
20872
     {"code_newempty", code_newempty,                     METH_VARARGS},
 
20873
     {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
 
20874
      METH_VARARGS | METH_KEYWORDS},
 
20875
+    {"sequence_delitem", (PyCFunction)sequence_delitem, METH_VARARGS},
 
20876
     {NULL, NULL} /* sentinel */
 
20877
 };
 
20878
 
 
20879
diff -r 8527427914a2 Modules/_tkinter.c
 
20880
--- a/Modules/_tkinter.c
 
20881
+++ b/Modules/_tkinter.c
 
20882
@@ -663,8 +663,8 @@
 
20883
     }
 
20884
 
 
20885
     strcpy(argv0, className);
 
20886
-    if (isupper(Py_CHARMASK(argv0[0])))
 
20887
-        argv0[0] = tolower(Py_CHARMASK(argv0[0]));
 
20888
+    if (Py_ISUPPER(Py_CHARMASK(argv0[0])))
 
20889
+        argv0[0] = Py_TOLOWER(Py_CHARMASK(argv0[0]));
 
20890
     Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
 
20891
     ckfree(argv0);
 
20892
 
 
20893
diff -r 8527427914a2 Modules/binascii.c
 
20894
--- a/Modules/binascii.c
 
20895
+++ b/Modules/binascii.c
 
20896
@@ -1105,8 +1105,8 @@
 
20897
     if (isdigit(c))
 
20898
         return c - '0';
 
20899
     else {
 
20900
-        if (isupper(c))
 
20901
-            c = tolower(c);
 
20902
+        if (Py_ISUPPER(c))
 
20903
+            c = Py_TOLOWER(c);
 
20904
         if (c >= 'a' && c <= 'f')
 
20905
             return c - 'a' + 10;
 
20906
     }
 
20907
diff -r 8527427914a2 Modules/bz2module.c
 
20908
--- a/Modules/bz2module.c
 
20909
+++ b/Modules/bz2module.c
 
20910
@@ -224,25 +224,14 @@
 
20911
 #define SMALLCHUNK BUFSIZ
 
20912
 #endif
 
20913
 
 
20914
-#if SIZEOF_INT < 4
 
20915
-#define BIGCHUNK  (512 * 32)
 
20916
-#else
 
20917
-#define BIGCHUNK  (512 * 1024)
 
20918
-#endif
 
20919
-
 
20920
 /* This is a hacked version of Python's fileobject.c:new_buffersize(). */
 
20921
 static size_t
 
20922
 Util_NewBufferSize(size_t currentsize)
 
20923
 {
 
20924
-    if (currentsize > SMALLCHUNK) {
 
20925
-        /* Keep doubling until we reach BIGCHUNK;
 
20926
-           then keep adding BIGCHUNK. */
 
20927
-        if (currentsize <= BIGCHUNK)
 
20928
-            return currentsize + currentsize;
 
20929
-        else
 
20930
-            return currentsize + BIGCHUNK;
 
20931
-    }
 
20932
-    return currentsize + SMALLCHUNK;
 
20933
+    /* Expand the buffer by an amount proportional to the current size,
 
20934
+       giving us amortized linear-time behavior. Use a less-than-double
 
20935
+       growth factor to avoid excessive allocation. */
 
20936
+    return currentsize + (currentsize >> 3) + 6;
 
20937
 }
 
20938
 
 
20939
 /* This is a hacked version of Python's fileobject.c:get_line(). */
 
20940
diff -r 8527427914a2 Modules/cPickle.c
 
20941
--- a/Modules/cPickle.c
 
20942
+++ b/Modules/cPickle.c
 
20943
@@ -2697,11 +2697,6 @@
 
20944
         }
 
20945
     }
 
20946
 
 
20947
-    if (PyType_IsSubtype(type, &PyType_Type)) {
 
20948
-        res = save_global(self, args, NULL);
 
20949
-        goto finally;
 
20950
-    }
 
20951
-
 
20952
     /* Get a reduction callable, and call it.  This may come from
 
20953
      * copy_reg.dispatch_table, the object's __reduce_ex__ method,
 
20954
      * or the object's __reduce__ method.
 
20955
@@ -2717,6 +2712,11 @@
 
20956
         }
 
20957
     }
 
20958
     else {
 
20959
+        if (PyType_IsSubtype(type, &PyType_Type)) {
 
20960
+            res = save_global(self, args, NULL);
 
20961
+            goto finally;
 
20962
+        }
 
20963
+
 
20964
         /* Check for a __reduce_ex__ method. */
 
20965
         __reduce__ = PyObject_GetAttr(args, __reduce_ex___str);
 
20966
         if (__reduce__ != NULL) {
 
20967
diff -r 8527427914a2 Modules/cStringIO.c
 
20968
--- a/Modules/cStringIO.c
 
20969
+++ b/Modules/cStringIO.c
 
20970
@@ -661,7 +661,11 @@
 
20971
   char *buf;
 
20972
   Py_ssize_t size;
 
20973
 
 
20974
-  if (PyObject_AsReadBuffer(s, (const void **)&buf, &size)) {
 
20975
+  if (PyUnicode_Check(s)) {
 
20976
+    if (PyObject_AsCharBuffer(s, (const char **)&buf, &size) != 0)
 
20977
+      return NULL;
 
20978
+  }
 
20979
+  else if (PyObject_AsReadBuffer(s, (const void **)&buf, &size)) {
 
20980
     PyErr_Format(PyExc_TypeError, "expected read buffer, %.200s found",
 
20981
                  s->ob_type->tp_name);
 
20982
     return NULL;
8397
20983
diff -r 8527427914a2 Modules/cjkcodecs/_codecs_hk.c
8398
20984
--- a/Modules/cjkcodecs/_codecs_hk.c
8399
20985
+++ b/Modules/cjkcodecs/_codecs_hk.c
8519
21105
 
8520
21106
         if (c == 0x8e) {
8521
21107
             /* JIS X 0201 half-width katakana */
 
21108
diff -r 8527427914a2 Modules/itertoolsmodule.c
 
21109
--- a/Modules/itertoolsmodule.c
 
21110
+++ b/Modules/itertoolsmodule.c
 
21111
@@ -1234,7 +1234,9 @@
 
21112
         return NULL;
 
21113
     lz->cnt++;
 
21114
     oldnext = lz->next;
 
21115
-    lz->next += lz->step;
 
21116
+    /* The (size_t) cast below avoids the danger of undefined
 
21117
+       behaviour from signed integer overflow. */
 
21118
+    lz->next += (size_t)lz->step;
 
21119
     if (lz->next < oldnext || (stop != -1 && lz->next > stop))
 
21120
         lz->next = stop;
 
21121
     return item;
8522
21122
diff -r 8527427914a2 Modules/mmapmodule.c
8523
21123
--- a/Modules/mmapmodule.c
8524
21124
+++ b/Modules/mmapmodule.c
8537
21137
             map_size = calc_size;
8538
21138
             if (map_size != calc_size) {
8539
21139
                 PyErr_SetString(PyExc_ValueError,
 
21140
diff -r 8527427914a2 Modules/ossaudiodev.c
 
21141
--- a/Modules/ossaudiodev.c
 
21142
+++ b/Modules/ossaudiodev.c
 
21143
@@ -129,6 +129,7 @@
 
21144
     }
 
21145
 
 
21146
     if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
 
21147
+        close(fd);
 
21148
         PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename);
 
21149
         return NULL;
 
21150
     }
 
21151
@@ -425,6 +426,11 @@
 
21152
     if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
 
21153
         return NULL;
 
21154
 
 
21155
+    if (!_PyIsSelectable_fd(self->fd)) {
 
21156
+        PyErr_SetString(PyExc_ValueError,
 
21157
+                        "file descriptor out of range for select");
 
21158
+        return NULL;
 
21159
+    }
 
21160
     /* use select to wait for audio device to be available */
 
21161
     FD_ZERO(&write_set_fds);
 
21162
     FD_SET(self->fd, &write_set_fds);
8540
21163
diff -r 8527427914a2 Modules/posixmodule.c
8541
21164
--- a/Modules/posixmodule.c
8542
21165
+++ b/Modules/posixmodule.c
8671
21294
     Py_END_ALLOW_THREADS
8672
21295
     PyBuffer_Release(&pbuf);
8673
21296
     if (size < 0)
8674
 
@@ -8968,6 +9011,7 @@
 
21297
@@ -6951,6 +6994,14 @@
 
21298
 
 
21299
     /* XXX This can leak memory -- not easy to fix :-( */
 
21300
     len = strlen(s1) + strlen(s2) + 2;
 
21301
+#ifdef MS_WINDOWS
 
21302
+    if (_MAX_ENV < (len - 1)) {
 
21303
+        PyErr_Format(PyExc_ValueError,
 
21304
+                     "the environment variable is longer than %u bytes",
 
21305
+                     _MAX_ENV);
 
21306
+        return NULL;
 
21307
+    }
 
21308
+#endif
 
21309
     /* len includes space for a trailing \0; the size arg to
 
21310
        PyString_FromStringAndSize does not count that */
 
21311
     newstr = PyString_FromStringAndSize(NULL, (int)len - 1);
 
21312
@@ -6993,11 +7044,20 @@
 
21313
 posix_unsetenv(PyObject *self, PyObject *args)
 
21314
 {
 
21315
     char *s1;
 
21316
+#ifndef HAVE_BROKEN_UNSETENV
 
21317
+    int err;
 
21318
+#endif
 
21319
 
 
21320
     if (!PyArg_ParseTuple(args, "s:unsetenv", &s1))
 
21321
         return NULL;
 
21322
 
 
21323
+#ifdef HAVE_BROKEN_UNSETENV
 
21324
     unsetenv(s1);
 
21325
+#else
 
21326
+    err = unsetenv(s1);
 
21327
+    if (err)
 
21328
+        return posix_error();
 
21329
+#endif
 
21330
 
 
21331
     /* Remove the key from posix_putenv_garbage;
 
21332
      * this will cause it to be collected.  This has to
 
21333
@@ -8968,6 +9028,7 @@
8675
21334
     {"abort",           posix_abort, METH_NOARGS, posix_abort__doc__},
8676
21335
 #ifdef MS_WINDOWS
8677
21336
     {"_getfullpathname",        posix__getfullpathname, METH_VARARGS, NULL},
8682
21341
diff -r 8527427914a2 Modules/selectmodule.c
8683
21342
--- a/Modules/selectmodule.c
8684
21343
+++ b/Modules/selectmodule.c
8685
 
@@ -912,7 +912,7 @@
 
21344
@@ -114,7 +114,7 @@
 
21345
 #if defined(_MSC_VER)
 
21346
         max = 0;                             /* not used for Win32 */
 
21347
 #else  /* !_MSC_VER */
 
21348
-        if (v < 0 || v >= FD_SETSIZE) {
 
21349
+        if (!_PyIsSelectable_fd(v)) {
 
21350
             PyErr_SetString(PyExc_ValueError,
 
21351
                         "filedescriptor out of range in select()");
 
21352
             goto finally;
 
21353
@@ -164,13 +164,6 @@
 
21354
     for (j = 0; fd2obj[j].sentinel >= 0; j++) {
 
21355
         fd = fd2obj[j].fd;
 
21356
         if (FD_ISSET(fd, set)) {
 
21357
-#ifndef _MSC_VER
 
21358
-            if (fd > FD_SETSIZE) {
 
21359
-                PyErr_SetString(PyExc_SystemError,
 
21360
-               "filedescriptor out of range returned in select()");
 
21361
-                goto finally;
 
21362
-            }
 
21363
-#endif
 
21364
             o = fd2obj[j].obj;
 
21365
             fd2obj[j].obj = NULL;
 
21366
             /* transfer ownership */
 
21367
@@ -912,7 +905,7 @@
8686
21368
 PyDoc_STRVAR(pyepoll_register_doc,
8687
21369
 "register(fd[, eventmask]) -> None\n\
8688
21370
 \n\
8691
21373
 fd is the target file descriptor of the operation.\n\
8692
21374
 events is a bit set composed of the various EPOLL constants; the default\n\
8693
21375
 is EPOLL_IN | EPOLL_OUT | EPOLL_PRI.\n\
 
21376
diff -r 8527427914a2 Modules/signalmodule.c
 
21377
--- a/Modules/signalmodule.c
 
21378
+++ b/Modules/signalmodule.c
 
21379
@@ -976,7 +976,6 @@
 
21380
 PyOS_AfterFork(void)
 
21381
 {
 
21382
 #ifdef WITH_THREAD
 
21383
-    _PyGILState_Reinit();
 
21384
     PyEval_ReInitThreads();
 
21385
     main_thread = PyThread_get_thread_ident();
 
21386
     main_pid = getpid();
8694
21387
diff -r 8527427914a2 Modules/socketmodule.c
8695
21388
--- a/Modules/socketmodule.c
8696
21389
+++ b/Modules/socketmodule.c
8697
 
@@ -1784,7 +1784,7 @@
 
21390
@@ -456,18 +456,14 @@
 
21391
 #include <sys/poll.h>
 
21392
 #endif
 
21393
 
 
21394
-#ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
 
21395
-/* Platform can select file descriptors beyond FD_SETSIZE */
 
21396
-#define IS_SELECTABLE(s) 1
 
21397
-#elif defined(HAVE_POLL)
 
21398
+#ifdef HAVE_POLL
 
21399
 /* Instead of select(), we'll use poll() since poll() works on any fd. */
 
21400
 #define IS_SELECTABLE(s) 1
 
21401
 /* Can we call select() with this socket without a buffer overrun? */
 
21402
 #else
 
21403
-/* POSIX says selecting file descriptors beyond FD_SETSIZE
 
21404
-   has undefined behaviour.  If there's no timeout left, we don't have to
 
21405
-   call select, so it's a safe, little white lie. */
 
21406
-#define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
 
21407
+/* If there's no timeout left, we don't have to call select, so it's a safe,
 
21408
+ * little white lie. */
 
21409
+#define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0.0)
 
21410
 #endif
 
21411
 
 
21412
 static PyObject*
 
21413
@@ -1784,7 +1780,7 @@
8698
21414
 PyDoc_STRVAR(gettimeout_doc,
8699
21415
 "gettimeout() -> timeout\n\
8700
21416
 \n\
8703
21419
 operations. A timeout of None indicates that timeouts on socket \n\
8704
21420
 operations are disabled.");
8705
21421
 
8706
 
@@ -4252,7 +4252,7 @@
 
21422
@@ -4252,7 +4248,7 @@
8707
21423
 PyDoc_STRVAR(getdefaulttimeout_doc,
8708
21424
 "getdefaulttimeout() -> timeout\n\
8709
21425
 \n\
8712
21428
 A value of None indicates that new socket objects have no timeout.\n\
8713
21429
 When the socket module is first imported, the default is None.");
8714
21430
 
8715
 
@@ -4282,7 +4282,7 @@
 
21431
@@ -4282,7 +4278,7 @@
8716
21432
 PyDoc_STRVAR(setdefaulttimeout_doc,
8717
21433
 "setdefaulttimeout(timeout)\n\
8718
21434
 \n\
8733
21449
 \n\
8734
21450
 This is synonymous to ``raise SystemExit''.  It will cause the current\n\
8735
21451
 thread to exit silently unless the exception is caught.");
 
21452
diff -r 8527427914a2 Modules/unicodedata.c
 
21453
--- a/Modules/unicodedata.c
 
21454
+++ b/Modules/unicodedata.c
 
21455
@@ -830,7 +830,7 @@
 
21456
     unsigned long h = 0;
 
21457
     unsigned long ix;
 
21458
     for (i = 0; i < len; i++) {
 
21459
-        h = (h * scale) + (unsigned char) toupper(Py_CHARMASK(s[i]));
 
21460
+        h = (h * scale) + (unsigned char) Py_TOUPPER(Py_CHARMASK(s[i]));
 
21461
         ix = h & 0xff000000;
 
21462
         if (ix)
 
21463
             h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff;
 
21464
@@ -978,7 +978,7 @@
 
21465
     if (!_getucname(self, code, buffer, sizeof(buffer)))
 
21466
         return 0;
 
21467
     for (i = 0; i < namelen; i++) {
 
21468
-        if (toupper(Py_CHARMASK(name[i])) != buffer[i])
 
21469
+        if (Py_TOUPPER(Py_CHARMASK(name[i])) != buffer[i])
 
21470
             return 0;
 
21471
     }
 
21472
     return buffer[namelen] == '\0';
 
21473
diff -r 8527427914a2 Modules/zlibmodule.c
 
21474
--- a/Modules/zlibmodule.c
 
21475
+++ b/Modules/zlibmodule.c
 
21476
@@ -72,7 +72,13 @@
 
21477
 static void
 
21478
 zlib_error(z_stream zst, int err, char *msg)
 
21479
 {
 
21480
-    const char *zmsg = zst.msg;
 
21481
+    const char *zmsg = Z_NULL;
 
21482
+    /* In case of a version mismatch, zst.msg won't be initialized.
 
21483
+       Check for this case first, before looking at zst.msg. */
 
21484
+    if (err == Z_VERSION_ERROR)
 
21485
+        zmsg = "library version mismatch";
 
21486
+    if (zmsg == Z_NULL)
 
21487
+        zmsg = zst.msg;
 
21488
     if (zmsg == Z_NULL) {
 
21489
         switch (err) {
 
21490
         case Z_BUF_ERROR:
 
21491
diff -r 8527427914a2 Objects/abstract.c
 
21492
--- a/Objects/abstract.c
 
21493
+++ b/Objects/abstract.c
 
21494
@@ -156,7 +156,7 @@
 
21495
                               "be integer, not '%.200s'", key);
 
21496
     }
 
21497
 
 
21498
-    return type_error("'%.200s' object is not subscriptable", o);
 
21499
+    return type_error("'%.200s' object has no attribute '__getitem__'", o);
 
21500
 }
 
21501
 
 
21502
 int
8736
21503
diff -r 8527427914a2 Objects/bytearrayobject.c
8737
21504
--- a/Objects/bytearrayobject.c
8738
21505
+++ b/Objects/bytearrayobject.c
8754
21521
 arguments start and end are interpreted as in slice notation.\n\
8755
21522
 \n\
8756
21523
 Return -1 on failure.");
 
21524
diff -r 8527427914a2 Objects/classobject.c
 
21525
--- a/Objects/classobject.c
 
21526
+++ b/Objects/classobject.c
 
21527
@@ -1221,7 +1221,7 @@
 
21528
     if (func == NULL)
 
21529
         return -1;
 
21530
     if (item == NULL)
 
21531
-        arg = PyInt_FromSsize_t(i);
 
21532
+        arg = Py_BuildValue("(n)", i);
 
21533
     else
 
21534
         arg = Py_BuildValue("(nO)", i, item);
 
21535
     if (arg == NULL) {
8757
21536
diff -r 8527427914a2 Objects/descrobject.c
8758
21537
--- a/Objects/descrobject.c
8759
21538
+++ b/Objects/descrobject.c
8787
21566
     0,                                          /* tp_as_number */
8788
21567
     &proxy_as_sequence,                         /* tp_as_sequence */
8789
21568
     &proxy_as_mapping,                          /* tp_as_mapping */
 
21569
diff -r 8527427914a2 Objects/dictobject.c
 
21570
--- a/Objects/dictobject.c
 
21571
+++ b/Objects/dictobject.c
 
21572
@@ -1335,14 +1335,18 @@
 
21573
         PyObject *key;
 
21574
         long hash;
 
21575
 
 
21576
-        if (dictresize(mp, Py_SIZE(seq)))
 
21577
+        if (dictresize(mp, Py_SIZE(seq))) {
 
21578
+            Py_DECREF(d);
 
21579
             return NULL;
 
21580
+        }
 
21581
 
 
21582
         while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
 
21583
             Py_INCREF(key);
 
21584
             Py_INCREF(value);
 
21585
-            if (insertdict(mp, key, hash, value))
 
21586
+            if (insertdict(mp, key, hash, value)) {
 
21587
+                Py_DECREF(d);
 
21588
                 return NULL;
 
21589
+            }
 
21590
         }
 
21591
         return d;
 
21592
     }
 
21593
@@ -1353,14 +1357,18 @@
 
21594
         PyObject *key;
 
21595
         long hash;
 
21596
 
 
21597
-        if (dictresize(mp, PySet_GET_SIZE(seq)))
 
21598
+        if (dictresize(mp, PySet_GET_SIZE(seq))) {
 
21599
+            Py_DECREF(d);
 
21600
             return NULL;
 
21601
+        }
 
21602
 
 
21603
         while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
 
21604
             Py_INCREF(key);
 
21605
             Py_INCREF(value);
 
21606
-            if (insertdict(mp, key, hash, value))
 
21607
+            if (insertdict(mp, key, hash, value)) {
 
21608
+                Py_DECREF(d);
 
21609
                 return NULL;
 
21610
+            }
 
21611
         }
 
21612
         return d;
 
21613
     }
 
21614
diff -r 8527427914a2 Objects/fileobject.c
 
21615
--- a/Objects/fileobject.c
 
21616
+++ b/Objects/fileobject.c
 
21617
@@ -468,28 +468,34 @@
 
21618
 PyObject *
 
21619
 PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
 
21620
 {
 
21621
-    PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
 
21622
-                                                         NULL, NULL);
 
21623
-    if (f != NULL) {
 
21624
-        PyObject *o_name = PyString_FromString(name);
 
21625
-        if (o_name == NULL)
 
21626
-            return NULL;
 
21627
-        if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
 
21628
-            Py_DECREF(f);
 
21629
-            f = NULL;
 
21630
-        }
 
21631
+    PyFileObject *f;
 
21632
+    PyObject *o_name;
 
21633
+
 
21634
+    f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type, NULL, NULL);
 
21635
+    if (f == NULL)
 
21636
+        return NULL;
 
21637
+    o_name = PyString_FromString(name);
 
21638
+    if (o_name == NULL) {
 
21639
+        if (close != NULL && fp != NULL)
 
21640
+            close(fp);
 
21641
+        Py_DECREF(f);
 
21642
+        return NULL;
 
21643
+    }
 
21644
+    if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
 
21645
+        Py_DECREF(f);
 
21646
         Py_DECREF(o_name);
 
21647
+        return NULL;
 
21648
     }
 
21649
-    return (PyObject *) f;
 
21650
+    Py_DECREF(o_name);
 
21651
+    return (PyObject *)f;
 
21652
 }
 
21653
 
 
21654
 PyObject *
 
21655
 PyFile_FromString(char *name, char *mode)
 
21656
 {
 
21657
-    extern int fclose(FILE *);
 
21658
     PyFileObject *f;
 
21659
 
 
21660
-    f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
 
21661
+    f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, NULL);
 
21662
     if (f != NULL) {
 
21663
         if (open_the_file(f, name, mode) == NULL) {
 
21664
             Py_DECREF(f);
 
21665
@@ -986,12 +992,6 @@
 
21666
 #define SMALLCHUNK BUFSIZ
 
21667
 #endif
 
21668
 
 
21669
-#if SIZEOF_INT < 4
 
21670
-#define BIGCHUNK  (512 * 32)
 
21671
-#else
 
21672
-#define BIGCHUNK  (512 * 1024)
 
21673
-#endif
 
21674
-
 
21675
 static size_t
 
21676
 new_buffersize(PyFileObject *f, size_t currentsize)
 
21677
 {
 
21678
@@ -1020,15 +1020,10 @@
 
21679
         /* Add 1 so if the file were to grow we'd notice. */
 
21680
     }
 
21681
 #endif
 
21682
-    if (currentsize > SMALLCHUNK) {
 
21683
-        /* Keep doubling until we reach BIGCHUNK;
 
21684
-           then keep adding BIGCHUNK. */
 
21685
-        if (currentsize <= BIGCHUNK)
 
21686
-            return currentsize + currentsize;
 
21687
-        else
 
21688
-            return currentsize + BIGCHUNK;
 
21689
-    }
 
21690
-    return currentsize + SMALLCHUNK;
 
21691
+    /* Expand the buffer by an amount proportional to the current size,
 
21692
+       giving us amortized linear-time behavior. Use a less-than-double
 
21693
+       growth factor to avoid excessive allocation. */
 
21694
+    return currentsize + (currentsize >> 3) + 6;
 
21695
 }
 
21696
 
 
21697
 #if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
 
21698
diff -r 8527427914a2 Objects/intobject.c
 
21699
--- a/Objects/intobject.c
 
21700
+++ b/Objects/intobject.c
 
21701
@@ -751,7 +751,13 @@
 
21702
     while (iw > 0) {
 
21703
         prev = ix;              /* Save value for overflow check */
 
21704
         if (iw & 1) {
 
21705
-            ix = ix*temp;
 
21706
+            /*
 
21707
+             * The (unsigned long) cast below ensures that the multiplication
 
21708
+             * is interpreted as an unsigned operation rather than a signed one
 
21709
+             * (C99 6.3.1.8p1), thus avoiding the perils of undefined behaviour
 
21710
+             * from signed arithmetic overflow (C99 6.5p5).  See issue #12973.
 
21711
+             */
 
21712
+            ix = (unsigned long)ix * temp;
 
21713
             if (temp == 0)
 
21714
                 break; /* Avoid ix / 0 */
 
21715
             if (ix / temp != prev) {
 
21716
@@ -764,7 +770,7 @@
 
21717
         iw >>= 1;               /* Shift exponent down by 1 bit */
 
21718
         if (iw==0) break;
 
21719
         prev = temp;
 
21720
-        temp *= temp;           /* Square the value of temp */
 
21721
+        temp = (unsigned long)temp * temp;  /* Square the value of temp */
 
21722
         if (prev != 0 && temp / prev != prev) {
 
21723
             return PyLong_Type.tp_as_number->nb_power(
 
21724
                 (PyObject *)v, (PyObject *)w, (PyObject *)z);
 
21725
diff -r 8527427914a2 Objects/listobject.c
 
21726
--- a/Objects/listobject.c
 
21727
+++ b/Objects/listobject.c
 
21728
@@ -58,7 +58,7 @@
 
21729
     if (newsize == 0)
 
21730
         new_allocated = 0;
 
21731
     items = self->ob_item;
 
21732
-    if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
 
21733
+    if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
 
21734
         PyMem_RESIZE(items, PyObject *, new_allocated);
 
21735
     else
 
21736
         items = NULL;
 
21737
@@ -551,9 +551,9 @@
 
21738
     PyObject *elem;
 
21739
     if (n < 0)
 
21740
         n = 0;
 
21741
+    if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
 
21742
+        return PyErr_NoMemory();
 
21743
     size = Py_SIZE(a) * n;
 
21744
-    if (n && size/n != Py_SIZE(a))
 
21745
-        return PyErr_NoMemory();
 
21746
     if (size == 0)
 
21747
         return PyList_New(0);
 
21748
     np = (PyListObject *) PyList_New(size);
 
21749
diff -r 8527427914a2 Objects/setobject.c
 
21750
--- a/Objects/setobject.c
 
21751
+++ b/Objects/setobject.c
 
21752
@@ -1871,7 +1871,7 @@
 
21753
         tmpkey = make_new_set(&PyFrozenSet_Type, key);
 
21754
         if (tmpkey == NULL)
 
21755
             return -1;
 
21756
-        rv = set_contains(so, tmpkey);
 
21757
+        rv = set_contains_key(so, tmpkey);
 
21758
         Py_DECREF(tmpkey);
 
21759
     }
 
21760
     return rv;
 
21761
@@ -1925,7 +1925,7 @@
 
21762
 static PyObject *
 
21763
 set_discard(PySetObject *so, PyObject *key)
 
21764
 {
 
21765
-    PyObject *tmpkey, *result;
 
21766
+    PyObject *tmpkey;
 
21767
     int rv;
 
21768
 
 
21769
     rv = set_discard_key(so, key);
 
21770
@@ -1936,9 +1936,10 @@
 
21771
         tmpkey = make_new_set(&PyFrozenSet_Type, key);
 
21772
         if (tmpkey == NULL)
 
21773
             return NULL;
 
21774
-        result = set_discard(so, tmpkey);
 
21775
+        rv = set_discard_key(so, tmpkey);
 
21776
         Py_DECREF(tmpkey);
 
21777
-        return result;
 
21778
+        if (rv == -1)
 
21779
+            return NULL;
 
21780
     }
 
21781
     Py_RETURN_NONE;
 
21782
 }
8790
21783
diff -r 8527427914a2 Objects/stringobject.c
8791
21784
--- a/Objects/stringobject.c
8792
21785
+++ b/Objects/stringobject.c
8831
21824
     /* Can't reference self beyond this point */
8832
21825
     Py_DECREF(type);
8833
21826
 
8834
 
@@ -2978,7 +2980,7 @@
 
21827
@@ -2233,8 +2235,10 @@
 
21828
                 (add_weak && strcmp(s, "__weakref__") == 0))
 
21829
                 continue;
 
21830
             tmp =_Py_Mangle(name, tmp);
 
21831
-            if (!tmp)
 
21832
+            if (!tmp) {
 
21833
+                Py_DECREF(newslots);
 
21834
                 goto bad_slots;
 
21835
+            }
 
21836
             PyList_SET_ITEM(newslots, j, tmp);
 
21837
             j++;
 
21838
         }
 
21839
@@ -2978,7 +2982,7 @@
8835
21840
     unaryfunc f;
8836
21841
 
8837
21842
     f = Py_TYPE(self)->tp_repr;
8840
21845
         f = object_repr;
8841
21846
     return f(self);
8842
21847
 }
 
21848
@@ -5933,27 +5937,27 @@
 
21849
     NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
 
21850
            "x[y:z] <==> x[y.__index__():z.__index__()]"),
 
21851
     IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
 
21852
-           wrap_binaryfunc, "+"),
 
21853
+           wrap_binaryfunc, "+="),
 
21854
     IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
 
21855
-           wrap_binaryfunc, "-"),
 
21856
+           wrap_binaryfunc, "-="),
 
21857
     IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
 
21858
-           wrap_binaryfunc, "*"),
 
21859
+           wrap_binaryfunc, "*="),
 
21860
     IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
 
21861
-           wrap_binaryfunc, "/"),
 
21862
+           wrap_binaryfunc, "/="),
 
21863
     IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
 
21864
-           wrap_binaryfunc, "%"),
 
21865
+           wrap_binaryfunc, "%="),
 
21866
     IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
 
21867
-           wrap_binaryfunc, "**"),
 
21868
+           wrap_binaryfunc, "**="),
 
21869
     IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
 
21870
-           wrap_binaryfunc, "<<"),
 
21871
+           wrap_binaryfunc, "<<="),
 
21872
     IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
 
21873
-           wrap_binaryfunc, ">>"),
 
21874
+           wrap_binaryfunc, ">>="),
 
21875
     IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
 
21876
-           wrap_binaryfunc, "&"),
 
21877
+           wrap_binaryfunc, "&="),
 
21878
     IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
 
21879
-           wrap_binaryfunc, "^"),
 
21880
+           wrap_binaryfunc, "^="),
 
21881
     IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
 
21882
-           wrap_binaryfunc, "|"),
 
21883
+           wrap_binaryfunc, "|="),
 
21884
     BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
 
21885
     RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
 
21886
     BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
8843
21887
diff -r 8527427914a2 Objects/unicodeobject.c
8844
21888
--- a/Objects/unicodeobject.c
8845
21889
+++ b/Objects/unicodeobject.c
8846
 
@@ -5485,13 +5485,13 @@
 
21890
@@ -1628,21 +1628,17 @@
 
21891
                             *p++ = outCh;
 
21892
 #endif
 
21893
                             surrogate = 0;
 
21894
+                            continue;
 
21895
                         }
 
21896
                         else {
 
21897
+                            *p++ = surrogate;
 
21898
                             surrogate = 0;
 
21899
-                            errmsg = "second surrogate missing";
 
21900
-                            goto utf7Error;
 
21901
                         }
 
21902
                     }
 
21903
-                    else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
 
21904
+                    if (outCh >= 0xD800 && outCh <= 0xDBFF) {
 
21905
                         /* first surrogate */
 
21906
                         surrogate = outCh;
 
21907
                     }
 
21908
-                    else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
 
21909
-                        errmsg = "unexpected second surrogate";
 
21910
-                        goto utf7Error;
 
21911
-                    }
 
21912
                     else {
 
21913
                         *p++ = outCh;
 
21914
                     }
 
21915
@@ -1652,8 +1648,8 @@
 
21916
                 inShift = 0;
 
21917
                 s++;
 
21918
                 if (surrogate) {
 
21919
-                    errmsg = "second surrogate missing at end of shift sequence";
 
21920
-                    goto utf7Error;
 
21921
+                    *p++ = surrogate;
 
21922
+                    surrogate = 0;
 
21923
                 }
 
21924
                 if (base64bits > 0) { /* left-over bits */
 
21925
                     if (base64bits >= 6) {
 
21926
@@ -5164,11 +5160,10 @@
 
21927
         }
 
21928
         /* All other characters are considered unencodable */
 
21929
         collstart = p;
 
21930
-        collend = p+1;
 
21931
-        while (collend < end) {
 
21932
+        for (collend = p+1; collend < end; collend++) {
 
21933
             if ((0 < *collend && *collend < 256) ||
 
21934
-                !Py_UNICODE_ISSPACE(*collend) ||
 
21935
-                Py_UNICODE_TODECIMAL(*collend))
 
21936
+                Py_UNICODE_ISSPACE(*collend) ||
 
21937
+                0 <= Py_UNICODE_TODECIMAL(*collend))
 
21938
                 break;
 
21939
         }
 
21940
         /* cache callback name lookup
 
21941
@@ -5485,13 +5480,13 @@
8847
21942
 
8848
21943
     if (len == 0)
8849
21944
         return 0;
8859
21954
             *s = Py_UNICODE_TOLOWER(*s);
8860
21955
             status = 1;
8861
21956
         }
8862
 
@@ -6491,7 +6491,7 @@
 
21957
@@ -6491,7 +6486,7 @@
8863
21958
              "S.find(sub [,start [,end]]) -> int\n\
8864
21959
 \n\
8865
21960
 Return the lowest index in S where substring sub is found,\n\
8868
21963
 arguments start and end are interpreted as in slice notation.\n\
8869
21964
 \n\
8870
21965
 Return -1 on failure.");
8871
 
@@ -7226,7 +7226,7 @@
 
21966
@@ -7226,7 +7221,7 @@
8872
21967
              "S.rfind(sub [,start [,end]]) -> int\n\
8873
21968
 \n\
8874
21969
 Return the highest index in S where substring sub is found,\n\
8877
21972
 arguments start and end are interpreted as in slice notation.\n\
8878
21973
 \n\
8879
21974
 Return -1 on failure.");
 
21975
diff -r 8527427914a2 PC/pyconfig.h
 
21976
--- a/PC/pyconfig.h
 
21977
+++ b/PC/pyconfig.h
 
21978
@@ -643,6 +643,9 @@
 
21979
 #define HAVE_WCSCOLL 1
 
21980
 #endif
 
21981
 
 
21982
+/* Define if the zlib library has inflateCopy */
 
21983
+#define HAVE_ZLIB_COPY 1
 
21984
+
 
21985
 /* Define if you have the <dlfcn.h> header file.  */
 
21986
 /* #undef HAVE_DLFCN_H */
 
21987
 
8880
21988
diff -r 8527427914a2 Parser/asdl_c.py
8881
21989
--- a/Parser/asdl_c.py
8882
21990
+++ b/Parser/asdl_c.py
9009
22117
diff -r 8527427914a2 Python/bltinmodule.c
9010
22118
--- a/Python/bltinmodule.c
9011
22119
+++ b/Python/bltinmodule.c
9012
 
@@ -224,7 +224,7 @@
 
22120
@@ -224,9 +224,6 @@
9013
22121
 static PyObject *
9014
22122
 builtin_callable(PyObject *self, PyObject *v)
9015
22123
 {
9016
22124
-    if (PyErr_WarnPy3k("callable() not supported in 3.x; "
9017
 
+    if (PyErr_WarnPy3k("callable() not supported in 3.1; "
9018
 
                        "use isinstance(x, collections.Callable)", 1) < 0)
9019
 
         return NULL;
 
22125
-                       "use isinstance(x, collections.Callable)", 1) < 0)
 
22126
-        return NULL;
9020
22127
     return PyBool_FromLong((long)PyCallable_Check(v));
9021
 
@@ -604,7 +604,7 @@
 
22128
 }
 
22129
 
 
22130
@@ -604,7 +601,7 @@
9022
22131
 }
9023
22132
 
9024
22133
 PyDoc_STRVAR(divmod_doc,
9062
22171
         p[i] = ch;
9063
22172
     }
9064
22173
     return v;
 
22174
diff -r 8527427914a2 Python/compile.c
 
22175
--- a/Python/compile.c
 
22176
+++ b/Python/compile.c
 
22177
@@ -2079,11 +2079,9 @@
 
22178
     ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
 
22179
     if (s->v.Assert.msg) {
 
22180
         VISIT(c, expr, s->v.Assert.msg);
 
22181
-        ADDOP_I(c, RAISE_VARARGS, 2);
 
22182
+        ADDOP_I(c, CALL_FUNCTION, 1);
 
22183
     }
 
22184
-    else {
 
22185
-        ADDOP_I(c, RAISE_VARARGS, 1);
 
22186
-    }
 
22187
+    ADDOP_I(c, RAISE_VARARGS, 1);
 
22188
     compiler_use_next_block(c, end);
 
22189
     return 1;
 
22190
 }
 
22191
diff -r 8527427914a2 Python/import.c
 
22192
--- a/Python/import.c
 
22193
+++ b/Python/import.c
 
22194
@@ -1235,7 +1235,7 @@
 
22195
 
 
22196
         meta_path = PySys_GetObject("meta_path");
 
22197
         if (meta_path == NULL || !PyList_Check(meta_path)) {
 
22198
-            PyErr_SetString(PyExc_ImportError,
 
22199
+            PyErr_SetString(PyExc_RuntimeError,
 
22200
                             "sys.meta_path must be a list of "
 
22201
                             "import hooks");
 
22202
             return NULL;
 
22203
@@ -1304,14 +1304,14 @@
 
22204
         path = PySys_GetObject("path");
 
22205
     }
 
22206
     if (path == NULL || !PyList_Check(path)) {
 
22207
-        PyErr_SetString(PyExc_ImportError,
 
22208
+        PyErr_SetString(PyExc_RuntimeError,
 
22209
                         "sys.path must be a list of directory names");
 
22210
         return NULL;
 
22211
     }
 
22212
 
 
22213
     path_hooks = PySys_GetObject("path_hooks");
 
22214
     if (path_hooks == NULL || !PyList_Check(path_hooks)) {
 
22215
-        PyErr_SetString(PyExc_ImportError,
 
22216
+        PyErr_SetString(PyExc_RuntimeError,
 
22217
                         "sys.path_hooks must be a list of "
 
22218
                         "import hooks");
 
22219
         return NULL;
 
22220
@@ -1319,7 +1319,7 @@
 
22221
     path_importer_cache = PySys_GetObject("path_importer_cache");
 
22222
     if (path_importer_cache == NULL ||
 
22223
         !PyDict_Check(path_importer_cache)) {
 
22224
-        PyErr_SetString(PyExc_ImportError,
 
22225
+        PyErr_SetString(PyExc_RuntimeError,
 
22226
                         "sys.path_importer_cache must be a dict");
 
22227
         return NULL;
 
22228
     }
 
22229
@@ -2064,7 +2064,9 @@
 
22230
 {
 
22231
     PyObject *result;
 
22232
     PyObject *modules;
 
22233
+#ifdef WITH_THREAD
 
22234
     long me;
 
22235
+#endif
 
22236
 
 
22237
     /* Try to get the module from sys.modules[name] */
 
22238
     modules = PyImport_GetModuleDict();
 
22239
@@ -2843,10 +2845,8 @@
 
22240
         return NULL;
 
22241
     if (fp != NULL) {
 
22242
         fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
 
22243
-        if (fob == NULL) {
 
22244
-            fclose(fp);
 
22245
+        if (fob == NULL)
 
22246
             return NULL;
 
22247
-        }
 
22248
     }
 
22249
     else {
 
22250
         fob = Py_None;
 
22251
diff -r 8527427914a2 Python/pystate.c
 
22252
--- a/Python/pystate.c
 
22253
+++ b/Python/pystate.c
 
22254
@@ -537,23 +537,6 @@
 
22255
     autoInterpreterState = NULL;
 
22256
 }
 
22257
 
 
22258
-/* Reset the TLS key - called by PyOS_AfterFork.
 
22259
- * This should not be necessary, but some - buggy - pthread implementations
 
22260
- * don't flush TLS on fork, see issue #10517.
 
22261
- */
 
22262
-void
 
22263
-_PyGILState_Reinit(void)
 
22264
-{
 
22265
-    PyThreadState *tstate = PyGILState_GetThisThreadState();
 
22266
-    PyThread_delete_key(autoTLSkey);
 
22267
-    if ((autoTLSkey = PyThread_create_key()) == -1)
 
22268
-        Py_FatalError("Could not allocate TLS entry");
 
22269
-
 
22270
-    /* re-associate the current thread state with the new key */
 
22271
-    if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
 
22272
-        Py_FatalError("Couldn't create autoTLSkey mapping");
 
22273
-}
 
22274
-
 
22275
 /* When a thread state is created for a thread by some mechanism other than
 
22276
    PyGILState_Ensure, it's important that the GILState machinery knows about
 
22277
    it so it doesn't try to create another thread state for the thread (this is
9065
22278
diff -r 8527427914a2 Python/sysmodule.c
9066
22279
--- a/Python/sysmodule.c
9067
22280
+++ b/Python/sysmodule.c
9073
22286
     Py_INCREF(Py_None);
9074
22287
     return Py_None;
9075
22288
 }
 
22289
diff -r 8527427914a2 Tools/iobench/iobench.py
 
22290
--- a/Tools/iobench/iobench.py
 
22291
+++ b/Tools/iobench/iobench.py
 
22292
@@ -358,7 +358,7 @@
 
22293
             with text_open(name, "r") as f:
 
22294
                 return f.read()
 
22295
         run_test_family(modify_tests, "b", text_files,
 
22296
-            lambda fn: open(fn, "r+"), make_test_source)
 
22297
+            lambda fn: text_open(fn, "r+"), make_test_source)
 
22298
 
 
22299
 
 
22300
 def prepare_files():
9076
22301
diff -r 8527427914a2 Tools/scripts/analyze_dxp.py
9077
22302
--- a/Tools/scripts/analyze_dxp.py
9078
22303
+++ b/Tools/scripts/analyze_dxp.py
9240
22465
                     f.writelines(new_lines)
9241
22466
                 fixed.append(path)
9242
22467
         except Exception as err:
 
22468
@@ -150,8 +157,9 @@
 
22469
     reported_news(special_files)
 
22470
 
 
22471
     # Test suite run and passed.
 
22472
-    print
 
22473
-    print "Did you run the test suite?"
 
22474
+    if python_files or c_files:
 
22475
+        print
 
22476
+        print "Did you run the test suite?"
 
22477
 
 
22478
 
 
22479
 if __name__ == '__main__':
9243
22480
diff -r 8527427914a2 Tools/scripts/redemo.py
9244
22481
--- a/Tools/scripts/redemo.py
9245
22482
+++ b/Tools/scripts/redemo.py
9316
22553
        MACHDEP="$ac_md_system$ac_md_release"
9317
22554
 
9318
22555
        case $MACHDEP in
9319
 
+       linux3*) MACHDEP="linux2";;
 
22556
+       linux*) MACHDEP="linux2";;
9320
22557
        cygwin*) MACHDEP="cygwin";;
9321
22558
        darwin*) MACHDEP="darwin";;
9322
22559
        atheos*) MACHDEP="atheos";;
9346
22583
          LDLIBRARY='libpython$(VERSION).so'
9347
22584
          BLDLIBRARY='-L. -lpython$(VERSION)'
9348
22585
          RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
9349
 
@@ -2359,18 +2360,15 @@
 
22586
@@ -931,6 +932,12 @@
 
22587
         if "$CC" -v --help 2>/dev/null |grep -- -fwrapv > /dev/null; then
 
22588
            WRAP="-fwrapv"
 
22589
         fi
 
22590
+
 
22591
+        # Clang also needs -fwrapv
 
22592
+        if test "$CC" = "clang" ; then
 
22593
+            WRAP="-fwrapv"
 
22594
+        fi
 
22595
+
 
22596
        case $ac_cv_prog_cc_g in
 
22597
        yes)
 
22598
            if test "$Py_DEBUG" = 'true' ; then
 
22599
@@ -2359,18 +2366,15 @@
9350
22600
 
9351
22601
       # Bug 662787: Using semaphores causes unexplicable hangs on Solaris 8.
9352
22602
       case  $ac_sys_system/$ac_sys_release in
9367
22617
       esac
9368
22618
 
9369
22619
       AC_MSG_CHECKING(if PTHREAD_SCOPE_SYSTEM is supported)
9370
 
@@ -2839,7 +2837,7 @@
 
22620
@@ -2827,6 +2831,15 @@
 
22621
   [AC_MSG_RESULT(no)
 
22622
 ])
 
22623
 
 
22624
+AC_MSG_CHECKING(for broken unsetenv)
 
22625
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
 
22626
+#include <stdlib.h>
 
22627
+]], [[int res = unsetenv("DUMMY")]])],
 
22628
+  [AC_MSG_RESULT(no)],
 
22629
+  [AC_DEFINE(HAVE_BROKEN_UNSETENV, 1, Define if `unsetenv` does not return an int.)
 
22630
+   AC_MSG_RESULT(yes)
 
22631
+])
 
22632
+
 
22633
 dnl check for true
 
22634
 AC_CHECK_PROGS(TRUE, true, /bin/true)
 
22635
 
 
22636
@@ -2839,7 +2852,7 @@
9371
22637
 # On Tru64, chflags seems to be present, but calling it will
9372
22638
 # exit Python
9373
22639
 AC_CACHE_CHECK([for chflags], [ac_cv_have_chflags], [dnl
9376
22642
 #include <sys/stat.h>
9377
22643
 #include <unistd.h>
9378
22644
 int main(int argc, char*argv[])
9379
 
@@ -2848,7 +2846,7 @@
 
22645
@@ -2848,7 +2861,7 @@
9380
22646
     return 1;
9381
22647
   return 0;
9382
22648
 }
9385
22651
 [ac_cv_have_chflags=yes],
9386
22652
 [ac_cv_have_chflags=no],
9387
22653
 [ac_cv_have_chflags=cross])
9388
 
@@ -2857,11 +2855,11 @@
 
22654
@@ -2857,11 +2870,11 @@
9389
22655
   AC_CHECK_FUNC([chflags], [ac_cv_have_chflags="yes"], [ac_cv_have_chflags="no"])
9390
22656
 fi
9391
22657
 if test "$ac_cv_have_chflags" = yes ; then
9399
22665
 #include <sys/stat.h>
9400
22666
 #include <unistd.h>
9401
22667
 int main(int argc, char*argv[])
9402
 
@@ -2870,13 +2868,13 @@
 
22668
@@ -2870,13 +2883,13 @@
9403
22669
     return 1;
9404
22670
   return 0;
9405
22671
 }
9418
22684
diff -r 8527427914a2 pyconfig.h.in
9419
22685
--- a/pyconfig.h.in
9420
22686
+++ b/pyconfig.h.in
9421
 
@@ -100,7 +100,7 @@
 
22687
@@ -97,10 +97,13 @@
 
22688
 /* define to 1 if your sem_getvalue is broken. */
 
22689
 #undef HAVE_BROKEN_SEM_GETVALUE
 
22690
 
 
22691
+/* Define if `unsetenv` does not return an int. */
 
22692
+#undef HAVE_BROKEN_UNSETENV
 
22693
+
9422
22694
 /* Define this if you have the type _Bool. */
9423
22695
 #undef HAVE_C99_BOOL
9424
22696
 
9427
22699
 #undef HAVE_CHFLAGS
9428
22700
 
9429
22701
 /* Define to 1 if you have the `chown' function. */
9430
 
@@ -391,7 +391,7 @@
 
22702
@@ -391,7 +394,7 @@
9431
22703
    Solaris and Linux, the necessary defines are already defined.) */
9432
22704
 #undef HAVE_LARGEFILE_SUPPORT
9433
22705
 
9436
22708
 #undef HAVE_LCHFLAGS
9437
22709
 
9438
22710
 /* Define to 1 if you have the `lchmod' function. */
9439
 
@@ -1137,6 +1137,9 @@
 
22711
@@ -1137,6 +1140,9 @@
9440
22712
 /* This must be defined on some systems to enable large file support. */
9441
22713
 #undef _LARGEFILE_SOURCE
9442
22714