[Python-checkins] cpython (merge default -> default): Merge with main repo default branch.

georg.brandl python-checkins at python.org
Sat Sep 29 09:27:55 CEST 2012


http://hg.python.org/cpython/rev/d4312199103e
changeset:   79238:d4312199103e
parent:      79237:cb84dcb35114
parent:      79228:4a979326e6d6
user:        Georg Brandl <georg at python.org>
date:        Sat Sep 29 09:27:15 2012 +0200
summary:
  Merge with main repo default branch.

files:
  Doc/ACKS.txt                             |   239 -
  Doc/about.rst                            |     9 +-
  Doc/c-api/import.rst                     |     2 +-
  Doc/extending/newtypes.rst               |     6 +-
  Doc/faq/windows.rst                      |    10 +-
  Doc/howto/regex.rst                      |    26 +-
  Doc/howto/unicode.rst                    |    27 +-
  Doc/library/argparse.rst                 |    23 +-
  Doc/library/collections.rst              |     2 +-
  Doc/library/configparser.rst             |    19 +-
  Doc/library/crypt.rst                    |    10 +-
  Doc/library/crypto.rst                   |     1 +
  Doc/library/csv.rst                      |    28 +-
  Doc/library/curses.rst                   |    46 +-
  Doc/library/doctest.rst                  |    12 +-
  Doc/library/functions.rst                |    75 +-
  Doc/library/http.client.rst              |     8 +-
  Doc/library/inspect.rst                  |     4 +-
  Doc/library/itertools.rst                |     3 +-
  Doc/library/json.rst                     |    18 +-
  Doc/library/lzma.rst                     |    12 +-
  Doc/library/mailbox.rst                  |    19 +-
  Doc/library/multiprocessing.rst          |     5 +-
  Doc/library/nntplib.rst                  |     6 +-
  Doc/library/optparse.rst                 |    17 +-
  Doc/library/os.rst                       |     5 +-
  Doc/library/ossaudiodev.rst              |     3 +-
  Doc/library/pyexpat.rst                  |     2 +-
  Doc/library/random.rst                   |    11 +-
  Doc/library/site.rst                     |     2 +-
  Doc/library/smtpd.rst                    |    13 +-
  Doc/library/socket.rst                   |     3 +-
  Doc/library/stdtypes.rst                 |    11 +-
  Doc/library/subprocess.rst               |    14 +-
  Doc/library/syslog.rst                   |     3 +-
  Doc/library/textwrap.rst                 |    19 +-
  Doc/library/threading.rst                |     6 +-
  Doc/library/timeit.rst                   |    20 +-
  Doc/library/tkinter.tix.rst              |     2 +-
  Doc/library/types.rst                    |     2 +-
  Doc/library/unittest.mock.rst            |     4 +-
  Doc/library/unittest.rst                 |     2 +-
  Doc/library/urllib.parse.rst             |     5 +-
  Doc/license.rst                          |     6 +-
  Doc/reference/compound_stmts.rst         |    10 +-
  Doc/reference/datamodel.rst              |    26 +-
  Doc/tools/sphinxext/susp-ignored.csv     |     3 +-
  Doc/tutorial/datastructures.rst          |     2 +-
  Doc/tutorial/interpreter.rst             |     8 +-
  Doc/tutorial/introduction.rst            |     3 +-
  Doc/tutorial/stdlib.rst                  |     2 +-
  Doc/tutorial/stdlib2.rst                 |     8 +-
  Doc/whatsnew/3.3.rst                     |   118 +-
  Include/object.h                         |     2 +-
  Include/objimpl.h                        |     9 +-
  Include/pyfpe.h                          |     8 +-
  Include/pymacro.h                        |    14 +
  Lib/_pyio.py                             |     8 +
  Lib/argparse.py                          |    27 +-
  Lib/calendar.py                          |     6 +-
  Lib/doctest.py                           |     7 +-
  Lib/gzip.py                              |     4 +-
  Lib/http/cookiejar.py                    |     4 +-
  Lib/importlib/_bootstrap.py              |     8 +-
  Lib/lib2to3/fixer_util.py                |     4 +-
  Lib/lib2to3/refactor.py                  |     2 +-
  Lib/mailbox.py                           |    46 +-
  Lib/multiprocessing/pool.py              |    15 +-
  Lib/multiprocessing/util.py              |    42 +-
  Lib/socket.py                            |    15 +-
  Lib/test/sample_doctest_no_docstrings.py |    12 +
  Lib/test/sample_doctest_no_doctests.py   |    15 +
  Lib/test/string_tests.py                 |     3 +
  Lib/test/support.py                      |     2 +-
  Lib/test/test_argparse.py                |    81 +
  Lib/test/test_ast.py                     |     8 +
  Lib/test/test_calendar.py                |     6 +
  Lib/test/test_codecs.py                  |   116 +
  Lib/test/test_compileall.py              |    16 +-
  Lib/test/test_csv.py                     |     9 +
  Lib/test/test_decimal.py                 |    12 +-
  Lib/test/test_doctest.py                 |    25 +
  Lib/test/test_gdb.py                     |     5 +
  Lib/test/test_import.py                  |     2 +-
  Lib/test/test_importlib/test_locks.py    |    22 +-
  Lib/test/test_int.py                     |    12 +
  Lib/test/test_io.py                      |     5 +
  Lib/test/test_mailbox.py                 |    63 +-
  Lib/test/test_memoryio.py                |     7 +-
  Lib/test/test_mmap.py                    |     9 +
  Lib/test/test_multiprocessing.py         |     3 +-
  Lib/test/test_os.py                      |    26 +-
  Lib/test/test_pyexpat.py                 |    10 +
  Lib/test/test_socket.py                  |    11 +
  Lib/test/test_ssl.py                     |     8 +-
  Lib/test/test_startfile.py               |    15 +-
  Lib/test/test_super.py                   |    15 +
  Lib/test/test_support.py                 |     9 +
  Lib/test/test_textwrap.py                |    64 +-
  Lib/test/test_threaded_import.py         |     4 +-
  Lib/test/test_types.py                   |     2 +-
  Lib/test/test_webbrowser.py              |   192 +
  Lib/test/test_xml_etree.py               |    12 +
  Lib/test/test_zipimport_support.py       |    21 +-
  Lib/unittest/__main__.py                 |     9 +-
  Lib/unittest/mock.py                     |     4 +-
  Lib/unittest/runner.py                   |     2 +-
  Lib/unittest/test/test_runner.py         |    13 +
  Lib/unittest/test/testmock/testmock.py   |     7 +
  Lib/webbrowser.py                        |    15 +-
  Lib/xml/etree/ElementTree.py             |     2 +-
  Makefile.pre.in                          |    17 +-
  Misc/ACKS                                |   122 +-
  Misc/NEWS                                |   123 +-
  Modules/_csv.c                           |    11 +-
  Modules/_cursesmodule.c                  |     1 +
  Modules/_decimal/tests/bench.py          |    47 +-
  Modules/_elementtree.c                   |     2 +-
  Modules/_io/_iomodule.c                  |     2 +-
  Modules/_io/bytesio.c                    |    24 +-
  Modules/_io/iobase.c                     |     2 +-
  Modules/_io/stringio.c                   |    19 +-
  Modules/_io/textio.c                     |     2 +-
  Modules/_ssl.c                           |     2 +-
  Modules/_testbuffer.c                    |     7 +-
  Modules/mmapmodule.c                     |    11 +
  Modules/posixmodule.c                    |     9 +-
  Modules/selectmodule.c                   |     2 +-
  Modules/socketmodule.c                   |     3 +-
  Modules/zipimport.c                      |     8 +-
  Objects/classobject.c                    |     3 +-
  Objects/longobject.c                     |    10 +-
  Objects/memoryobject.c                   |    78 +-
  Objects/obmalloc.c                       |     7 +-
  Objects/setobject.c                      |     4 +-
  Objects/stringlib/codecs.h               |    14 +-
  Objects/stringlib/fastsearch.h           |     3 +-
  Objects/stringlib/find_max_char.h        |    11 +-
  Objects/tupleobject.c                    |     4 +-
  Objects/typeobject.c                     |    28 +-
  Objects/unicodeobject.c                  |    27 +-
  Parser/node.c                            |     2 +-
  Python/ast.c                             |   187 +-
  Python/formatter_unicode.c               |     2 +-
  Python/getargs.c                         |     1 +
  Python/importlib.h                       |  6991 ++++-----
  Python/pyarena.c                         |     8 +-
  Python/structmember.c                    |     6 +-
  Python/symtable.c                        |     8 +-
  setup.py                                 |     2 +
  150 files changed, 5467 insertions(+), 4378 deletions(-)


diff --git a/Doc/ACKS.txt b/Doc/ACKS.txt
deleted file mode 100644
--- a/Doc/ACKS.txt
+++ /dev/null
@@ -1,239 +0,0 @@
-Contributors to the Python Documentation
-----------------------------------------
-
-This section lists people who have contributed in some way to the Python
-documentation.  It is probably not complete -- if you feel that you or
-anyone else should be on this list, please let us know (send email to
-docs at python.org), and we'll be glad to correct the problem.
-
-.. acks::
-
-   * Aahz
-   * Michael Abbott
-   * Steve Alexander
-   * Jim Ahlstrom
-   * Fred Allen
-   * A. Amoroso
-   * Pehr Anderson
-   * Oliver Andrich
-   * Heidi Annexstad
-   * Jesús Cea Avión
-   * Manuel Balsera
-   * Daniel Barclay
-   * Chris Barker
-   * Don Bashford
-   * Anthony Baxter
-   * Alexander Belopolsky
-   * Bennett Benson
-   * Jonathan Black
-   * Robin Boerdijk
-   * Michal Bozon
-   * Aaron Brancotti
-   * Georg Brandl
-   * Keith Briggs
-   * Ian Bruntlett
-   * Lee Busby
-   * Arnaud Calmettes
-   * Lorenzo M. Catucci
-   * Carl Cerecke
-   * Mauro Cicognini
-   * Gilles Civario
-   * Mike Clarkson
-   * Steve Clift
-   * Dave Cole
-   * Matthew Cowles
-   * Jeremy Craven
-   * Andrew Dalke
-   * Ben Darnell
-   * L. Peter Deutsch
-   * Robert Donohue
-   * Fred L. Drake, Jr.
-   * Jacques Ducasse
-   * Josip Dzolonga
-   * Jeff Epler
-   * Michael Ernst
-   * Blame Andy Eskilsson
-   * Carey Evans
-   * Martijn Faassen
-   * Carl Feynman
-   * Dan Finnie
-   * Hernán Martínez Foffani
-   * Michael Foord
-   * Stefan Franke
-   * Jim Fulton
-   * Peter Funk
-   * Ethan Furman
-   * Lele Gaifax
-   * Matthew Gallagher
-   * Gabriel Genellina
-   * Ben Gertzfield
-   * Nadim Ghaznavi
-   * Jonathan Giddy
-   * Matt Giuca
-   * Shelley Gooch
-   * Nathaniel Gray
-   * Grant Griffin
-   * Thomas Guettler
-   * Anders Hammarquist
-   * Mark Hammond
-   * Harald Hanche-Olsen
-   * Manus Hand
-   * Gerhard Häring
-   * Travis B. Hartwell
-   * Tim Hatch
-   * Janko Hauser
-   * Ben Hayden
-   * Thomas Heller
-   * Bernhard Herzog
-   * Magnus L. Hetland
-   * Konrad Hinsen
-   * Stefan Hoffmeister
-   * Albert Hofkamp
-   * Gregor Hoffleit
-   * Steve Holden
-   * Thomas Holenstein
-   * Gerrit Holl
-   * Rob Hooft
-   * Brian Hooper
-   * Randall Hopper
-   * Michael Hudson
-   * Eric Huss
-   * Jeremy Hylton
-   * Roger Irwin
-   * Jack Jansen
-   * Philip H. Jensen
-   * Pedro Diaz Jimenez
-   * Kent Johnson
-   * Lucas de Jonge
-   * Andreas Jung
-   * Robert Kern
-   * Jim Kerr
-   * Jan Kim
-   * Kamil Kisiel
-   * Greg Kochanski
-   * Guido Kollerie
-   * Peter A. Koren
-   * Daniel Kozan
-   * Andrew M. Kuchling
-   * Dave Kuhlman
-   * Erno Kuusela
-   * Ross Lagerwall
-   * Thomas Lamb
-   * Detlef Lannert
-   * Piers Lauder
-   * Julia Lawall
-   * Glyph Lefkowitz
-   * Robert Lehmann
-   * Marc-André Lemburg
-   * Ross Light
-   * Gediminas Liktaras
-   * Ulf A. Lindgren
-   * Everett Lipman
-   * Mirko Liss
-   * Martin von Löwis
-   * Fredrik Lundh
-   * Jeff MacDonald
-   * John Machin
-   * Andrew MacIntyre
-   * Vladimir Marangozov
-   * Vincent Marchetti
-   * Westley Martínez
-   * Laura Matson
-   * Daniel May
-   * Rebecca McCreary
-   * Doug Mennella
-   * Paolo Milani
-   * Skip Montanaro
-   * Paul Moore
-   * Ross Moore
-   * Sjoerd Mullender
-   * Dale Nagata
-   * Trent Nelson
-   * Michal Nowikowski
-   * Steffen Daode Nurpmeso
-   * Ng Pheng Siong
-   * Koray Oner
-   * Tomas Oppelstrup
-   * Denis S. Otkidach
-   * Zooko O'Whielacronx
-   * Shriphani Palakodety
-   * William Park
-   * Joonas Paalasmaa
-   * Harri Pasanen
-   * Bo Peng
-   * Tim Peters
-   * Benjamin Peterson
-   * Christopher Petrilli
-   * Justin D. Pettit
-   * Chris Phoenix
-   * François Pinard
-   * Paul Prescod
-   * Eric S. Raymond
-   * Edward K. Ream
-   * Terry J. Reedy
-   * Sean Reifschneider
-   * Bernhard Reiter
-   * Armin Rigo
-   * Wes Rishel
-   * Armin Ronacher
-   * Jim Roskind
-   * Guido van Rossum
-   * Donald Wallace Rouse II
-   * Mark Russell
-   * Nick Russo
-   * Chris Ryland
-   * Constantina S.
-   * Hugh Sasse
-   * Bob Savage
-   * Scott Schram
-   * Neil Schemenauer
-   * Barry Scott
-   * Joakim Sernbrant
-   * Justin Sheehy
-   * Charlie Shepherd
-   * Yue Shuaijie
-   * SilentGhost
-   * Michael Simcich
-   * Ionel Simionescu
-   * Michael Sloan
-   * Gregory P. Smith
-   * Roy Smith
-   * Clay Spence
-   * Nicholas Spies
-   * Tage Stabell-Kulo
-   * Frank Stajano
-   * Anthony Starks
-   * Greg Stein
-   * Peter Stoehr
-   * Mark Summerfield
-   * Reuben Sumner
-   * Kalle Svensson
-   * Jim Tittsler
-   * David Turner
-   * Sandro Tosi
-   * Ville Vainio
-   * Nadeem Vawda
-   * Martijn Vries
-   * Charles G. Waldman
-   * Greg Ward
-   * Barry Warsaw
-   * Corran Webster
-   * Glyn Webster
-   * Bob Weiner
-   * Eddy Welbourne
-   * Jeff Wheeler
-   * Mats Wichmann
-   * Gerry Wiener
-   * Timothy Wild
-   * Paul Winkler
-   * Collin Winter
-   * Blake Winton
-   * Dan Wolfe
-   * Adam Woodbeck
-   * Steven Work
-   * Thomas Wouters
-   * Ka-Ping Yee
-   * Rory Yorke
-   * Moshe Zadka
-   * Milan Zamazal
-   * Cheng Zhang
diff --git a/Doc/about.rst b/Doc/about.rst
--- a/Doc/about.rst
+++ b/Doc/about.rst
@@ -29,8 +29,13 @@
 See :ref:`reporting-bugs` for information how to report bugs in this
 documentation, or Python itself.
 
-.. including the ACKS file here so that it can be maintained separately
-.. include:: ACKS.txt
+
+Contributors to the Python Documentation
+----------------------------------------
+
+Many people have contributed to the Python language, the Python standard
+library, and the Python documentation.  See :source:`Misc/ACKS` in the Python
+source distribution for a partial list of contributors.
 
 It is only with the input and contributions of the Python community
 that Python has such wonderful documentation -- Thank You!
diff --git a/Doc/c-api/import.rst b/Doc/c-api/import.rst
--- a/Doc/c-api/import.rst
+++ b/Doc/c-api/import.rst
@@ -76,7 +76,7 @@
    UTF-8 encoded string instead of a Unicode object.
 
    .. versionchanged:: 3.3
-         Negative values for **level** are no longer accepted.
+         Negative values for *level* are no longer accepted.
 
 .. c:function:: PyObject* PyImport_Import(PyObject *name)
 
diff --git a/Doc/extending/newtypes.rst b/Doc/extending/newtypes.rst
--- a/Doc/extending/newtypes.rst
+++ b/Doc/extending/newtypes.rst
@@ -1277,9 +1277,9 @@
 bit does not indicate that the slot values are non-*NULL*. The flag may be set
 to indicate the presence of a slot, but a slot may still be unfilled.) ::
 
-   PyNumberMethods   tp_as_number;
-   PySequenceMethods tp_as_sequence;
-   PyMappingMethods  tp_as_mapping;
+   PyNumberMethods   *tp_as_number;
+   PySequenceMethods *tp_as_sequence;
+   PyMappingMethods  *tp_as_mapping;
 
 If you wish your object to be able to act like a number, a sequence, or a
 mapping object, then you place the address of a structure that implements the C
diff --git a/Doc/faq/windows.rst b/Doc/faq/windows.rst
--- a/Doc/faq/windows.rst
+++ b/Doc/faq/windows.rst
@@ -464,13 +464,13 @@
 Why does os.path.isdir() fail on NT shared directories?
 -------------------------------------------------------
 
-The solution appears to be always append the "\\" on the end of shared
-drives.
+In order to work correctly, :func:`os.path.isdir` requires a ``"\\"`` at the
+end of the shared drive::
 
    >>> import os
-   >>> os.path.isdir( '\\\\rorschach\\public')
+   >>> os.path.isdir('\\\\rorschach\\public')
    0
-   >>> os.path.isdir( '\\\\rorschach\\public\\')
+   >>> os.path.isdir('\\\\rorschach\\public\\')
    1
 
 It helps to think of share points as being like drive letters.  Example::
@@ -480,7 +480,7 @@
    k:\media is a directory
    k:\media\ is not a directory
 
-The same rules apply if you substitute "k:" with "\\conky\foo"::
+The same rules apply if you substitute ``"k:"`` with ``"\\conky\foo"``::
 
    \\conky\foo  is not a directory
    \\conky\foo\ is a directory
diff --git a/Doc/howto/regex.rst b/Doc/howto/regex.rst
--- a/Doc/howto/regex.rst
+++ b/Doc/howto/regex.rst
@@ -260,7 +260,7 @@
 
    >>> import re
    >>> p = re.compile('ab*')
-   >>> p
+   >>> p  #doctest: +ELLIPSIS
    <_sre.SRE_Pattern object at 0x...>
 
 :func:`re.compile` also accepts an optional *flags* argument, used to enable
@@ -372,7 +372,7 @@
 
    >>> import re
    >>> p = re.compile('[a-z]+')
-   >>> p
+   >>> p  #doctest: +ELLIPSIS
    <_sre.SRE_Pattern object at 0x...>
 
 Now, you can try matching various strings against the RE ``[a-z]+``.  An empty
@@ -390,7 +390,7 @@
 result in a variable for later use. ::
 
    >>> m = p.match('tempo')
-   >>> m
+   >>> m  #doctest: +ELLIPSIS
    <_sre.SRE_Match object at 0x...>
 
 Now you can query the :class:`MatchObject` for information about the matching
@@ -429,7 +429,7 @@
 
    >>> print(p.match('::: message'))
    None
-   >>> m = p.search('::: message') ; print(m)
+   >>> m = p.search('::: message'); print(m)  #doctest: +ELLIPSIS
    <_sre.SRE_Match object at 0x...>
    >>> m.group()
    'message'
@@ -458,7 +458,7 @@
 instances as an :term:`iterator`::
 
    >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
-   >>> iterator
+   >>> iterator  #doctest: +ELLIPSIS
    <callable_iterator object at 0x...>
    >>> for match in iterator:
    ...     print(match.span())
@@ -480,7 +480,7 @@
 
    >>> print(re.match(r'From\s+', 'Fromage amk'))
    None
-   >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
+   >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')  #doctest: +ELLIPSIS
    <_sre.SRE_Match object at 0x...>
 
 Under the hood, these functions simply create a pattern object for you
@@ -682,7 +682,7 @@
    For example, if you wish to match the word ``From`` only at the beginning of a
    line, the RE to use is ``^From``. ::
 
-      >>> print(re.search('^From', 'From Here to Eternity'))
+      >>> print(re.search('^From', 'From Here to Eternity'))  #doctest: +ELLIPSIS
       <_sre.SRE_Match object at 0x...>
       >>> print(re.search('^From', 'Reciting From Memory'))
       None
@@ -694,11 +694,11 @@
    Matches at the end of a line, which is defined as either the end of the string,
    or any location followed by a newline character.     ::
 
-      >>> print(re.search('}$', '{block}'))
+      >>> print(re.search('}$', '{block}'))  #doctest: +ELLIPSIS
       <_sre.SRE_Match object at 0x...>
       >>> print(re.search('}$', '{block} '))
       None
-      >>> print(re.search('}$', '{block}\n'))
+      >>> print(re.search('}$', '{block}\n'))  #doctest: +ELLIPSIS
       <_sre.SRE_Match object at 0x...>
 
    To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
@@ -723,7 +723,7 @@
    match when it's contained inside another word. ::
 
       >>> p = re.compile(r'\bclass\b')
-      >>> print(p.search('no class at all'))
+      >>> print(p.search('no class at all'))  #doctest: +ELLIPSIS
       <_sre.SRE_Match object at 0x...>
       >>> print(p.search('the declassified algorithm'))
       None
@@ -741,7 +741,7 @@
       >>> p = re.compile('\bclass\b')
       >>> print(p.search('no class at all'))
       None
-      >>> print(p.search('\b' + 'class' + '\b')  )
+      >>> print(p.search('\b' + 'class' + '\b'))  #doctest: +ELLIPSIS
       <_sre.SRE_Match object at 0x...>
 
    Second, inside a character class, where there's no use for this assertion,
@@ -1182,9 +1182,9 @@
 In the following example, the replacement function translates  decimals into
 hexadecimal::
 
-   >>> def hexrepl( match ):
+   >>> def hexrepl(match):
    ...     "Return the hex string for a decimal number"
-   ...     value = int( match.group() )
+   ...     value = int(match.group())
    ...     return hex(value)
    ...
    >>> p = re.compile(r'\d+')
diff --git a/Doc/howto/unicode.rst b/Doc/howto/unicode.rst
--- a/Doc/howto/unicode.rst
+++ b/Doc/howto/unicode.rst
@@ -257,13 +257,13 @@
 'REPLACEMENT CHARACTER'), or 'ignore' (just leave the character out of the
 Unicode result).  The following examples show the differences::
 
-    >>> b'\x80abc'.decode("utf-8", "strict")
+    >>> b'\x80abc'.decode("utf-8", "strict")  #doctest: +NORMALIZE_WHITESPACE
     Traceback (most recent call last):
-      File "<stdin>", line 1, in ?
-    UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0:
-                        unexpected code byte
+        ...
+    UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
+      invalid start byte
     >>> b'\x80abc'.decode("utf-8", "replace")
-    '?abc'
+    '\ufffdabc'
     >>> b'\x80abc'.decode("utf-8", "ignore")
     'abc'
 
@@ -301,11 +301,11 @@
     >>> u = chr(40960) + 'abcd' + chr(1972)
     >>> u.encode('utf-8')
     b'\xea\x80\x80abcd\xde\xb4'
-    >>> u.encode('ascii')
+    >>> u.encode('ascii')  #doctest: +NORMALIZE_WHITESPACE
     Traceback (most recent call last):
-      File "<stdin>", line 1, in ?
+        ...
     UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in
-                        position 0: ordinal not in range(128)
+      position 0: ordinal not in range(128)
     >>> u.encode('ascii', 'ignore')
     b'abcd'
     >>> u.encode('ascii', 'replace')
@@ -331,12 +331,11 @@
 not four::
 
     >>> s = "a\xac\u1234\u20ac\U00008000"
-              ^^^^ two-digit hex escape
-                   ^^^^^ four-digit Unicode escape
-                              ^^^^^^^^^^ eight-digit Unicode escape
-    >>> for c in s:  print(ord(c), end=" ")
-    ...
-    97 172 4660 8364 32768
+    ... #     ^^^^ two-digit hex escape
+    ... #         ^^^^^^ four-digit Unicode escape
+    ... #                     ^^^^^^^^^^ eight-digit Unicode escape
+    >>> [ord(c) for c in s]
+    [97, 172, 4660, 8364, 32768]
 
 Using escape sequences for code points greater than 127 is fine in small doses,
 but becomes an annoyance if you're using many accented characters, as you would
diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -130,9 +130,12 @@
 ArgumentParser objects
 ----------------------
 
-.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
-                          [argument_default], [parents], [prefix_chars], \
-                          [conflict_handler], [formatter_class])
+.. class:: ArgumentParser(prog=None, usage=None, description=None, \
+                          epilog=None, parents=[], \
+                          formatter_class=argparse.HelpFormatter, \
+                          prefix_chars='-', fromfile_prefix_chars=None, \
+                          argument_default=None, conflict_handler='error', \
+                          add_help=True)
 
    Create a new :class:`ArgumentParser` object.  Each parameter has its own more
    detailed description below, but in short they are:
@@ -920,6 +923,17 @@
    >>> parser.parse_args(''.split())
    Namespace(foo=42)
 
+If the ``default`` value is a string, the parser parses the value as if it
+were a command-line argument.  In particular, the parser applies any type_
+conversion argument, if provided, before setting the attribute on the
+:class:`Namespace` return value.  Otherwise, the parser uses the value as is::
+
+   >>> parser = argparse.ArgumentParser()
+   >>> parser.add_argument('--length', default='10', type=int)
+   >>> parser.add_argument('--width', default=10.5, type=int)
+   >>> parser.parse_args()
+   Namespace(length=10, width=10.5)
+
 For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
 is used when no command-line argument was present::
 
@@ -958,6 +972,9 @@
    >>> parser.parse_args('2 temp.txt'.split())
    Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
 
+See the section on the default_ keyword argument for information on when the
+``type`` argument is applied to default arguments.
+
 To ease the use of various types of files, the argparse module provides the
 factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
 :func:`open` function.  For example, ``FileType('w')`` can be used to create a
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -1012,7 +1012,7 @@
 to the end and the sort is not maintained.
 
 It is also straight-forward to create an ordered dictionary variant
-that the remembers the order the keys were *last* inserted.
+that remembers the order the keys were *last* inserted.
 If a new entry overwrites an existing entry, the
 original insertion position is changed and moved to the end::
 
diff --git a/Doc/library/configparser.rst b/Doc/library/configparser.rst
--- a/Doc/library/configparser.rst
+++ b/Doc/library/configparser.rst
@@ -1007,7 +1007,7 @@
       .. versionadded:: 3.2
 
 
-   .. method:: get(section, option, raw=False, [vars, fallback])
+   .. method:: get(section, option, *, raw=False, vars=None[, fallback])
 
       Get an *option* value for the named *section*.  If *vars* is provided, it
       must be a dictionary.  The *option* is looked up in *vars* (if provided),
@@ -1025,21 +1025,21 @@
          (especially when using the mapping protocol).
 
 
-   .. method:: getint(section, option, raw=False, [vars, fallback])
+   .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
 
       A convenience method which coerces the *option* in the specified *section*
       to an integer.  See :meth:`get` for explanation of *raw*, *vars* and
       *fallback*.
 
 
-   .. method:: getfloat(section, option, raw=False, [vars, fallback])
+   .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
 
       A convenience method which coerces the *option* in the specified *section*
       to a floating point number.  See :meth:`get` for explanation of *raw*,
       *vars* and *fallback*.
 
 
-   .. method:: getboolean(section, option, raw=False, [vars, fallback])
+   .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
 
       A convenience method which coerces the *option* in the specified *section*
       to a Boolean value.  Note that the accepted values for the option are
@@ -1051,7 +1051,8 @@
       *fallback*.
 
 
-   .. method:: items([section], raw=False, vars=None)
+   .. method:: items(raw=False, vars=None)
+               items(section, raw=False, vars=None)
 
       When *section* is not given, return a list of *section_name*,
       *section_proxy* pairs, including DEFAULTSECT.
@@ -1149,7 +1150,13 @@
 RawConfigParser Objects
 -----------------------
 
-.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configaparser.DEFAULTSECT, interpolation=None)
+.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, \
+                           allow_no_value=False, *, delimiters=('=', ':'), \
+                           comment_prefixes=('#', ';'), \
+                           inline_comment_prefixes=None, strict=True, \
+                           empty_lines_in_values=True, \
+                           default_section=configparser.DEFAULTSECT[, \
+                           interpolation])
 
    Legacy variant of the :class:`ConfigParser` with interpolation disabled
    by default and unsafe ``add_section`` and ``set`` methods.
diff --git a/Doc/library/crypt.rst b/Doc/library/crypt.rst
--- a/Doc/library/crypt.rst
+++ b/Doc/library/crypt.rst
@@ -121,11 +121,14 @@
 Examples
 --------
 
-A simple example illustrating typical use::
+A simple example illustrating typical use (a constant-time comparison
+operation is needed to limit exposure to timing attacks.
+:func:`hmac.compare_digest` is suitable for this purpose)::
 
    import pwd
    import crypt
    import getpass
+   from hmac import compare_digest as compare_hash
 
    def login():
        username = input('Python login: ')
@@ -134,7 +137,7 @@
            if cryptedpasswd == 'x' or cryptedpasswd == '*':
                raise ValueError('no support for shadow passwords')
            cleartext = getpass.getpass()
-           return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd
+           return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
        else:
            return True
 
@@ -142,7 +145,8 @@
 check it against the original::
 
    import crypt
+   from hmac import compare_digest as compare_hash
 
    hashed = crypt.crypt(plaintext)
-   if hashed != crypt.crypt(plaintext, hashed):
+   if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
       raise ValueError("hashed version doesn't validate against original")
diff --git a/Doc/library/crypto.rst b/Doc/library/crypto.rst
--- a/Doc/library/crypto.rst
+++ b/Doc/library/crypto.rst
@@ -8,6 +8,7 @@
 
 The modules described in this chapter implement various algorithms of a
 cryptographic nature.  They are available at the discretion of the installation.
+On Unix systems, the :mod:`crypt` module may also be available.
 Here's an overview:
 
 
diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -71,9 +71,10 @@
    A short usage example::
 
       >>> import csv
-      >>> spamReader = csv.reader(open('eggs.csv', newline=''), delimiter=' ', quotechar='|')
-      >>> for row in spamReader:
-      ...     print(', '.join(row))
+      >>> with open('eggs.csv', newline='') as csvfile:
+      ...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
+      ...     for row in spamreader:
+      ...         print(', '.join(row))
       Spam, Spam, Spam, Spam, Spam, Baked Beans
       Spam, Lovely Spam, Wonderful Spam
 
@@ -99,11 +100,12 @@
 
    A short usage example::
 
-      >>> import csv
-      >>> spamWriter = csv.writer(open('eggs.csv', 'w', newline=''), delimiter=' ',
-      ...                         quotechar='|', quoting=csv.QUOTE_MINIMAL)
-      >>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
-      >>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
+      import csv
+      with open('eggs.csv', 'w', newline='') as csvfile:
+          spamwriter = csv.writer(csvfile, delimiter=' ',
+                                  quotechar='|', quoting=csv.QUOTE_MINIMAL)
+          spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
+          spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
 
 
 .. function:: register_dialect(name[, dialect], **fmtparams)
@@ -221,11 +223,11 @@
 
 An example for :class:`Sniffer` use::
 
-   csvfile = open("example.csv")
-   dialect = csv.Sniffer().sniff(csvfile.read(1024))
-   csvfile.seek(0)
-   reader = csv.reader(csvfile, dialect)
-   # ... process CSV file contents here ...
+   with open('example.csv') as csvfile:
+       dialect = csv.Sniffer().sniff(csvfile.read(1024))
+       csvfile.seek(0)
+       reader = csv.reader(csvfile, dialect)
+       # ... process CSV file contents here ...
 
 
 The :mod:`csv` module defines the following constants:
diff --git a/Doc/library/curses.rst b/Doc/library/curses.rst
--- a/Doc/library/curses.rst
+++ b/Doc/library/curses.rst
@@ -377,7 +377,8 @@
    is to be displayed.
 
 
-.. function:: newwin([nlines, ncols,] begin_y, begin_x)
+.. function:: newwin(begin_y, begin_x)
+              newwin(nlines, ncols, begin_y, begin_x)
 
    Return a new window, whose left-upper corner is at  ``(begin_y, begin_x)``, and
    whose height/width is  *nlines*/*ncols*.
@@ -656,7 +657,8 @@
 the following methods and attributes:
 
 
-.. method:: window.addch([y, x,] ch[, attr])
+.. method:: window.addch(ch[, attr])
+            window.addch(y, x, ch[, attr])
 
    .. note::
 
@@ -670,13 +672,15 @@
    position and attributes are the current settings for the window object.
 
 
-.. method:: window.addnstr([y, x,] str, n[, attr])
+.. method:: window.addnstr(str, n[, attr])
+            window.addnstr(y, x, str, n[, attr])
 
    Paint at most *n* characters of the  string *str* at ``(y, x)`` with attributes
    *attr*, overwriting anything previously on the display.
 
 
-.. method:: window.addstr([y, x,] str[, attr])
+.. method:: window.addstr(str[, attr])
+            window.addstr(y, x, str[, attr])
 
    Paint the string *str* at ``(y, x)`` with attributes *attr*, overwriting
    anything previously on the display.
@@ -763,7 +767,10 @@
    *bs* are *horch*.  The default corner characters are always used by this function.
 
 
-.. method:: window.chgat([y, x, ] [num,] attr)
+.. method:: window.chgat(attr)
+            window.chgat(num, attr)
+            window.chgat(y, x, attr)
+            window.chgat(y, x, num, attr)
 
    Set the attributes of *num* characters at the current cursor position, or at
    position ``(y, x)`` if supplied. If no value of *num* is given or *num* = -1,
@@ -812,7 +819,8 @@
    Delete the line under the cursor. All following lines are moved up by one line.
 
 
-.. method:: window.derwin([nlines, ncols,] begin_y, begin_x)
+.. method:: window.derwin(begin_y, begin_x)
+            window.derwin(nlines, ncols, begin_y, begin_x)
 
    An abbreviation for "derive window", :meth:`derwin` is the same as calling
    :meth:`subwin`, except that *begin_y* and *begin_x* are relative to the origin
@@ -837,7 +845,7 @@
 .. attribute:: window.encoding
 
    Encoding used to encode method arguments (Unicode strings and characters).
-   The encoding attribute is inherited from by parent window when a subwindow
+   The encoding attribute is inherited from the parent window when a subwindow
    is created, for example with :meth:`window.subwin`. By default, the locale
    encoding is used (see :func:`locale.getpreferredencoding`).
 
@@ -906,7 +914,8 @@
    upper-left corner.
 
 
-.. method:: window.hline([y, x,] ch, n)
+.. method:: window.hline(ch, n)
+            window.hline(y, x, ch, n)
 
    Display a horizontal line starting at ``(y, x)`` with length *n* consisting of
    the character *ch*.
@@ -940,7 +949,8 @@
    the character proper, and upper bits are the attributes.
 
 
-.. method:: window.insch([y, x,] ch[, attr])
+.. method:: window.insch(ch[, attr])
+            window.insch(y, x, ch[, attr])
 
    Paint character *ch* at ``(y, x)`` with attributes *attr*, moving the line from
    position *x* right by one character.
@@ -961,7 +971,8 @@
    line.
 
 
-.. method:: window.insnstr([y, x,] str, n [, attr])
+.. method:: window.insnstr(str, n[, attr])
+            window.insnstr(y, x, str, n[, attr])
 
    Insert a character string (as many characters as will fit on the line) before
    the character under the cursor, up to *n* characters.   If *n* is zero or
@@ -970,7 +981,8 @@
    The cursor position does not change (after moving to *y*, *x*, if specified).
 
 
-.. method:: window.insstr([y, x, ] str [, attr])
+.. method:: window.insstr(str[, attr])
+            window.insstr(y, x, str[, attr])
 
    Insert a character string (as many characters as will fit on the line) before
    the character under the cursor.  All characters to the right of the cursor are
@@ -978,7 +990,8 @@
    position does not change (after moving to *y*, *x*, if specified).
 
 
-.. method:: window.instr([y, x] [, n])
+.. method:: window.instr([n])
+            window.instr(y, x[, n])
 
    Return a string of characters, extracted from the window starting at the
    current cursor position, or at *y*, *x* if specified. Attributes are stripped
@@ -1153,13 +1166,15 @@
    Turn on attribute *A_STANDOUT*.
 
 
-.. method:: window.subpad([nlines, ncols,] begin_y, begin_x)
+.. method:: window.subpad(begin_y, begin_x)
+            window.subpad(nlines, ncols, begin_y, begin_x)
 
    Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and
    whose width/height is *ncols*/*nlines*.
 
 
-.. method:: window.subwin([nlines, ncols,] begin_y, begin_x)
+.. method:: window.subwin(begin_y, begin_x)
+            window.subwin(nlines, ncols, begin_y, begin_x)
 
    Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and
    whose width/height is *ncols*/*nlines*.
@@ -1216,7 +1231,8 @@
    :meth:`refresh`.
 
 
-.. method:: window.vline([y, x,] ch, n)
+.. method:: window.vline(ch, n)
+            window.vline(y, x, ch, n)
 
    Display a vertical line starting at ``(y, x)`` with length *n* consisting of the
    character *ch*.
diff --git a/Doc/library/doctest.rst b/Doc/library/doctest.rst
--- a/Doc/library/doctest.rst
+++ b/Doc/library/doctest.rst
@@ -338,7 +338,7 @@
      Backslashes in a raw docstring: m\n
 
   Otherwise, the backslash will be interpreted as part of the string. For example,
-  the "\\" above would be interpreted as a newline character.  Alternatively, you
+  the ``\n`` above would be interpreted as a newline character.  Alternatively, you
   can double each backslash in the doctest version (and not use a raw string)::
 
      >>> def f(x):
@@ -1024,6 +1024,16 @@
 
    This function uses the same search technique as :func:`testmod`.
 
+   .. note::
+      Unlike :func:`testmod` and :class:`DocTestFinder`, this function raises
+      a :exc:`ValueError` if *module* contains no docstrings.  You can prevent
+      this error by passing a :class:`DocTestFinder` instance as the
+      *test_finder* argument with its *exclude_empty* keyword argument set
+      to ``False``::
+
+         >>> finder = doctest.DocTestFinder(exclude_empty=False)
+         >>> suite = doctest.DocTestSuite(test_finder=finder)
+
 
 Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
 of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -629,14 +629,19 @@
    to provide elaborate line editing and history features.
 
 
-.. function:: int([number | string[, base]])
+.. function:: int(x=0)
+              int(x, base=10)
 
-   Convert a number or string to an integer.  If no arguments are given, return
-   ``0``.  If a number is given, return ``number.__int__()``.  Conversion of
-   floating point numbers to integers truncates towards zero.  A string must be
-   a base-radix integer literal optionally preceded by '+' or '-' (with no space
-   in between) and optionally surrounded by whitespace.  A base-n literal
-   consists of the digits 0 to n-1, with 'a' to 'z' (or 'A' to 'Z') having
+   Convert a number or string *x* to an integer, or return ``0`` if no
+   arguments are given.  If *x* is a number, return :meth:`x.__int__()
+   <object.__int__>`.  For floating point numbers, this truncates towards zero.
+
+   If *x* is not a number or if *base* is given, then *x* must be a string,
+   :class:`bytes`, or :class:`bytearray` instance representing an :ref:`integer
+   literal <integers>` in radix *base*.  Optionally, the literal can be
+   preceded by ``+`` or ``-`` (with no space in between) and surrounded by
+   whitespace.  A base-n literal consists of the digits 0 to n-1, with ``a``
+   to ``z`` (or ``A`` to ``Z``) having
    values 10 to 35.  The default *base* is 10. The allowed values are 0 and 2-36.
    Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``,
    ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code.  Base 0
@@ -725,11 +730,16 @@
    already arranged into argument tuples, see :func:`itertools.starmap`\.
 
 
-.. function:: max(iterable[, args...], *[, key])
+.. function:: max(iterable, *[, key])
+              max(arg1, arg2, *args[, key])
 
-   With a single argument *iterable*, return the largest item of a non-empty
-   iterable (such as a string, tuple or list).  With more than one argument, return
-   the largest of the arguments.
+   Return the largest item in an iterable or the largest of two or more
+   arguments.
+
+   If one positional argument is provided, *iterable* must be a non-empty
+   iterable (such as a non-empty string, tuple or list).  The largest item
+   in the iterable is returned.  If two or more positional arguments are
+   provided, the largest of the positional arguments is returned.
 
    The optional keyword-only *key* argument specifies a one-argument ordering
    function like that used for :meth:`list.sort`.
@@ -748,11 +758,16 @@
    :ref:`typememoryview` for more information.
 
 
-.. function:: min(iterable[, args...], *[, key])
+.. function:: min(iterable, *[, key])
+              min(arg1, arg2, *args[, key])
 
-   With a single argument *iterable*, return the smallest item of a non-empty
-   iterable (such as a string, tuple or list).  With more than one argument, return
-   the smallest of the arguments.
+   Return the smallest item in an iterable or the smallest of two or more
+   arguments.
+
+   If one positional argument is provided, *iterable* must be a non-empty
+   iterable (such as a non-empty string, tuple or list).  The smallest item
+   in the iterable is returned.  If two or more positional arguments are
+   provided, the smallest of the positional arguments is returned.
 
    The optional keyword-only *key* argument specifies a one-argument ordering
    function like that used for :meth:`list.sort`.
@@ -970,16 +985,16 @@
    must be of integer types, and *y* must be non-negative.
 
 
-.. function:: print([object, ...], *, sep=' ', end='\\n', file=sys.stdout, flush=False)
+.. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)
 
-   Print *object*\(s) to the stream *file*, separated by *sep* and followed by
+   Print *objects* to the stream *file*, separated by *sep* and followed by
    *end*.  *sep*, *end* and *file*, if present, must be given as keyword
    arguments.
 
    All non-keyword arguments are converted to strings like :func:`str` does and
    written to the stream, separated by *sep* and followed by *end*.  Both *sep*
    and *end* must be strings; they can also be ``None``, which means to use the
-   default values.  If no *object* is given, :func:`print` will just write
+   default values.  If no *objects* are given, :func:`print` will just write
    *end*.
 
    The *file* argument must be an object with a ``write(string)`` method; if it
@@ -1061,7 +1076,8 @@
 
 
 .. _func-range:
-.. function:: range([start,] stop[, step])
+.. function:: range(stop)
+              range(start, stop[, step])
    :noindex:
 
    Rather than being a function, :class:`range` is actually an immutable
@@ -1087,18 +1103,18 @@
    arguments starting at ``0``).
 
 
-.. function:: round(x[, n])
+.. function:: round(number[, ndigits])
 
-   Return the floating point value *x* rounded to *n* digits after the decimal
-   point.  If *n* is omitted, it defaults to zero.  Delegates to
-   ``x.__round__(n)``.
+   Return the floating point value *number* rounded to *ndigits* digits after
+   the decimal point.  If *ndigits* is omitted, it defaults to zero. Delegates
+   to ``number.__round__(ndigits)``.
 
    For the built-in types supporting :func:`round`, values are rounded to the
-   closest multiple of 10 to the power minus *n*; if two multiples are equally
-   close, rounding is done toward the even choice (so, for example, both
-   ``round(0.5)`` and ``round(-0.5)`` are ``0``, and ``round(1.5)`` is ``2``).
-   The return value is an integer if called with one argument, otherwise of the
-   same type as *x*.
+   closest multiple of 10 to the power minus *ndigits*; if two multiples are
+   equally close, rounding is done toward the even choice (so, for example,
+   both ``round(0.5)`` and ``round(-0.5)`` are ``0``, and ``round(1.5)`` is
+   ``2``).  The return value is an integer if called with one argument,
+   otherwise of the same type as *number*.
 
    .. note::
 
@@ -1126,7 +1142,8 @@
    ``x.foobar = 123``.
 
 
-.. function:: slice([start,] stop[, step])
+.. function:: slice(stop)
+              slice(start, stop[, step])
 
    .. index:: single: Numerical Python
 
diff --git a/Doc/library/http.client.rst b/Doc/library/http.client.rst
--- a/Doc/library/http.client.rst
+++ b/Doc/library/http.client.rst
@@ -27,7 +27,8 @@
 The module provides the following classes:
 
 
-.. class:: HTTPConnection(host, port=None[, strict[, timeout[, source_address]]])
+.. class:: HTTPConnection(host, port=None[, strict][, timeout], \
+                          source_address=None)
 
    An :class:`HTTPConnection` instance represents one transaction with an HTTP
    server.  It should be instantiated passing it a host and optional port
@@ -55,7 +56,10 @@
       are not supported anymore.
 
 
-.. class:: HTTPSConnection(host, port=None, key_file=None, cert_file=None[, strict[, timeout[, source_address]]], *, context=None, check_hostname=None)
+.. class:: HTTPSConnection(host, port=None, key_file=None, \
+                           cert_file=None[, strict][, timeout], \
+                           source_address=None, *, context=None, \
+                           check_hostname=None)
 
    A subclass of :class:`HTTPConnection` that uses SSL for communication with
    secure servers.  Default port is ``443``.  If *context* is specified, it
diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -471,7 +471,7 @@
       Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
       passed arguments do not match the signature.
 
-   .. method:: Signature.replace([parameters], *, [return_annotation])
+   .. method:: Signature.replace(*[, parameters][, return_annotation])
 
       Create a new Signature instance based on the instance replace was invoked
       on.  It is possible to pass different ``parameters`` and/or
@@ -565,7 +565,7 @@
          ...         print('Parameter:', param)
          Parameter: c
 
-   .. method:: Parameter.replace(*, [name], [kind], [default], [annotation])
+   .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
 
       Create a new Parameter instance based on the instance replaced was invoked
       on.  To override a :class:`Parameter` attribute, pass the corresponding
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -401,7 +401,8 @@
                   self.currkey = self.keyfunc(self.currvalue)
 
 
-.. function:: islice(iterable, [start,] stop [, step])
+.. function:: islice(iterable, stop)
+              islice(iterable, start, stop[, step])
 
    Make an iterator that returns selected elements from the iterable. If *start* is
    non-zero, then elements from the iterable are skipped until start is reached.
diff --git a/Doc/library/json.rst b/Doc/library/json.rst
--- a/Doc/library/json.rst
+++ b/Doc/library/json.rst
@@ -146,9 +146,12 @@
    object members will be pretty-printed with that indent level.  An indent level
    of 0, negative, or ``""`` will only insert newlines.  ``None`` (the default)
    selects the most compact representation. Using a positive integer indent
-   indents that many spaces per level.  If *indent* is a string (such at '\t'),
+   indents that many spaces per level.  If *indent* is a string (such as ``"\t"``),
    that string is used to indent each level.
 
+   .. versionchanged:: 3.2
+      Allow strings for *indent* in addition to integers.
+
    If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
    will be used instead of the default ``(', ', ': ')`` separators.  ``(',',
    ':')`` is the most compact JSON representation.
@@ -371,10 +374,15 @@
    will be sorted by key; this is useful for regression tests to ensure that
    JSON serializations can be compared on a day-to-day basis.
 
-   If *indent* is a non-negative integer (it is ``None`` by default), then JSON
-   array elements and object members will be pretty-printed with that indent
-   level.  An indent level of 0 will only insert newlines.  ``None`` is the most
-   compact representation.
+   If *indent* is a non-negative integer or string, then JSON array elements and
+   object members will be pretty-printed with that indent level.  An indent level
+   of 0, negative, or ``""`` will only insert newlines.  ``None`` (the default)
+   selects the most compact representation. Using a positive integer indent
+   indents that many spaces per level.  If *indent* is a string (such as ``"\t"``),
+   that string is used to indent each level.
+
+   .. versionchanged:: 3.2
+      Allow strings for *indent* in addition to integers.
 
    If specified, *separators* should be an ``(item_separator, key_separator)``
    tuple.  The default is ``(', ', ': ')``.  To get the most compact JSON
diff --git a/Doc/library/lzma.rst b/Doc/library/lzma.rst
--- a/Doc/library/lzma.rst
+++ b/Doc/library/lzma.rst
@@ -335,15 +335,15 @@
 Reading in a compressed file::
 
    import lzma
-   with lzma.LZMAFile("file.xz") as f:
-      file_content = f.read()
+   with lzma.open("file.xz") as f:
+       file_content = f.read()
 
 Creating a compressed file::
 
    import lzma
    data = b"Insert Data Here"
-   with lzma.LZMAFile("file.xz", "w") as f:
-      f.write(data)
+   with lzma.open("file.xz", "w") as f:
+       f.write(data)
 
 Compressing data in memory::
 
@@ -367,7 +367,7 @@
    import lzma
    with open("file.xz", "wb") as f:
        f.write(b"This data will not be compressed\n")
-       with lzma.LZMAFile(f, "w") as lzf:
+       with lzma.open(f, "w") as lzf:
            lzf.write(b"This *will* be compressed\n")
        f.write(b"Not compressed\n")
 
@@ -378,5 +378,5 @@
        {"id": lzma.FILTER_DELTA, "dist": 5},
        {"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME},
    ]
-   with lzma.LZMAFile("file.xz", "w", filters=my_filters) as f:
+   with lzma.open("file.xz", "w", filters=my_filters) as f:
        f.write(b"blah blah blah")
diff --git a/Doc/library/mailbox.rst b/Doc/library/mailbox.rst
--- a/Doc/library/mailbox.rst
+++ b/Doc/library/mailbox.rst
@@ -10,9 +10,9 @@
 This module defines two classes, :class:`Mailbox` and :class:`Message`, for
 accessing and manipulating on-disk mailboxes and the messages they contain.
 :class:`Mailbox` offers a dictionary-like mapping from keys to messages.
-:class:`Message` extends the :mod:`email.Message` module's :class:`Message`
-class with format-specific state and behavior. Supported mailbox formats are
-Maildir, mbox, MH, Babyl, and MMDF.
+:class:`Message` extends the :mod:`email.message` module's
+:class:`~email.message.Message` class with format-specific state and behavior.
+Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.
 
 
 .. seealso::
@@ -81,7 +81,7 @@
       it.
 
       Parameter *message* may be a :class:`Message` instance, an
-      :class:`email.Message.Message` instance, a string, a byte string, or a
+      :class:`email.message.Message` instance, a string, a byte string, or a
       file-like object (which should be open in binary mode). If *message* is
       an instance of the
       appropriate format-specific :class:`Message` subclass (e.g., if it's an
@@ -112,7 +112,7 @@
       :exc:`KeyError` exception if no message already corresponds to *key*.
 
       As with :meth:`add`, parameter *message* may be a :class:`Message`
-      instance, an :class:`email.Message.Message` instance, a string, a byte
+      instance, an :class:`email.message.Message` instance, a string, a byte
       string, or a file-like object (which should be open in binary mode). If
       *message* is an
       instance of the appropriate format-specific :class:`Message` subclass
@@ -757,11 +757,12 @@
 
 .. class:: Message(message=None)
 
-   A subclass of the :mod:`email.Message` module's :class:`Message`. Subclasses of
-   :class:`mailbox.Message` add mailbox-format-specific state and behavior.
+   A subclass of the :mod:`email.message` module's
+   :class:`~email.message.Message`. Subclasses of :class:`mailbox.Message` add
+   mailbox-format-specific state and behavior.
 
    If *message* is omitted, the new instance is created in a default, empty state.
-   If *message* is an :class:`email.Message.Message` instance, its contents are
+   If *message* is an :class:`email.message.Message` instance, its contents are
    copied; furthermore, any format-specific information is converted insofar as
    possible if *message* is a :class:`Message` instance. If *message* is a string,
    a byte string,
@@ -1267,7 +1268,7 @@
 
       Set the message's visible headers to be the same as the headers in
       *message*.  Parameter *visible* should be a :class:`Message` instance, an
-      :class:`email.Message.Message` instance, a string, or a file-like object
+      :class:`email.message.Message` instance, a string, or a file-like object
       (which should be open in text mode).
 
 
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -295,7 +295,8 @@
 :class:`Process` and exceptions
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-.. class:: Process([group[, target[, name[, args[, kwargs]]]]], *, daemon=None)
+.. class:: Process(group=None, target=None, name=None, args=(), kwargs={}, \
+                   *, daemon=None)
 
    Process objects represent activity that is run in a separate process. The
    :class:`Process` class has equivalents of all the methods of
@@ -1147,7 +1148,7 @@
 
        n = Value('i', 7)
        x = Value(c_double, 1.0/3.0, lock=False)
-       s = Array('c', 'hello world', lock=lock)
+       s = Array('c', b'hello world', lock=lock)
        A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)
 
        p = Process(target=modify, args=(n, x, s, A))
diff --git a/Doc/library/nntplib.rst b/Doc/library/nntplib.rst
--- a/Doc/library/nntplib.rst
+++ b/Doc/library/nntplib.rst
@@ -487,10 +487,10 @@
 them have been superseded by newer commands in :rfc:`3977`.
 
 
-.. method:: NNTP.xhdr(header, string, *, file=None)
+.. method:: NNTP.xhdr(hdr, str, *, file=None)
 
-   Send an ``XHDR`` command.  The *header* argument is a header keyword, e.g.
-   ``'subject'``.  The *string* argument should have the form ``'first-last'``
+   Send an ``XHDR`` command.  The *hdr* argument is a header keyword, e.g.
+   ``'subject'``.  The *str* argument should have the form ``'first-last'``
    where *first* and *last* are the first and last article numbers to search.
    Return a pair ``(response, list)``, where *list* is a list of pairs ``(id,
    text)``, where *id* is an article number (as a string) and *text* is the text of
diff --git a/Doc/library/optparse.rst b/Doc/library/optparse.rst
--- a/Doc/library/optparse.rst
+++ b/Doc/library/optparse.rst
@@ -273,7 +273,8 @@
 strings as you like (including zero), as long as there is at least one option
 string overall.
 
-The option strings passed to :meth:`add_option` are effectively labels for the
+The option strings passed to :meth:`OptionParser.add_option` are effectively
+labels for the
 option defined by that call.  For brevity, we will frequently refer to
 *encountering an option* on the command line; in reality, :mod:`optparse`
 encounters *option strings* and looks up options from them.
@@ -892,7 +893,8 @@
 The canonical way to create an :class:`Option` instance is with the
 :meth:`add_option` method of :class:`OptionParser`.
 
-.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
+.. method:: OptionParser.add_option(option)
+            OptionParser.add_option(*opt_str, attr=value, ...)
 
    To define an option with only a short option string::
 
@@ -1165,6 +1167,17 @@
 
      options.tracks.append(int("4"))
 
+  The ``append`` action calls the ``append`` method on the current value of the
+  option.  This means that any default value specified must have an ``append``
+  method.  It also means that if the default value is non-empty, the default
+  elements will be present in the parsed value for the option, with any values
+  from the command line appended after those default values::
+
+     >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
+     >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
+     >>> opts.files
+     ['~/.mypkg/defaults', 'overrides.mypkg']
+
 * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
   :attr:`~Option.dest`]
 
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -1855,9 +1855,8 @@
    :attr:`st_mtime`, :attr:`st_ctime`. More items may be added at the end by
    some implementations.
 
-   This function can support :ref:`specifying a file descriptor
-   <path_fd>`, :ref:`specifying a file descriptor <path_fd>` and :ref:`not
-   following symlinks <follow_symlinks>`.
+   This function can support :ref:`specifying a file descriptor <path_fd>` and
+   :ref:`not following symlinks <follow_symlinks>`.
 
    .. index:: module: stat
 
diff --git a/Doc/library/ossaudiodev.rst b/Doc/library/ossaudiodev.rst
--- a/Doc/library/ossaudiodev.rst
+++ b/Doc/library/ossaudiodev.rst
@@ -67,7 +67,8 @@
    ``ossaudiodev.error``.)
 
 
-.. function:: open([device, ]mode)
+.. function:: open(mode)
+              open(device, mode)
 
    Open an audio device and return an OSS audio device object.  This object
    supports many file-like methods, such as :meth:`read`, :meth:`write`, and
diff --git a/Doc/library/pyexpat.rst b/Doc/library/pyexpat.rst
--- a/Doc/library/pyexpat.rst
+++ b/Doc/library/pyexpat.rst
@@ -402,7 +402,7 @@
 .. method:: xmlparser.CommentHandler(data)
 
    Called for comments.  *data* is the text of the comment, excluding the leading
-   '``<!-``\ ``-``' and trailing '``-``\ ``->``'.
+   ``'<!-``\ ``-'`` and trailing ``'-``\ ``->'``.
 
 
 .. method:: xmlparser.StartCdataSectionHandler()
diff --git a/Doc/library/random.rst b/Doc/library/random.rst
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -52,20 +52,20 @@
 
 Bookkeeping functions:
 
-.. function:: seed([x], version=2)
+.. function:: seed(a=None, version=2)
 
    Initialize the random number generator.
 
-   If *x* is omitted or ``None``, the current system time is used.  If
+   If *a* is omitted or ``None``, the current system time is used.  If
    randomness sources are provided by the operating system, they are used
    instead of the system time (see the :func:`os.urandom` function for details
    on availability).
 
-   If *x* is an int, it is used directly.
+   If *a* is an int, it is used directly.
 
    With version 2 (the default), a :class:`str`, :class:`bytes`, or :class:`bytearray`
    object gets converted to an :class:`int` and all of its bits are used.  With version 1,
-   the :func:`hash` of *x* is used instead.
+   the :func:`hash` of *a* is used instead.
 
    .. versionchanged:: 3.2
       Moved to the version 2 scheme which uses all of the bits in a string seed.
@@ -93,7 +93,8 @@
 
 Functions for integers:
 
-.. function:: randrange([start,] stop[, step])
+.. function:: randrange(stop)
+              randrange(start, stop[, step])
 
    Return a randomly selected element from ``range(start, stop, step)``.  This is
    equivalent to ``choice(range(start, stop, step))``, but doesn't actually build a
diff --git a/Doc/library/site.rst b/Doc/library/site.rst
--- a/Doc/library/site.rst
+++ b/Doc/library/site.rst
@@ -33,7 +33,7 @@
 For the head part, it uses ``sys.prefix`` and ``sys.exec_prefix``; empty heads
 are skipped.  For the tail part, it uses the empty string and then
 :file:`lib/site-packages` (on Windows) or
-:file:`lib/python|version|/site-packages` and then :file:`lib/site-python` (on
+:file:`lib/python{X.Y}/site-packages` and then :file:`lib/site-python` (on
 Unix and Macintosh).  For each of the distinct head-tail combinations, it sees
 if it refers to an existing directory, and if so, adds it to ``sys.path`` and
 also inspects the newly added path for configuration files.
diff --git a/Doc/library/smtpd.rst b/Doc/library/smtpd.rst
--- a/Doc/library/smtpd.rst
+++ b/Doc/library/smtpd.rst
@@ -111,12 +111,13 @@
    .. attribute:: addr
 
       Holds the address of the client, the second value returned by
-      socket.accept()
+      :func:`socket.accept <socket.socket.accept>`
 
    .. attribute:: received_lines
 
       Holds a list of the line strings (decoded using UTF-8) received from
-      the client. The lines have their "\\r\\n" line ending translated to "\\n".
+      the client. The lines have their ``"\r\n"`` line ending translated to
+      ``"\n"``.
 
    .. attribute:: smtp_state
 
@@ -141,12 +142,12 @@
    .. attribute:: received_data
 
       Holds a string containing all of the data sent by the client during the
-      DATA state, up to but not including the terminating "\r\n.\r\n".
+      DATA state, up to but not including the terminating ``"\r\n.\r\n"``.
 
    .. attribute:: fqdn
 
       Holds the fully-qualified domain name of the server as returned by
-      ``socket.getfqdn()``.
+      :func:`socket.getfqdn`.
 
    .. attribute:: peer
 
@@ -170,14 +171,14 @@
    MAIL     Accepts the "MAIL FROM:" syntax and stores the supplied address as
             :attr:`mailfrom`.  In extended command mode, accepts the
             :rfc:`1870` SIZE attribute and responds appropriately based on the
-            value of ``data_size_limit``.
+            value of *data_size_limit*.
    RCPT     Accepts the "RCPT TO:" syntax and stores the supplied addresses in
             the :attr:`rcpttos` list.
    RSET     Resets the :attr:`mailfrom`, :attr:`rcpttos`, and
             :attr:`received_data`, but not the greeting.
    DATA     Sets the internal state to :attr:`DATA` and stores remaining lines
             from the client in :attr:`received_data` until the terminator
-            "\r\n.\r\n" is received.
+            ``"\r\n.\r\n"`` is received.
    HELP     Returns minimal information on command syntax
    VRFY     Returns code 252 (the server doesn't know if the address is valid)
    EXPN     Reports that the command is not implemented.
diff --git a/Doc/library/socket.rst b/Doc/library/socket.rst
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -1005,7 +1005,8 @@
    much data, if any, was successfully sent.
 
 
-.. method:: socket.sendto(bytes[, flags], address)
+.. method:: socket.sendto(bytes, address)
+            socket.sendto(bytes, flags, address)
 
    Send data to the socket.  The socket should not be connected to a remote socket,
    since the destination socket is specified by *address*.  The optional *flags*
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1235,7 +1235,8 @@
 commonly used for looping a specific number of times in :keyword:`for`
 loops.
 
-.. class:: range([start, ]stop[, step])
+.. class:: range(stop)
+           range(start, stop[, step])
 
    The arguments to the range constructor must be integers (either built-in
    :class:`int` or any object that implements the ``__index__`` special
@@ -2687,13 +2688,19 @@
    .. attribute:: shape
 
       A tuple of integers the length of :attr:`ndim` giving the shape of the
-      memory as a N-dimensional array.
+      memory as an N-dimensional array.
+
+      .. versionchanged:: 3.3
+         An empty tuple instead of None when ndim = 0.
 
    .. attribute:: strides
 
       A tuple of integers the length of :attr:`ndim` giving the size in bytes to
       access each element for each dimension of the array.
 
+      .. versionchanged:: 3.3
+         An empty tuple instead of None when ndim = 0.
+
    .. attribute:: suboffsets
 
       Used internally for PIL-style arrays. The value is informational only.
diff --git a/Doc/library/subprocess.rst b/Doc/library/subprocess.rst
--- a/Doc/library/subprocess.rst
+++ b/Doc/library/subprocess.rst
@@ -307,10 +307,14 @@
       :meth:`Popen.communicate` method.
 
    If *shell* is ``True``, the specified command will be executed through
-   the shell. This can be useful if you are using Python primarily for the
+   the shell.  This can be useful if you are using Python primarily for the
    enhanced control flow it offers over most system shells and still want
-   access to other shell features such as filename wildcards, shell pipes and
-   environment variable expansion.
+   convenient access to other shell features such as shell pipes, filename
+   wildcards, environment variable expansion, and expansion of ``~`` to a
+   user's home directory.  However, note that Python itself offers
+   implementations of many shell-like features (in particular, :mod:`glob`,
+   :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`,
+   :func:`os.path.expanduser`, and :mod:`shutil`).
 
    .. versionchanged:: 3.3
       When *universal_newlines* is ``True``, the class uses the encoding
@@ -669,8 +673,8 @@
 
 .. warning::
 
-   Use :meth:`communicate` rather than :attr:`.stdin.write <stdin>`,
-   :attr:`.stdout.read <stdout>` or :attr:`.stderr.read <stderr>` to avoid
+   Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
+   :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
    deadlocks due to any of the other OS pipe buffers filling up and blocking the
    child process.
 
diff --git a/Doc/library/syslog.rst b/Doc/library/syslog.rst
--- a/Doc/library/syslog.rst
+++ b/Doc/library/syslog.rst
@@ -17,7 +17,8 @@
 The module defines the following functions:
 
 
-.. function:: syslog([priority,] message)
+.. function:: syslog(message)
+              syslog(priority, message)
 
    Send the string *message* to the system logger.  A trailing newline is added
    if necessary.  Each message is tagged with a priority composed of a
diff --git a/Doc/library/textwrap.rst b/Doc/library/textwrap.rst
--- a/Doc/library/textwrap.rst
+++ b/Doc/library/textwrap.rst
@@ -25,6 +25,9 @@
    Optional keyword arguments correspond to the instance attributes of
    :class:`TextWrapper`, documented below.  *width* defaults to ``70``.
 
+   See the :meth:`TextWrapper.wrap` method for additional details on how
+   :func:`wrap` behaves.
+
 
 .. function:: fill(text, width=70, **kwargs)
 
@@ -167,15 +170,18 @@
 
    .. attribute:: drop_whitespace
 
-      (default: ``True``) If true, whitespace that, after wrapping, happens to
-      end up at the beginning or end of a line is dropped (leading whitespace in
-      the first line is always preserved, though).
+      (default: ``True``) If true, whitespace at the beginning and ending of
+      every line (after wrapping but before indenting) is dropped.
+      Whitespace at the beginning of the paragraph, however, is not dropped
+      if non-whitespace follows it.  If whitespace being dropped takes up an
+      entire line, the whole line is dropped.
 
 
    .. attribute:: initial_indent
 
       (default: ``''``) String that will be prepended to the first line of
-      wrapped output.  Counts towards the length of the first line.
+      wrapped output.  Counts towards the length of the first line.  The empty
+      string is not indented.
 
 
    .. attribute:: subsequent_indent
@@ -236,8 +242,9 @@
 
       Wraps the single paragraph in *text* (a string) so every line is at most
       :attr:`width` characters long.  All wrapping options are taken from
-      instance attributes of the :class:`TextWrapper` instance. Returns a list
-      of output lines, without final newlines.
+      instance attributes of the :class:`TextWrapper` instance.  Returns a list
+      of output lines, without final newlines.  If the wrapped output has no
+      content, the returned list is empty.
 
 
    .. method:: fill(text)
diff --git a/Doc/library/threading.rst b/Doc/library/threading.rst
--- a/Doc/library/threading.rst
+++ b/Doc/library/threading.rst
@@ -255,8 +255,8 @@
 since it is impossible to detect the termination of alien threads.
 
 
-.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={},
-                  verbose=None, *, daemon=None)
+.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}, *, \
+                  daemon=None)
 
    This constructor should always be called with keyword arguments.  Arguments
    are:
@@ -275,8 +275,6 @@
    *kwargs* is a dictionary of keyword arguments for the target invocation.
    Defaults to ``{}``.
 
-   *verbose* is a flag used for debugging messages.
-
    If not ``None``, *daemon* explicitly sets whether the thread is daemonic.
    If ``None`` (the default), the daemonic property is inherited from the
    current thread.
diff --git a/Doc/library/timeit.rst b/Doc/library/timeit.rst
--- a/Doc/library/timeit.rst
+++ b/Doc/library/timeit.rst
@@ -31,13 +31,13 @@
    may also contain multiple statements separated by ``;`` or newlines, as long as
    they don't contain multi-line string literals.
 
-   To measure the execution time of the first statement, use the :meth:`timeit`
-   method.  The :meth:`repeat` method is a convenience to call :meth:`timeit`
+   To measure the execution time of the first statement, use the :meth:`Timer.timeit`
+   method.  The :meth:`repeat` method is a convenience to call :meth:`.timeit`
    multiple times and return a list of results.
 
    The *stmt* and *setup* parameters can also take objects that are callable
    without arguments. This will embed calls to them in a timer function that
-   will then be executed by :meth:`timeit`.  Note that the timing overhead is a
+   will then be executed by :meth:`.timeit`.  Note that the timing overhead is a
    little larger in this case because of the extra function calls.
 
 
@@ -60,12 +60,12 @@
 
 .. method:: Timer.repeat(repeat=3, number=1000000)
 
-   Call :meth:`timeit` a few times.
+   Call :meth:`.timeit` a few times.
 
-   This is a convenience function that calls the :meth:`timeit` repeatedly,
+   This is a convenience function that calls the :meth:`.timeit` repeatedly,
    returning a list of results.  The first argument specifies how many times to
-   call :meth:`timeit`.  The second argument specifies the *number* argument for
-   :func:`timeit`.
+   call :meth:`.timeit`.  The second argument specifies the *number* argument for
+   :meth:`.timeit`.
 
    .. note::
 
@@ -89,7 +89,7 @@
 
    .. note::
 
-      By default, :meth:`timeit` temporarily turns off :term:`garbage collection`
+      By default, :meth:`.timeit` temporarily turns off :term:`garbage collection`
       during the timing.  The advantage of this approach is that it makes
       independent timings more comparable.  This disadvantage is that GC may be
       an important component of the performance of the function being measured.
@@ -117,7 +117,7 @@
 .. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
 
    Create a :class:`Timer` instance with the given statement, setup code and timer
-   function and run its :meth:`timeit` method with *number* executions.
+   function and run its :meth:`.timeit` method with *number* executions.
 
 
 Command Line Interface
@@ -243,7 +243,7 @@
    3.15 usec/pass
 
 To give the :mod:`timeit` module access to functions you define, you can pass a
-``setup`` parameter which contains an import statement::
+*setup* parameter which contains an import statement::
 
    def test():
        """Stupid test function"""
diff --git a/Doc/library/tkinter.tix.rst b/Doc/library/tkinter.tix.rst
--- a/Doc/library/tkinter.tix.rst
+++ b/Doc/library/tkinter.tix.rst
@@ -504,7 +504,7 @@
       print(root.tix_configure())
 
 
-.. method:: tixCommand.tix_configure([cnf,] **kw)
+.. method:: tixCommand.tix_configure(cnf=None, **kw)
 
    Query or modify the configuration options of the Tix application context. If no
    option is specified, returns a dictionary all of the available options.  If
diff --git a/Doc/library/types.rst b/Doc/library/types.rst
--- a/Doc/library/types.rst
+++ b/Doc/library/types.rst
@@ -69,7 +69,7 @@
 the types that arise only incidentally during processing such as the
 ``listiterator`` type.
 
-Typical use is of these names is for :func:`isinstance` or
+Typical use of these names is for :func:`isinstance` or
 :func:`issubclass` checks.
 
 Standard names are defined for the following types:
diff --git a/Doc/library/unittest.mock.rst b/Doc/library/unittest.mock.rst
--- a/Doc/library/unittest.mock.rst
+++ b/Doc/library/unittest.mock.rst
@@ -276,7 +276,7 @@
             >>> mock.assert_called_once_with('foo', bar='baz')
             Traceback (most recent call last):
               ...
-            AssertionError: Expected to be called once. Called 2 times.
+            AssertionError: Expected 'mock' to be called once. Called 2 times.
 
 
     .. method:: assert_any_call(*args, **kwargs)
@@ -2020,7 +2020,7 @@
     >>> mock.assert_called_once_with(1, 2, 3)
     Traceback (most recent call last):
      ...
-    AssertionError: Expected to be called once. Called 2 times.
+    AssertionError: Expected 'mock' to be called once. Called 2 times.
 
 Because mocks auto-create attributes on demand, and allow you to call them
 with arbitrary arguments, if you misspell one of these assert methods then
diff --git a/Doc/library/unittest.rst b/Doc/library/unittest.rst
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -1265,7 +1265,7 @@
    .. method:: assertListEqual(first, second, msg=None)
                assertTupleEqual(first, second, msg=None)
 
-      Tests that two lists or tuples are equal.  If not an error message is
+      Tests that two lists or tuples are equal.  If not, an error message is
       constructed that shows only the differences between the two.  An error
       is also raised if either of the parameters are of the wrong type.
       These methods are used by default when comparing lists or tuples with
diff --git a/Doc/library/urllib.parse.rst b/Doc/library/urllib.parse.rst
--- a/Doc/library/urllib.parse.rst
+++ b/Doc/library/urllib.parse.rst
@@ -145,8 +145,9 @@
    percent-encoded sequences into Unicode characters, as accepted by the
    :meth:`bytes.decode` method.
 
-   Use the :func:`urllib.parse.urlencode` function to convert such
-   dictionaries into query strings.
+   Use the :func:`urllib.parse.urlencode` function (with the ``doseq``
+   parameter set to ``True``) to convert such dictionaries into query
+   strings.
 
 
    .. versionchanged:: 3.2
diff --git a/Doc/license.rst b/Doc/license.rst
--- a/Doc/license.rst
+++ b/Doc/license.rst
@@ -327,7 +327,7 @@
 ----------------
 
 The :mod:`_random` module includes code based on a download from
-http://www.math.keio.ac.jp/ matumoto/MT2002/emt19937ar.html. The following are
+http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. The following are
 the verbatim comments from the original code::
 
    A C-program for MT19937, with initialization improved 2002/1/26.
@@ -368,8 +368,8 @@
 
 
    Any feedback is very welcome.
-   http://www.math.keio.ac.jp/matumoto/emt.html
-   email: matumoto at math.keio.ac.jp
+   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
+   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
 
 
 Sockets
diff --git a/Doc/reference/compound_stmts.rst b/Doc/reference/compound_stmts.rst
--- a/Doc/reference/compound_stmts.rst
+++ b/Doc/reference/compound_stmts.rst
@@ -307,11 +307,11 @@
 :keyword:`try` clause is executed, including any :keyword:`except` and
 :keyword:`else` clauses.  If an exception occurs in any of the clauses and is
 not handled, the exception is temporarily saved. The :keyword:`finally` clause
-is executed.  If there is a saved exception or :keyword:`break` statement,
-it is re-raised at the end of the :keyword:`finally` clause. If the
-:keyword:`finally` clause raises another exception the saved exception
-is set as the context of the new exception; if the :keyword:`finally` clause
-executes a :keyword:`return` statement, the saved exception is discarded::
+is executed.  If there is a saved exception it is re-raised at the end of the
+:keyword:`finally` clause.  If the :keyword:`finally` clause raises another
+exception, the saved exception is set as the context of the new exception.
+If the :keyword:`finally` clause executes a :keyword:`return` or :keyword:`break`
+statement, the saved exception is discarded::
 
     def f():
         try:
diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -1271,22 +1271,22 @@
    and ``x.__hash__()`` returns an appropriate value such that ``x == y``
    implies both that ``x is y`` and ``hash(x) == hash(y)``.
 
-   Classes which inherit a :meth:`__hash__` method from a parent class but
-   change the meaning of :meth:`__eq__` such that the hash value returned is no
-   longer appropriate (e.g. by switching to a value-based concept of equality
-   instead of the default identity based equality) can explicitly flag
-   themselves as being unhashable by setting ``__hash__ = None`` in the class
-   definition. Doing so means that not only will instances of the class raise an
-   appropriate :exc:`TypeError` when a program attempts to retrieve their hash
-   value, but they will also be correctly identified as unhashable when checking
-   ``isinstance(obj, collections.Hashable)`` (unlike classes which define their
-   own :meth:`__hash__` to explicitly raise :exc:`TypeError`).
+   A class that overrides :meth:`__eq__` and does not define :meth:`__hash__`
+   will have its :meth:`__hash__` implicitly set to ``None``.  When the
+   :meth:`__hash__` method of a class is ``None``, instances of the class will
+   raise an appropriate :exc:`TypeError` when a program attempts to retrieve
+   their hash value, and will also be correctly identified as unhashable when
+   checking ``isinstance(obj, collections.Hashable``).
 
    If a class that overrides :meth:`__eq__` needs to retain the implementation
    of :meth:`__hash__` from a parent class, the interpreter must be told this
-   explicitly by setting ``__hash__ = <ParentClass>.__hash__``. Otherwise the
-   inheritance of :meth:`__hash__` will be blocked, just as if :attr:`__hash__`
-   had been explicitly set to :const:`None`.
+   explicitly by setting ``__hash__ = <ParentClass>.__hash__``.
+
+   If a class that does not override :meth:`__eq__` wishes to suppress hash
+   support, it should include ``__hash__ = None`` in the class definition.
+   A class which defines its own :meth:`__hash__` that explicitly raises
+   a :exc:`TypeError` would be incorrectly identified as hashable by
+   an ``isinstance(obj, collections.Hashable)`` call.
 
 
    .. note::
diff --git a/Doc/tools/sphinxext/susp-ignored.csv b/Doc/tools/sphinxext/susp-ignored.csv
--- a/Doc/tools/sphinxext/susp-ignored.csv
+++ b/Doc/tools/sphinxext/susp-ignored.csv
@@ -124,9 +124,8 @@
 library/functions,,:stop,"a[start:stop, i]"
 library/functions,,:stop,a[start:stop:step]
 library/hotshot,,:lineno,"ncalls  tottime  percall  cumtime  percall filename:lineno(function)"
-library/http.client,52,:port,host:port
+library/http.client,,:port,host:port
 library/http.cookies,,`,!#$%&'*+-.^_`|~:
-library/httplib,,:port,host:port
 library/imaplib,,:MM,"""DD-Mmm-YYYY HH:MM:SS"
 library/imaplib,,:SS,"""DD-Mmm-YYYY HH:MM:SS"
 library/inspect,,:int,">>> def foo(a, *, b:int, **kwargs):"
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -186,7 +186,7 @@
 
    squares = [x**2 for x in range(10)]
 
-This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
+This is also equivalent to ``squares = list(map(lambda x: x**2, range(10)))``,
 but it's more concise and readable.
 
 A list comprehension consists of brackets containing an expression followed
diff --git a/Doc/tutorial/interpreter.rst b/Doc/tutorial/interpreter.rst
--- a/Doc/tutorial/interpreter.rst
+++ b/Doc/tutorial/interpreter.rst
@@ -12,7 +12,9 @@
 
 The Python interpreter is usually installed as :file:`/usr/local/bin/python3.3`
 on those machines where it is available; putting :file:`/usr/local/bin` in your
-Unix shell's search path makes it possible to start it by typing the command ::
+Unix shell's search path makes it possible to start it by typing the command:
+
+.. code-block:: text
 
    python3.3
 
@@ -94,8 +96,8 @@
 before printing the first prompt::
 
    $ python3.3
-   Python 3.3 (py3k, Sep 12 2007, 12:21:02)
-   [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2
+   Python 3.3 (default, Sep 24 2012, 09:25:04)
+   [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
 
diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -94,8 +94,7 @@
 Variables must be "defined" (assigned a value) before they can be used, or an
 error will occur::
 
-   >>> # try to access an undefined variable
-   ... n
+   >>> n  # try to access an undefined variable
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'n' is not defined
diff --git a/Doc/tutorial/stdlib.rst b/Doc/tutorial/stdlib.rst
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -148,7 +148,7 @@
 
 There are a number of modules for accessing the internet and processing internet
 protocols. Two of the simplest are :mod:`urllib.request` for retrieving data
-from urls and :mod:`smtplib` for sending mail::
+from URLs and :mod:`smtplib` for sending mail::
 
    >>> from urllib.request import urlopen
    >>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
diff --git a/Doc/tutorial/stdlib2.rst b/Doc/tutorial/stdlib2.rst
--- a/Doc/tutorial/stdlib2.rst
+++ b/Doc/tutorial/stdlib2.rst
@@ -95,7 +95,7 @@
    >>> d = dict(item='unladen swallow')
    >>> t.substitute(d)
    Traceback (most recent call last):
-     . . .
+     ...
    KeyError: 'owner'
    >>> t.safe_substitute(d)
    'Return the unladen swallow to $owner.'
@@ -220,7 +220,9 @@
    logging.error('Error occurred')
    logging.critical('Critical error -- shutting down')
 
-This produces the following output::
+This produces the following output:
+
+.. code-block:: none
 
    WARNING:root:Warning:config file server.conf not found
    ERROR:root:Error occurred
@@ -311,6 +313,8 @@
    >>> print("Handling", d.popleft())
    Handling task1
 
+::
+
    unsearched = deque([starting_node])
    def breadth_first_search(unsearched):
        node = unsearched.popleft()
diff --git a/Doc/whatsnew/3.3.rst b/Doc/whatsnew/3.3.rst
--- a/Doc/whatsnew/3.3.rst
+++ b/Doc/whatsnew/3.3.rst
@@ -66,6 +66,7 @@
 * :mod:`faulthandler` (helps debugging low-level crashes)
 * :mod:`ipaddress` (high-level objects representing IP addresses and masks)
 * :mod:`lzma` (compress data using the XZ / LZMA algorithm)
+* :mod:`unittest.mock` (replace parts of your system under test with mock objects)
 * :mod:`venv` (Python :ref:`virtual environments <pep-405>`, as in the
   popular ``virtualenv`` package)
 
@@ -560,6 +561,41 @@
 or amends calling signatures or arguments.
 
 
+PEP 421: Adding sys.implementation
+==================================
+
+:pep:`421` - Adding sys.implementation
+ PEP written and implemented by Eric Snow.
+
+A new attribute on the :mod:`sys` module exposes details specific to the
+implementation of the currently running interpreter.  The initial set of
+attributes on :attr:`sys.implementation` are ``name``, ``version``,
+``hexversion``, and ``cache_tag``.
+
+The intention of ``sys.implementation`` is to consolidate into one namespace
+the implementation-specific data used by the standard library.  This allows
+different Python implementations to share a single standard library code base
+much more easily.  In its initial state, ``sys.implementation`` holds only a
+small portion of the implementation-specific data.  Over time that ratio will
+shift in order to make the standard library more portable.
+
+One example of improved standard library portability is ``cache_tag``.  As of
+Python 3.3, ``sys.implementation.cache_tag`` is used by :mod:`importlib` to
+support :pep:`3147` compliance.  Any Python implementation that uses
+``importlib`` for its built-in import system may use ``cache_tag`` to control
+the caching behavior for modules.
+
+SimpleNamespace
+---------------
+
+The implementation of ``sys.implementation`` also introduces a new type to
+Python: :class:`types.SimpleNamespace`.  In contrast to a mapping-based
+namespace, like :class:`dict`, ``SimpleNamespace`` is attribute-based, like
+:class:`object`.  However, unlike ``object``, ``SimpleNamespace`` instances
+are writable.  This means that you can add, remove, and modify the namespace
+through normal attribute access.
+
+
 .. _importlib:
 
 Using importlib as the Implementation of Import
@@ -815,6 +851,8 @@
 
   (Contributed by Ezio Melotti in :issue:`12753`)
 
+* Unicode database updated to UCD version 6.1.0
+
 * Equality comparisons on :func:`range` objects now return a result reflecting
   the equality of the underlying sequences generated by those range objects.
 
@@ -885,7 +923,7 @@
 faulthandler
 ------------
 
-This new debug module contains functions to dump Python tracebacks explicitly,
+This new debug module :mod:`faulthandler` contains functions to dump Python tracebacks explicitly,
 on a fault (a crash like a segmentation fault), after a timeout, or on a user
 signal. Call :func:`faulthandler.enable` to install fault handlers for the
 :const:`SIGSEGV`, :const:`SIGFPE`, :const:`SIGABRT`, :const:`SIGBUS`, and
@@ -1044,7 +1082,7 @@
 contextlib
 ----------
 
-:class:`~collections.ExitStack` now provides a solid foundation for
+:class:`~contextlib.ExitStack` now provides a solid foundation for
 programmatic manipulation of context managers and similar cleanup
 functionality. Unlike the previous ``contextlib.nested`` API (which was
 deprecated and removed), the new API is designed to work correctly
@@ -1084,7 +1122,7 @@
 --------
 
  * Equality comparisons between naive and aware :class:`~datetime.datetime`
-   instances don't raise :exc:`TypeError`.
+   instances now return :const:`False` instead of raising :exc:`TypeError`.
  * New :meth:`datetime.datetime.timestamp` method: Return POSIX timestamp
    corresponding to the :class:`~datetime.datetime` instance.
  * The :meth:`datetime.datetime.strftime` method supports formatting years
@@ -1193,13 +1231,18 @@
 ftplib
 ------
 
-The :class:`~ftplib.FTP_TLS` class now provides a new
-:func:`~ftplib.FTP_TLS.ccc` function to revert control channel back to
-plaintext.  This can be useful to take advantage of firewalls that know how to
-handle NAT with non-secure FTP without opening fixed ports.
-
-(Contributed by Giampaolo Rodolà in :issue:`12139`)
-
+* The :class:`~ftplib.FTP_TLS` class now provides a new
+  :func:`~ftplib.FTP_TLS.ccc` function to revert control channel back to
+  plaintext.  This can be useful to take advantage of firewalls that know how to
+  handle NAT with non-secure FTP without opening fixed ports.
+
+  (Contributed by Giampaolo Rodolà in :issue:`12139`)
+
+* Added :meth:`ftplib.FTP.mlsd` method which provides a parsable directory
+  listing format and deprecates :meth:`ftplib.FTP.nlst` and
+  :meth:`ftplib.FTP.dir`.
+
+  (Contributed by Giampaolo Rodolà in :issue:`11072`)
 
 gc
 --
@@ -1217,6 +1260,31 @@
 (Contributed by Nick Coghlan and Christian Heimes in issue:`15061`)
 
 
+html.entities
+-------------
+
+A new :data:`~html.entities.html5` dictionary that maps HTML5 named character
+references to the equivalent Unicode character(s) (e.g. ``html5['gt;'] == '>'``)
+has been added to the :mod:`html.entities` module.  The dictionary is now also
+used by :class:`~html.parser.HTMLParser`.
+
+(Contributed by Ezio Melotti in :issue:`11113` and :issue:`15156`)
+
+
+html.parser
+-----------
+
+:class:`~html.parser.HTMLParser` is now able to parse broken markup without
+raising errors, therefore the *strict* argument of the constructor and the
+:exc:`~html.parser.HTMLParseError` exception are now deprecated.
+The ability to parse broken markup is the result of a number of bug fixes that
+are also available on the latest bug fix releases of Python 2.7/3.2.
+
+(Contributed by Ezio Melotti in :issue:`15114`, and :issue:`14538`,
+:issue:`13993`, :issue:`13960`, :issue:`13358`, :issue:`1745761`,
+:issue:`755670`, :issue:`13357`, :issue:`12629`, :issue:`1200313`,
+:issue:`670664`, :issue:`13273`, :issue:`12888`, :issue:`7311`)
+
 imaplib
 -------
 
@@ -1659,6 +1727,16 @@
 for PEP 3115 compliant dynamic type creation. (:issue:`14588`)
 
 
+unittest
+--------
+
+:meth:`.assertRaises`, :meth:`.assertRaisesRegex`, :meth:`.assertWarns`, and
+:meth:`.assertWarnsRegex` now accept a keyword argument *msg* when used as
+context managers.
+
+(Contributed by Ezio Melotti and Winston Ewert in :issue:`10775`)
+
+
 urllib
 ------
 
@@ -1792,6 +1870,15 @@
   * :class:`abc.abstractstaticmethod` has been deprecated, use
     :class:`staticmethod` with :func:`abc.abstractmethod` instead.
 
+* :mod:`importlib` package:
+
+  * :meth:`importlib.abc.SourceLoader.path_mtime` is now deprecated in favour of
+    :meth:`importlib.abc.SourceLoader.path_stats` as bytecode files now store
+    both the modification time and size of the source file the bytecode file was
+    compiled from.
+
+
+
 
 
 Deprecated functions and types of the C API
@@ -1900,7 +1987,7 @@
   updated to use the full name of the module instead of just the tail of the
   name.
 
-* The **index** argument to :func:`__import__` now defaults to 0 instead of -1
+* The *index* argument to :func:`__import__` now defaults to 0 instead of -1
   and no longer support negative values. It was an oversight when :pep:`328` was
   implemented that the default value remained -1. If you need to continue to
   perform a relative import followed by an absolute import, then perform the
@@ -1923,11 +2010,6 @@
   :attr:`sys.path_importer_cache` where it repesents the use of implicit
   finders, but semantically it should not change anything.
 
-* :meth:`importlib.abc.SourceLoader.path_mtime` is now deprecated in favour of
-  :meth:`importlib.abc.SourceLoader.path_stats` as bytecode files now store
-  both the modification time and size of the source file the bytecode file was
-  compiled from.
-
 * :class:`importlib.abc.Finder` no longer specifies a `find_module()` abstract
   method that must be implemented. If you were relying on subclasses to
   implement that method, make sure to check for the method's existence first.
@@ -1968,9 +2050,9 @@
 
 * :c:func:`PyImport_GetMagicNumber` now returns -1 upon failure.
 
-* As a negative value for the **level** argument to :func:`__import__` is no
+* As a negative value for the *level* argument to :func:`__import__` is no
   longer valid, the same now holds for :c:func:`PyImport_ImportModuleLevel`.
-  This also means that the value of **level** used by
+  This also means that the value of *level* used by
   :c:func:`PyImport_ImportModuleEx` is now 0 instead of -1.
 
 
diff --git a/Include/object.h b/Include/object.h
--- a/Include/object.h
+++ b/Include/object.h
@@ -962,7 +962,7 @@
 */
 
 /* This is the old private API, invoked by the macros before 3.2.4.
-   Kept for binary compatibility of extensions. */
+   Kept for binary compatibility of extensions using the stable ABI. */
 PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);
 PyAPI_FUNC(void) _PyTrash_destroy_chain(void);
 PyAPI_DATA(int) _PyTrash_delete_nesting;
diff --git a/Include/objimpl.h b/Include/objimpl.h
--- a/Include/objimpl.h
+++ b/Include/objimpl.h
@@ -181,12 +181,9 @@
 #endif
 
 #define _PyObject_VAR_SIZE(typeobj, nitems)     \
-    (size_t)                                    \
-    ( ( (typeobj)->tp_basicsize +               \
-        (nitems)*(typeobj)->tp_itemsize +       \
-        (SIZEOF_VOID_P - 1)                     \
-      ) & ~(SIZEOF_VOID_P - 1)                  \
-    )
+    _Py_SIZE_ROUND_UP((typeobj)->tp_basicsize + \
+        (nitems)*(typeobj)->tp_itemsize,        \
+        SIZEOF_VOID_P)
 
 #define PyObject_NEW(type, typeobj) \
 ( (type *) PyObject_Init( \
diff --git a/Include/pyfpe.h b/Include/pyfpe.h
--- a/Include/pyfpe.h
+++ b/Include/pyfpe.h
@@ -4,8 +4,8 @@
 extern "C" {
 #endif
 /*
-     ---------------------------------------------------------------------  
-    /                       Copyright (c) 1996.                           \ 
+     ---------------------------------------------------------------------
+    /                       Copyright (c) 1996.                           \
    |          The Regents of the University of California.                 |
    |                        All rights reserved.                           |
    |                                                                       |
@@ -37,8 +37,8 @@
    |   opinions  of authors expressed herein do not necessarily state or   |
    |   reflect those of the United States Government or  the  University   |
    |   of  California,  and shall not be used for advertising or product   |
-    \  endorsement purposes.                                              / 
-     ---------------------------------------------------------------------  
+    \  endorsement purposes.                                              /
+     ---------------------------------------------------------------------
 */
 
 /*
diff --git a/Include/pymacro.h b/Include/pymacro.h
--- a/Include/pymacro.h
+++ b/Include/pymacro.h
@@ -52,4 +52,18 @@
 #define PyDoc_STR(str) ""
 #endif
 
+/* Below "a" is a power of 2. */
+/* Round down size "n" to be a multiple of "a". */
+#define _Py_SIZE_ROUND_DOWN(n, a) ((size_t)(n) & ~(size_t)((a) - 1))
+/* Round up size "n" to be a multiple of "a". */
+#define _Py_SIZE_ROUND_UP(n, a) (((size_t)(n) + \
+        (size_t)((a) - 1)) & ~(size_t)((a) - 1))
+/* Round pointer "p" down to the closest "a"-aligned address <= "p". */
+#define _Py_ALIGN_DOWN(p, a) ((void *)((Py_uintptr_t)(p) & ~(Py_uintptr_t)((a) - 1)))
+/* Round pointer "p" up to the closest "a"-aligned address >= "p". */
+#define _Py_ALIGN_UP(p, a) ((void *)(((Py_uintptr_t)(p) + \
+        (Py_uintptr_t)((a) - 1)) & ~(Py_uintptr_t)((a) - 1)))
+/* Check if pointer "p" is aligned to "a"-bytes boundary. */
+#define _Py_IS_ALIGNED(p, a) (!((Py_uintptr_t)(p) & (Py_uintptr_t)((a) - 1)))
+
 #endif /* Py_PYMACRO_H */
diff --git a/Lib/_pyio.py b/Lib/_pyio.py
--- a/Lib/_pyio.py
+++ b/Lib/_pyio.py
@@ -895,12 +895,18 @@
         return pos
 
     def readable(self):
+        if self.closed:
+            raise ValueError("I/O operation on closed file.")
         return True
 
     def writable(self):
+        if self.closed:
+            raise ValueError("I/O operation on closed file.")
         return True
 
     def seekable(self):
+        if self.closed:
+            raise ValueError("I/O operation on closed file.")
         return True
 
 
@@ -1562,6 +1568,8 @@
         return self._buffer
 
     def seekable(self):
+        if self.closed:
+            raise ValueError("I/O operation on closed file.")
         return self._seekable
 
     def readable(self):
diff --git a/Lib/argparse.py b/Lib/argparse.py
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -1725,10 +1725,7 @@
             if action.dest is not SUPPRESS:
                 if not hasattr(namespace, action.dest):
                     if action.default is not SUPPRESS:
-                        default = action.default
-                        if isinstance(action.default, str):
-                            default = self._get_value(action, default)
-                        setattr(namespace, action.dest, default)
+                        setattr(namespace, action.dest, action.default)
 
         # add any parser defaults that aren't present
         for dest in self._defaults:
@@ -1951,9 +1948,25 @@
         # if we didn't consume all the argument strings, there were extras
         extras.extend(arg_strings[stop_index:])
 
-        # make sure all required actions were present
-        required_actions = [_get_action_name(action) for action in self._actions
-                            if action.required and action not in seen_actions]
+        # make sure all required actions were present and also convert
+        # action defaults which were not given as arguments
+        required_actions = []
+        for action in self._actions:
+            if action not in seen_actions:
+                if action.required:
+                    required_actions.append(_get_action_name(action))
+                else:
+                    # Convert action default now instead of doing it before
+                    # parsing arguments to avoid calling convert functions
+                    # twice (which may fail) if the argument was given, but
+                    # only if it was defined already in the namespace
+                    if (action.default is not None and
+                        isinstance(action.default, str) and
+                        hasattr(namespace, action.dest) and
+                        action.default is getattr(namespace, action.dest)):
+                        setattr(namespace, action.dest,
+                                self._get_value(action, action.default))
+
         if required_actions:
             self.error(_('the following arguments are required: %s') %
                        ', '.join(required_actions))
diff --git a/Lib/calendar.py b/Lib/calendar.py
--- a/Lib/calendar.py
+++ b/Lib/calendar.py
@@ -161,7 +161,11 @@
         oneday = datetime.timedelta(days=1)
         while True:
             yield date
-            date += oneday
+            try:
+                date += oneday
+            except OverflowError:
+                # Adding one day could fail after datetime.MAXYEAR
+                break
             if date.month != month and date.weekday() == self.firstweekday:
                 break
 
diff --git a/Lib/doctest.py b/Lib/doctest.py
--- a/Lib/doctest.py
+++ b/Lib/doctest.py
@@ -2334,7 +2334,12 @@
     elif not tests:
         # Why do we want to do this? Because it reveals a bug that might
         # otherwise be hidden.
-        raise ValueError(module, "has no tests")
+        # It is probably a bug that this exception is not also raised if the
+        # number of doctest examples in tests is zero (i.e. if no doctest
+        # examples were found).  However, we should probably not be raising
+        # an exception at all here, though it is too late to make this change
+        # for a maintenance release.  See also issue #14649.
+        raise ValueError(module, "has no docstrings")
 
     tests.sort()
     suite = unittest.TestSuite()
diff --git a/Lib/gzip.py b/Lib/gzip.py
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -670,9 +670,9 @@
             if not chunk:
                 break
             g.write(chunk)
-        if g is not sys.stdout:
+        if g is not sys.stdout.buffer:
             g.close()
-        if f is not sys.stdin:
+        if f is not sys.stdin.buffer:
             f.close()
 
 if __name__ == '__main__':
diff --git a/Lib/http/cookiejar.py b/Lib/http/cookiejar.py
--- a/Lib/http/cookiejar.py
+++ b/Lib/http/cookiejar.py
@@ -1825,7 +1825,7 @@
 
 class LWPCookieJar(FileCookieJar):
     """
-    The LWPCookieJar saves a sequence of"Set-Cookie3" lines.
+    The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
     "Set-Cookie3" is the format used by the libwww-perl libary, not known
     to be compatible with any browser, but which is easy to read and
     doesn't lose information about RFC 2965 cookies.
@@ -1837,7 +1837,7 @@
     """
 
     def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
-        """Return cookies as a string of "\n"-separated "Set-Cookie3" headers.
+        """Return cookies as a string of "\\n"-separated "Set-Cookie3" headers.
 
         ignore_discard and ignore_expires: see docstring for FileCookieJar.save
 
diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py
--- a/Lib/importlib/_bootstrap.py
+++ b/Lib/importlib/_bootstrap.py
@@ -419,8 +419,8 @@
     .pyc/.pyo file calculated as if the .py file were imported.  The extension
     will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.
 
-    If debug_override is not None, then it must be a boolean and is taken as
-    the value of bool(sys.flags.optimize) instead.
+    If debug_override is not None, then it must be a boolean and is used in
+    place of sys.flags.optimize.
 
     If sys.implementation.cache_tag is None then NotImplementedError is raised.
 
@@ -1669,7 +1669,11 @@
         elif not name:
             return module
         else:
+            # Figure out where to slice the module's name up to the first dot
+            # in 'name'.
             cut_off = len(name) - len(name.partition('.')[0])
+            # Slice end needs to be positive to alleviate need to special-case
+            # when ``'.' not in name``.
             return sys.modules[module.__name__[:len(module.__name__)-cut_off]]
     else:
         return _handle_fromlist(module, fromlist, _gcd_import)
diff --git a/Lib/lib2to3/fixer_util.py b/Lib/lib2to3/fixer_util.py
--- a/Lib/lib2to3/fixer_util.py
+++ b/Lib/lib2to3/fixer_util.py
@@ -274,9 +274,9 @@
     """Find the top level namespace."""
     # Scamper up to the top level namespace
     while node.type != syms.file_input:
-        assert node.parent, "Tree is insane! root found before "\
-                           "file_input node was found."
         node = node.parent
+        if not node:
+            raise ValueError("root found before file_input node was found.")
     return node
 
 def does_tree_import(package, name, node):
diff --git a/Lib/lib2to3/refactor.py b/Lib/lib2to3/refactor.py
--- a/Lib/lib2to3/refactor.py
+++ b/Lib/lib2to3/refactor.py
@@ -445,7 +445,7 @@
 
                         try:
                             find_root(node)
-                        except AssertionError:
+                        except ValueError:
                             # this node has been cut off from a
                             # previous transformation ; skip
                             continue
diff --git a/Lib/mailbox.py b/Lib/mailbox.py
--- a/Lib/mailbox.py
+++ b/Lib/mailbox.py
@@ -208,6 +208,9 @@
             raise ValueError("String input must be ASCII-only; "
                 "use bytes or a Message instead")
 
+    # Whether each message must end in a newline
+    _append_newline = False
+
     def _dump_message(self, message, target, mangle_from_=False):
         # This assumes the target file is open in binary mode.
         """Dump message contents to target file."""
@@ -219,6 +222,9 @@
             data = buffer.read()
             data = data.replace(b'\n', linesep)
             target.write(data)
+            if self._append_newline and not data.endswith(linesep):
+                # Make sure the message ends with a newline
+                target.write(linesep)
         elif isinstance(message, (str, bytes, io.StringIO)):
             if isinstance(message, io.StringIO):
                 warnings.warn("Use of StringIO input is deprecated, "
@@ -230,11 +236,15 @@
                 message = message.replace(b'\nFrom ', b'\n>From ')
             message = message.replace(b'\n', linesep)
             target.write(message)
+            if self._append_newline and not message.endswith(linesep):
+                # Make sure the message ends with a newline
+                target.write(linesep)
         elif hasattr(message, 'read'):
             if hasattr(message, 'buffer'):
                 warnings.warn("Use of text mode files is deprecated, "
                     "use a binary mode file instead", DeprecationWarning, 3)
                 message = message.buffer
+            lastline = None
             while True:
                 line = message.readline()
                 # Universal newline support.
@@ -248,6 +258,10 @@
                     line = b'>From ' + line[5:]
                 line = line.replace(b'\n', linesep)
                 target.write(line)
+                lastline = line
+            if self._append_newline and lastline and not lastline.endswith(linesep):
+                # Make sure the message ends with a newline
+                target.write(linesep)
         else:
             raise TypeError('Invalid message type: %s' % type(message))
 
@@ -833,30 +847,48 @@
 
     _mangle_from_ = True
 
+    # All messages must end in a newline character, and
+    # _post_message_hooks outputs an empty line between messages.
+    _append_newline = True
+
     def __init__(self, path, factory=None, create=True):
         """Initialize an mbox mailbox."""
         self._message_factory = mboxMessage
         _mboxMMDF.__init__(self, path, factory, create)
 
-    def _pre_message_hook(self, f):
-        """Called before writing each message to file f."""
-        if f.tell() != 0:
-            f.write(linesep)
+    def _post_message_hook(self, f):
+        """Called after writing each message to file f."""
+        f.write(linesep)
 
     def _generate_toc(self):
         """Generate key-to-(start, stop) table of contents."""
         starts, stops = [], []
+        last_was_empty = False
         self._file.seek(0)
         while True:
             line_pos = self._file.tell()
             line = self._file.readline()
             if line.startswith(b'From '):
                 if len(stops) < len(starts):
+                    if last_was_empty:
+                        stops.append(line_pos - len(linesep))
+                    else:
+                        # The last line before the "From " line wasn't
+                        # blank, but we consider it a start of a
+                        # message anyway.
+                        stops.append(line_pos)
+                starts.append(line_pos)
+                last_was_empty = False
+            elif not line:
+                if last_was_empty:
                     stops.append(line_pos - len(linesep))
-                starts.append(line_pos)
-            elif not line:
-                stops.append(line_pos)
+                else:
+                    stops.append(line_pos)
                 break
+            elif line == linesep:
+                last_was_empty = True
+            else:
+                last_was_empty = False
         self._toc = dict(enumerate(zip(starts, stops)))
         self._next_key = len(self._toc)
         self._file_length = self._file.tell()
diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py
--- a/Lib/multiprocessing/pool.py
+++ b/Lib/multiprocessing/pool.py
@@ -225,7 +225,6 @@
         Apply `func` to each element in `iterable`, collecting the results
         in a list that is returned.
         '''
-        assert self._state == RUN
         return self._map_async(func, iterable, mapstar, chunksize).get()
 
     def starmap(self, func, iterable, chunksize=None):
@@ -234,7 +233,6 @@
         be iterables as well and will be unpacked as arguments. Hence
         `func` and (a, b) becomes func(a, b).
         '''
-        assert self._state == RUN
         return self._map_async(func, iterable, starmapstar, chunksize).get()
 
     def starmap_async(self, func, iterable, chunksize=None, callback=None,
@@ -242,7 +240,6 @@
         '''
         Asynchronous version of `starmap()` method.
         '''
-        assert self._state == RUN
         return self._map_async(func, iterable, starmapstar, chunksize,
                                callback, error_callback)
 
@@ -250,7 +247,8 @@
         '''
         Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
         '''
-        assert self._state == RUN
+        if self._state != RUN:
+            raise ValueError("Pool not running")
         if chunksize == 1:
             result = IMapIterator(self._cache)
             self._taskqueue.put((((result._job, i, func, (x,), {})
@@ -268,7 +266,8 @@
         '''
         Like `imap()` method but ordering of results is arbitrary.
         '''
-        assert self._state == RUN
+        if self._state != RUN:
+            raise ValueError("Pool not running")
         if chunksize == 1:
             result = IMapUnorderedIterator(self._cache)
             self._taskqueue.put((((result._job, i, func, (x,), {})
@@ -287,7 +286,8 @@
         '''
         Asynchronous version of `apply()` method.
         '''
-        assert self._state == RUN
+        if self._state != RUN:
+            raise ValueError("Pool not running")
         result = ApplyResult(self._cache, callback, error_callback)
         self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
         return result
@@ -297,7 +297,6 @@
         '''
         Asynchronous version of `map()` method.
         '''
-        assert self._state == RUN
         return self._map_async(func, iterable, mapstar, chunksize)
 
     def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
@@ -305,6 +304,8 @@
         '''
         Helper function to implement map, starmap and their async counterparts.
         '''
+        if self._state != RUN:
+            raise ValueError("Pool not running")
         if not hasattr(iterable, '__len__'):
             iterable = list(iterable)
 
diff --git a/Lib/multiprocessing/util.py b/Lib/multiprocessing/util.py
--- a/Lib/multiprocessing/util.py
+++ b/Lib/multiprocessing/util.py
@@ -235,6 +235,12 @@
     Finalizers with highest priority are called first; finalizers with
     the same priority will be called in reverse order of creation.
     '''
+    if _finalizer_registry is None:
+        # This function may be called after this module's globals are
+        # destroyed.  See the _exit_function function in this module for more
+        # notes.
+        return
+
     if minpriority is None:
         f = lambda p : p[0][0] is not None
     else:
@@ -266,7 +272,13 @@
 
 _exiting = False
 
-def _exit_function():
+def _exit_function(info=info, debug=debug, _run_finalizers=_run_finalizers,
+                   active_children=active_children,
+                   current_process=current_process):
+    # We hold on to references to functions in the arglist due to the
+    # situation described below, where this function is called after this
+    # module's globals are destroyed.
+
     global _exiting
 
     if not _exiting:
@@ -276,14 +288,28 @@
         debug('running all "atexit" finalizers with priority >= 0')
         _run_finalizers(0)
 
-        for p in active_children():
-            if p._daemonic:
-                info('calling terminate() for daemon %s', p.name)
-                p._popen.terminate()
+        if current_process() is not None:
+            # We check if the current process is None here because if
+            # it's None, any call to ``active_children()`` will throw
+            # an AttributeError (active_children winds up trying to
+            # get attributes from util._current_process).  One
+            # situation where this can happen is if someone has
+            # manipulated sys.modules, causing this module to be
+            # garbage collected.  The destructor for the module type
+            # then replaces all values in the module dict with None.
+            # For instance, after setuptools runs a test it replaces
+            # sys.modules with a copy created earlier.  See issues
+            # #9775 and #15881.  Also related: #4106, #9205, and
+            # #9207.
 
-        for p in active_children():
-            info('calling join() for process %s', p.name)
-            p.join()
+            for p in active_children():
+                if p._daemonic:
+                    info('calling terminate() for daemon %s', p.name)
+                    p._popen.terminate()
+
+            for p in active_children():
+                info('calling join() for process %s', p.name)
+                p.join()
 
         debug('running the remaining "atexit" finalizers')
         _run_finalizers()
diff --git a/Lib/socket.py b/Lib/socket.py
--- a/Lib/socket.py
+++ b/Lib/socket.py
@@ -324,12 +324,23 @@
     def readable(self):
         """True if the SocketIO is open for reading.
         """
-        return self._reading and not self.closed
+        if self.closed:
+            raise ValueError("I/O operation on closed socket.")
+        return self._reading
 
     def writable(self):
         """True if the SocketIO is open for writing.
         """
-        return self._writing and not self.closed
+        if self.closed:
+            raise ValueError("I/O operation on closed socket.")
+        return self._writing
+
+    def seekable(self):
+        """True if the SocketIO is open for seeking.
+        """
+        if self.closed:
+            raise ValueError("I/O operation on closed socket.")
+        return super().seekable()
 
     def fileno(self):
         """Return the file descriptor of the underlying socket.
diff --git a/Lib/test/sample_doctest_no_docstrings.py b/Lib/test/sample_doctest_no_docstrings.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/sample_doctest_no_docstrings.py
@@ -0,0 +1,12 @@
+# This is a sample module used for testing doctest.
+#
+# This module is for testing how doctest handles a module with no
+# docstrings.
+
+
+class Foo(object):
+
+    # A class with no docstring.
+
+    def __init__(self):
+        pass
diff --git a/Lib/test/sample_doctest_no_doctests.py b/Lib/test/sample_doctest_no_doctests.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/sample_doctest_no_doctests.py
@@ -0,0 +1,15 @@
+"""This is a sample module used for testing doctest.
+
+This module is for testing how doctest handles a module with docstrings
+but no doctest examples.
+
+"""
+
+
+class Foo(object):
+    """A docstring with no doctest examples.
+
+    """
+
+    def __init__(self):
+        pass
diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py
--- a/Lib/test/string_tests.py
+++ b/Lib/test/string_tests.py
@@ -1206,6 +1206,9 @@
         self.checkraises(ValueError, '%%%df' % (2**64), '__mod__', (3.2))
         self.checkraises(ValueError, '%%.%df' % (2**64), '__mod__', (3.2))
 
+        class X(object): pass
+        self.checkraises(TypeError, 'abc', '__mod__', X())
+
     def test_floatformatting(self):
         # float formatting
         for prec in range(100):
diff --git a/Lib/test/support.py b/Lib/test/support.py
--- a/Lib/test/support.py
+++ b/Lib/test/support.py
@@ -680,7 +680,7 @@
     except OSError:
         if not quiet:
             raise
-        warnings.warn('tests may fail, unable to change the CWD to ' + name,
+        warnings.warn('tests may fail, unable to change the CWD to ' + path,
                       RuntimeWarning, stacklevel=3)
     try:
         yield os.getcwd()
diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py
--- a/Lib/test/test_argparse.py
+++ b/Lib/test/test_argparse.py
@@ -1463,6 +1463,22 @@
         ('readonly', NS(x=None, spam=RFile('readonly'))),
     ]
 
+class TestFileTypeDefaults(TempDirMixin, ParserTestCase):
+    """Test that a file is not created unless the default is needed"""
+    def setUp(self):
+        super(TestFileTypeDefaults, self).setUp()
+        file = open(os.path.join(self.temp_dir, 'good'), 'w')
+        file.write('good')
+        file.close()
+
+    argument_signatures = [
+        Sig('-c', type=argparse.FileType('r'), default='no-file.txt'),
+    ]
+    # should provoke no such file error
+    failures = ['']
+    # should not provoke error because default file is created
+    successes = [('-c good', NS(c=RFile('good')))]
+
 
 class TestFileTypeRB(TempDirMixin, ParserTestCase):
     """Test the FileType option/argument type for reading files"""
@@ -4559,6 +4575,71 @@
         self.assertNotIn(msg, 'optional_positional')
 
 
+# ================================================
+# Check that the type function is called only once
+# ================================================
+
+class TestTypeFunctionCallOnlyOnce(TestCase):
+
+    def test_type_function_call_only_once(self):
+        def spam(string_to_convert):
+            self.assertEqual(string_to_convert, 'spam!')
+            return 'foo_converted'
+
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--foo', type=spam, default='bar')
+        args = parser.parse_args('--foo spam!'.split())
+        self.assertEqual(NS(foo='foo_converted'), args)
+
+# ==================================================================
+# Check semantics regarding the default argument and type conversion
+# ==================================================================
+
+class TestTypeFunctionCalledOnDefault(TestCase):
+
+    def test_type_function_call_with_non_string_default(self):
+        def spam(int_to_convert):
+            self.assertEqual(int_to_convert, 0)
+            return 'foo_converted'
+
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--foo', type=spam, default=0)
+        args = parser.parse_args([])
+        # foo should *not* be converted because its default is not a string.
+        self.assertEqual(NS(foo=0), args)
+
+    def test_type_function_call_with_string_default(self):
+        def spam(int_to_convert):
+            return 'foo_converted'
+
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--foo', type=spam, default='0')
+        args = parser.parse_args([])
+        # foo is converted because its default is a string.
+        self.assertEqual(NS(foo='foo_converted'), args)
+
+    def test_no_double_type_conversion_of_default(self):
+        def extend(str_to_convert):
+            return str_to_convert + '*'
+
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--test', type=extend, default='*')
+        args = parser.parse_args([])
+        # The test argument will be two stars, one coming from the default
+        # value and one coming from the type conversion being called exactly
+        # once.
+        self.assertEqual(NS(test='**'), args)
+
+    def test_issue_15906(self):
+        # Issue #15906: When action='append', type=str, default=[] are
+        # providing, the dest value was the string representation "[]" when it
+        # should have been an empty list.
+        parser = argparse.ArgumentParser()
+        parser.add_argument('--test', dest='test', type=str,
+                            default=[], action='append')
+        args = parser.parse_args([])
+        self.assertEqual(args.test, [])
+
 # ======================
 # parse_known_args tests
 # ======================
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -407,6 +407,14 @@
         b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
         self.assertEqual(ast.dump(a), ast.dump(b))
 
+    def test_parse_in_error(self):
+        try:
+            1/0
+        except Exception:
+            with self.assertRaises(SyntaxError) as e:
+                ast.literal_eval(r"'\U'")
+            self.assertIsNotNone(e.exception.__context__)
+
     def test_dump(self):
         node = ast.parse('spam(eggs, "and cheese")')
         self.assertEqual(ast.dump(node),
diff --git a/Lib/test/test_calendar.py b/Lib/test/test_calendar.py
--- a/Lib/test/test_calendar.py
+++ b/Lib/test/test_calendar.py
@@ -6,6 +6,7 @@
 import time
 import locale
 import sys
+import datetime
 
 result_2004_01_text = """
     January 2004
@@ -464,6 +465,11 @@
         new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
         self.assertEqual(old_october, new_october)
 
+    def test_itermonthdates(self):
+        # ensure itermonthdates doesn't overflow after datetime.MAXYEAR
+        # see #15421
+        list(calendar.Calendar().itermonthdates(datetime.MAXYEAR, 12))
+
 
 class MonthCalendarTestCase(unittest.TestCase):
     def setUp(self):
diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py
--- a/Lib/test/test_codecs.py
+++ b/Lib/test/test_codecs.py
@@ -1693,6 +1693,15 @@
         )
 
         self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict", "\U0010FFFFbc"),
+            ("\U0010FFFFbc", 3)
+        )
+
+        self.assertRaises(UnicodeDecodeError,
+            codecs.charmap_decode, b"\x00\x01\x02", "strict", "ab"
+        )
+
+        self.assertEqual(
             codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"),
             ("ab\ufffd", 3)
         )
@@ -1718,6 +1727,113 @@
             ("", len(allbytes))
         )
 
+    def test_decode_with_int2str_map(self):
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: 'a', 1: 'b', 2: 'c'}),
+            ("abc", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: 'Aa', 1: 'Bb', 2: 'Cc'}),
+            ("AaBbCc", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: '\U0010FFFF', 1: 'b', 2: 'c'}),
+            ("\U0010FFFFbc", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: 'a', 1: 'b', 2: ''}),
+            ("ab", 3)
+        )
+
+        self.assertRaises(UnicodeDecodeError,
+            codecs.charmap_decode, b"\x00\x01\x02", "strict",
+                                   {0: 'a', 1: 'b'}
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "replace",
+                                  {0: 'a', 1: 'b'}),
+            ("ab\ufffd", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "replace",
+                                  {0: 'a', 1: 'b', 2: None}),
+            ("ab\ufffd", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "ignore",
+                                  {0: 'a', 1: 'b'}),
+            ("ab", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "ignore",
+                                  {0: 'a', 1: 'b', 2: None}),
+            ("ab", 3)
+        )
+
+        allbytes = bytes(range(256))
+        self.assertEqual(
+            codecs.charmap_decode(allbytes, "ignore", {}),
+            ("", len(allbytes))
+        )
+
+    def test_decode_with_int2int_map(self):
+        a = ord('a')
+        b = ord('b')
+        c = ord('c')
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: a, 1: b, 2: c}),
+            ("abc", 3)
+        )
+
+        # Issue #15379
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: 0x10FFFF, 1: b, 2: c}),
+            ("\U0010FFFFbc", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "strict",
+                                  {0: sys.maxunicode, 1: b, 2: c}),
+            (chr(sys.maxunicode) + "bc", 3)
+        )
+
+        self.assertRaises(TypeError,
+            codecs.charmap_decode, b"\x00\x01\x02", "strict",
+                                   {0: sys.maxunicode + 1, 1: b, 2: c}
+        )
+
+        self.assertRaises(UnicodeDecodeError,
+            codecs.charmap_decode, b"\x00\x01\x02", "strict",
+                                   {0: a, 1: b},
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "replace",
+                                  {0: a, 1: b}),
+            ("ab\ufffd", 3)
+        )
+
+        self.assertEqual(
+            codecs.charmap_decode(b"\x00\x01\x02", "ignore",
+                                  {0: a, 1: b}),
+            ("ab", 3)
+        )
+
+
 class WithStmtTest(unittest.TestCase):
     def test_encodedfile(self):
         f = io.BytesIO(b"\xc3\xbc")
diff --git a/Lib/test/test_compileall.py b/Lib/test/test_compileall.py
--- a/Lib/test/test_compileall.py
+++ b/Lib/test/test_compileall.py
@@ -134,15 +134,21 @@
 class CommandLineTests(unittest.TestCase):
     """Test compileall's CLI."""
 
+    def _get_run_args(self, args):
+        interp_args = ['-S']
+        if sys.flags.optimize:
+            interp_args.append({1 : '-O', 2 : '-OO'}[sys.flags.optimize])
+        return interp_args + ['-m', 'compileall'] + list(args)
+
     def assertRunOK(self, *args, **env_vars):
         rc, out, err = script_helper.assert_python_ok(
-                        '-S', '-m', 'compileall', *args, **env_vars)
+                         *self._get_run_args(args), **env_vars)
         self.assertEqual(b'', err)
         return out
 
     def assertRunNotOK(self, *args, **env_vars):
         rc, out, err = script_helper.assert_python_failure(
-                        '-S', '-m', 'compileall', *args, **env_vars)
+                        *self._get_run_args(args), **env_vars)
         return rc, out, err
 
     def assertCompiled(self, fn):
@@ -198,7 +204,9 @@
         self.assertRunOK('-b', '-q', self.pkgdir)
         # Verify the __pycache__ directory contents.
         self.assertFalse(os.path.exists(self.pkgdir_cachedir))
-        expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
+        opt = 'c' if __debug__ else 'o'
+        expected = sorted(['__init__.py', '__init__.py' + opt, 'bar.py',
+                           'bar.py' + opt])
         self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
 
     def test_multiple_runs(self):
@@ -326,7 +334,7 @@
         f2 = script_helper.make_script(self.pkgdir, 'f2', '')
         f3 = script_helper.make_script(self.pkgdir, 'f3', '')
         f4 = script_helper.make_script(self.pkgdir, 'f4', '')
-        p = script_helper.spawn_python('-m', 'compileall', '-i', '-')
+        p = script_helper.spawn_python(*(self._get_run_args(()) + ['-i', '-']))
         p.stdin.write((f3+os.linesep).encode('ascii'))
         script_helper.kill_python(p)
         self.assertNotCompiled(f1)
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -225,6 +225,15 @@
         self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], [])
         self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], [])
 
+    def test_read_eof(self):
+        self._read_test(['a,"'], [['a', '']])
+        self._read_test(['"a'], [['a']])
+        self._read_test(['^'], [['\n']], escapechar='^')
+        self.assertRaises(csv.Error, self._read_test, ['a,"'], [], strict=True)
+        self.assertRaises(csv.Error, self._read_test, ['"a'], [], strict=True)
+        self.assertRaises(csv.Error, self._read_test,
+                          ['^'], [], escapechar='^', strict=True)
+
     def test_read_escape(self):
         self._read_test(['a,\\b,c'], [['a', 'b', 'c']], escapechar='\\')
         self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\')
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -34,7 +34,8 @@
 import locale
 from test.support import (run_unittest, run_doctest, is_resource_enabled,
                           requires_IEEE_754)
-from test.support import check_warnings, import_fresh_module, TestFailed
+from test.support import (check_warnings, import_fresh_module, TestFailed,
+                          run_with_locale)
 import random
 import time
 import warnings
@@ -1136,18 +1137,19 @@
         self.assertEqual(get_fmt(Decimal('-1.5'), dotsep_wide, '020n'),
                          '-0\u00b4000\u00b4000\u00b4000\u00b4001\u00bf5')
 
+    @run_with_locale('LC_ALL', 'ps_AF')
     def test_wide_char_separator_decimal_point(self):
         # locale with wide char separator and decimal point
+        import locale
         Decimal = self.decimal.Decimal
 
-        try:
-            locale.setlocale(locale.LC_ALL, 'ps_AF')
-        except locale.Error:
+        decimal_point = locale.localeconv()['decimal_point']
+        thousands_sep = locale.localeconv()['thousands_sep']
+        if decimal_point != '\u066b' or thousands_sep != '\u066c':
             return
 
         self.assertEqual(format(Decimal('100000000.123'), 'n'),
                          '100\u066c000\u066c000\u066b123')
-        locale.resetlocale()
 
 class CFormatTest(FormatTest):
     decimal = C
diff --git a/Lib/test/test_doctest.py b/Lib/test/test_doctest.py
--- a/Lib/test/test_doctest.py
+++ b/Lib/test/test_doctest.py
@@ -1986,6 +1986,31 @@
          >>> suite.run(unittest.TestResult())
          <unittest.result.TestResult run=9 errors=0 failures=4>
 
+       The module need not contain any doctest examples:
+
+         >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
+         >>> suite.run(unittest.TestResult())
+         <unittest.result.TestResult run=0 errors=0 failures=0>
+
+       However, if DocTestSuite finds no docstrings, it raises an error:
+
+         >>> try:
+         ...     doctest.DocTestSuite('test.sample_doctest_no_docstrings')
+         ... except ValueError as e:
+         ...     error = e
+
+         >>> print(error.args[1])
+         has no docstrings
+
+       You can prevent this error by passing a DocTestFinder instance with
+       the `exclude_empty` keyword argument set to False:
+
+         >>> finder = doctest.DocTestFinder(exclude_empty=False)
+         >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
+         ...                              test_finder=finder)
+         >>> suite.run(unittest.TestResult())
+         <unittest.result.TestResult run=0 errors=0 failures=0>
+
        We can use the current module:
 
          >>> suite = test.sample_doctest.test_suite()
diff --git a/Lib/test/test_gdb.py b/Lib/test/test_gdb.py
--- a/Lib/test/test_gdb.py
+++ b/Lib/test/test_gdb.py
@@ -154,6 +154,11 @@
         err = err.replace("warning: Cannot initialize thread debugging"
                           " library: Debugger service failed\n",
                           '')
+        err = err.replace('warning: Could not load shared library symbols for '
+                          'linux-vdso.so.1.\n'
+                          'Do you need "set solib-search-path" or '
+                          '"set sysroot"?\n',
+                          '')
 
         # Ensure no unexpected error messages:
         self.assertEqual(err, '')
diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -591,7 +591,7 @@
         self.assertTrue(os.path.exists('__pycache__'))
         self.assertTrue(os.path.exists(os.path.join(
             '__pycache__', '{}.{}.py{}'.format(
-            TESTFN, self.tag, __debug__ and 'c' or 'o'))))
+            TESTFN, self.tag, 'c' if __debug__ else 'o'))))
 
     @unittest.skipUnless(os.name == 'posix',
                          "test meaningful only on posix systems")
diff --git a/Lib/test/test_importlib/test_locks.py b/Lib/test/test_importlib/test_locks.py
--- a/Lib/test/test_importlib/test_locks.py
+++ b/Lib/test/test_importlib/test_locks.py
@@ -1,4 +1,5 @@
 from importlib import _bootstrap
+import sys
 import time
 import unittest
 import weakref
@@ -41,6 +42,17 @@
 @unittest.skipUnless(threading, "threads needed for this test")
 class DeadlockAvoidanceTests(unittest.TestCase):
 
+    def setUp(self):
+        try:
+            self.old_switchinterval = sys.getswitchinterval()
+            sys.setswitchinterval(0.000001)
+        except AttributeError:
+            self.old_switchinterval = None
+
+    def tearDown(self):
+        if self.old_switchinterval is not None:
+            sys.setswitchinterval(self.old_switchinterval)
+
     def run_deadlock_avoidance_test(self, create_deadlock):
         NLOCKS = 10
         locks = [LockType(str(i)) for i in range(NLOCKS)]
@@ -75,10 +87,12 @@
 
     def test_deadlock(self):
         results = self.run_deadlock_avoidance_test(True)
-        # One of the threads detected a potential deadlock on its second
-        # acquire() call.
-        self.assertEqual(results.count((True, False)), 1)
-        self.assertEqual(results.count((True, True)), len(results) - 1)
+        # At least one of the threads detected a potential deadlock on its
+        # second acquire() call.  It may be several of them, because the
+        # deadlock avoidance mechanism is conservative.
+        nb_deadlocks = results.count((True, False))
+        self.assertGreaterEqual(nb_deadlocks, 1)
+        self.assertEqual(results.count((True, True)), len(results) - nb_deadlocks)
 
     def test_no_deadlock(self):
         results = self.run_deadlock_avoidance_test(False)
diff --git a/Lib/test/test_int.py b/Lib/test/test_int.py
--- a/Lib/test/test_int.py
+++ b/Lib/test/test_int.py
@@ -305,6 +305,18 @@
                     self.fail("Failed to raise TypeError with %s" %
                               ((base, trunc_result_base),))
 
+                # Regression test for bugs.python.org/issue16060.
+                class BadInt(trunc_result_base):
+                    def __int__(self):
+                        return 42.0
+
+                class TruncReturnsBadInt(base):
+                    def __trunc__(self):
+                        return BadInt()
+
+                with self.assertRaises(TypeError):
+                    int(TruncReturnsBadInt())
+
     def test_error_message(self):
         testlist = ('\xbd', '123\xbd', '  123 456  ')
         for s in testlist:
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -2887,6 +2887,11 @@
         with self.open(support.TESTFN, 'rb') as f:
             self.assertEqual(b"spam", f.read())
 
+    def test_open_allargs(self):
+        # there used to be a buffer overflow in the parser for rawmode
+        self.assertRaises(ValueError, self.open, support.TESTFN, 'rwax+')
+
+
 class CMiscIOTest(MiscIOTest):
     io = io
 
diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py
--- a/Lib/test/test_mailbox.py
+++ b/Lib/test/test_mailbox.py
@@ -53,7 +53,7 @@
     maxDiff = None
 
     _factory = None     # Overridden by subclasses to reuse tests
-    _template = 'From: foo\n\n%s'
+    _template = 'From: foo\n\n%s\n'
 
     def setUp(self):
         self._path = support.TESTFN
@@ -232,7 +232,7 @@
         key0 = self._box.add(self._template % 0)
         msg = self._box.get(key0)
         self.assertEqual(msg['from'], 'foo')
-        self.assertEqual(msg.get_payload(), '0')
+        self.assertEqual(msg.get_payload(), '0\n')
         self.assertIs(self._box.get('foo'), None)
         self.assertIs(self._box.get('foo', False), False)
         self._box.close()
@@ -240,14 +240,14 @@
         key1 = self._box.add(self._template % 1)
         msg = self._box.get(key1)
         self.assertEqual(msg['from'], 'foo')
-        self.assertEqual(msg.get_payload(), '1')
+        self.assertEqual(msg.get_payload(), '1\n')
 
     def test_getitem(self):
         # Retrieve message using __getitem__()
         key0 = self._box.add(self._template % 0)
         msg = self._box[key0]
         self.assertEqual(msg['from'], 'foo')
-        self.assertEqual(msg.get_payload(), '0')
+        self.assertEqual(msg.get_payload(), '0\n')
         self.assertRaises(KeyError, lambda: self._box['foo'])
         self._box.discard(key0)
         self.assertRaises(KeyError, lambda: self._box[key0])
@@ -259,7 +259,7 @@
         msg0 = self._box.get_message(key0)
         self.assertIsInstance(msg0, mailbox.Message)
         self.assertEqual(msg0['from'], 'foo')
-        self.assertEqual(msg0.get_payload(), '0')
+        self.assertEqual(msg0.get_payload(), '0\n')
         self._check_sample(self._box.get_message(key1))
 
     def test_get_bytes(self):
@@ -432,15 +432,15 @@
         self.assertIn(key0, self._box)
         key1 = self._box.add(self._template % 1)
         self.assertIn(key1, self._box)
-        self.assertEqual(self._box.pop(key0).get_payload(), '0')
+        self.assertEqual(self._box.pop(key0).get_payload(), '0\n')
         self.assertNotIn(key0, self._box)
         self.assertIn(key1, self._box)
         key2 = self._box.add(self._template % 2)
         self.assertIn(key2, self._box)
-        self.assertEqual(self._box.pop(key2).get_payload(), '2')
+        self.assertEqual(self._box.pop(key2).get_payload(), '2\n')
         self.assertNotIn(key2, self._box)
         self.assertIn(key1, self._box)
-        self.assertEqual(self._box.pop(key1).get_payload(), '1')
+        self.assertEqual(self._box.pop(key1).get_payload(), '1\n')
         self.assertNotIn(key1, self._box)
         self.assertEqual(len(self._box), 0)
 
@@ -635,7 +635,7 @@
         msg_returned = self._box.get_message(key)
         self.assertEqual(msg_returned.get_subdir(), 'new')
         self.assertEqual(msg_returned.get_flags(), '')
-        self.assertEqual(msg_returned.get_payload(), '1')
+        self.assertEqual(msg_returned.get_payload(), '1\n')
         msg2 = mailbox.MaildirMessage(self._template % 2)
         msg2.set_info('2,S')
         self._box[key] = msg2
@@ -643,7 +643,7 @@
         msg_returned = self._box.get_message(key)
         self.assertEqual(msg_returned.get_subdir(), 'new')
         self.assertEqual(msg_returned.get_flags(), 'S')
-        self.assertEqual(msg_returned.get_payload(), '3')
+        self.assertEqual(msg_returned.get_payload(), '3\n')
 
     def test_consistent_factory(self):
         # Add a message.
@@ -763,13 +763,13 @@
             self.assertIsNot(match, None, "Invalid file name: '%s'" % tail)
             groups = match.groups()
             if previous_groups is not None:
-                self.assertTrue(int(groups[0] >= previous_groups[0]),
+                self.assertGreaterEqual(int(groups[0]), int(previous_groups[0]),
                              "Non-monotonic seconds: '%s' before '%s'" %
                              (previous_groups[0], groups[0]))
-                self.assertTrue(int(groups[1] >= previous_groups[1]) or
-                             groups[0] != groups[1],
-                             "Non-monotonic milliseconds: '%s' before '%s'" %
-                             (previous_groups[1], groups[1]))
+                if int(groups[0]) == int(previous_groups[0]):
+                    self.assertGreaterEqual(int(groups[1]), int(previous_groups[1]),
+                                "Non-monotonic milliseconds: '%s' before '%s'" %
+                                (previous_groups[1], groups[1]))
                 self.assertEqual(int(groups[2]), pid,
                              "Process ID mismatch: '%s' should be '%s'" %
                              (groups[2], pid))
@@ -996,20 +996,20 @@
 
     def test_add_from_string(self):
         # Add a string starting with 'From ' to the mailbox
-        key = self._box.add('From foo at bar blah\nFrom: foo\n\n0')
+        key = self._box.add('From foo at bar blah\nFrom: foo\n\n0\n')
         self.assertEqual(self._box[key].get_from(), 'foo at bar blah')
-        self.assertEqual(self._box[key].get_payload(), '0')
+        self.assertEqual(self._box[key].get_payload(), '0\n')
 
     def test_add_from_bytes(self):
         # Add a byte string starting with 'From ' to the mailbox
-        key = self._box.add(b'From foo at bar blah\nFrom: foo\n\n0')
+        key = self._box.add(b'From foo at bar blah\nFrom: foo\n\n0\n')
         self.assertEqual(self._box[key].get_from(), 'foo at bar blah')
-        self.assertEqual(self._box[key].get_payload(), '0')
+        self.assertEqual(self._box[key].get_payload(), '0\n')
 
     def test_add_mbox_or_mmdf_message(self):
         # Add an mboxMessage or MMDFMessage
         for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
-            msg = class_('From foo at bar blah\nFrom: foo\n\n0')
+            msg = class_('From foo at bar blah\nFrom: foo\n\n0\n')
             key = self._box.add(msg)
 
     def test_open_close_open(self):
@@ -1116,6 +1116,29 @@
             perms = st.st_mode
             self.assertFalse((perms & 0o111)) # Execute bits should all be off.
 
+    def test_terminating_newline(self):
+        message = email.message.Message()
+        message['From'] = 'john at example.com'
+        message.set_payload('No newline at the end')
+        i = self._box.add(message)
+
+        # A newline should have been appended to the payload
+        message = self._box.get(i)
+        self.assertEqual(message.get_payload(), 'No newline at the end\n')
+
+    def test_message_separator(self):
+        # Check there's always a single blank line after each message
+        self._box.add('From: foo\n\n0')  # No newline at the end
+        with open(self._path) as f:
+            data = f.read()
+            self.assertEqual(data[-3:], '0\n\n')
+
+        self._box.add('From: foo\n\n0\n')  # Newline at the end
+        with open(self._path) as f:
+            data = f.read()
+            self.assertEqual(data[-3:], '0\n\n')
+
+
 class TestMMDF(_TestMboxMMDF, unittest.TestCase):
 
     _factory = lambda self, path, factory=None: mailbox.MMDF(path, factory)
diff --git a/Lib/test/test_memoryio.py b/Lib/test/test_memoryio.py
--- a/Lib/test/test_memoryio.py
+++ b/Lib/test/test_memoryio.py
@@ -318,9 +318,9 @@
         self.assertEqual(memio.isatty(), False)
         self.assertEqual(memio.closed, False)
         memio.close()
-        self.assertEqual(memio.writable(), True)
-        self.assertEqual(memio.readable(), True)
-        self.assertEqual(memio.seekable(), True)
+        self.assertRaises(ValueError, memio.writable)
+        self.assertRaises(ValueError, memio.readable)
+        self.assertRaises(ValueError, memio.seekable)
         self.assertRaises(ValueError, memio.isatty)
         self.assertEqual(memio.closed, True)
 
@@ -665,7 +665,6 @@
         check(io.BytesIO(b'a'), basesize + 1 + 1 )
         check(io.BytesIO(b'a' * 1000), basesize + 1000 + 1 )
 
-
 class CStringIOTest(PyStringIOTest):
     ioclass = io.StringIO
     UnsupportedOperation = io.UnsupportedOperation
diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py
--- a/Lib/test/test_mmap.py
+++ b/Lib/test/test_mmap.py
@@ -488,6 +488,15 @@
         f.flush ()
         return mmap.mmap (f.fileno(), 0)
 
+    def test_empty_file (self):
+        f = open (TESTFN, 'w+b')
+        f.close()
+        with open(TESTFN, "rb") as f :
+            self.assertRaisesRegex(ValueError,
+                                   "cannot mmap an empty file",
+                                   mmap.mmap, f.fileno(), 0,
+                                   access=mmap.ACCESS_READ)
+
     def test_offset (self):
         f = open (TESTFN, 'w+b')
 
diff --git a/Lib/test/test_multiprocessing.py b/Lib/test/test_multiprocessing.py
--- a/Lib/test/test_multiprocessing.py
+++ b/Lib/test/test_multiprocessing.py
@@ -1727,7 +1727,8 @@
             with multiprocessing.Pool(2) as p:
                 r = p.map_async(sqr, L)
                 self.assertEqual(r.get(), expected)
-            self.assertRaises(AssertionError, p.map_async, sqr, L)
+            print(p._state)
+            self.assertRaises(ValueError, p.map_async, sqr, L)
 
 def raising():
     raise KeyError("key")
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -514,23 +514,23 @@
         return os.environ
 
     # Bug 1110478
+    @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
     def test_update2(self):
         os.environ.clear()
-        if os.path.exists("/bin/sh"):
-            os.environ.update(HELLO="World")
-            with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
-                value = popen.read().strip()
-                self.assertEqual(value, "World")
+        os.environ.update(HELLO="World")
+        with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
+            value = popen.read().strip()
+            self.assertEqual(value, "World")
 
+    @unittest.skipUnless(os.path.exists('/bin/sh'), 'requires /bin/sh')
     def test_os_popen_iter(self):
-        if os.path.exists("/bin/sh"):
-            with os.popen(
-                "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
-                it = iter(popen)
-                self.assertEqual(next(it), "line1\n")
-                self.assertEqual(next(it), "line2\n")
-                self.assertEqual(next(it), "line3\n")
-                self.assertRaises(StopIteration, next, it)
+        with os.popen(
+            "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
+            it = iter(popen)
+            self.assertEqual(next(it), "line1\n")
+            self.assertEqual(next(it), "line2\n")
+            self.assertEqual(next(it), "line3\n")
+            self.assertRaises(StopIteration, next, it)
 
     # Verify environ keys and values from the OS are of the
     # correct str type.
diff --git a/Lib/test/test_pyexpat.py b/Lib/test/test_pyexpat.py
--- a/Lib/test/test_pyexpat.py
+++ b/Lib/test/test_pyexpat.py
@@ -641,6 +641,16 @@
         parser.Parse("<?xml version='1.0'?><element/>")
         self.assertEqual(handler_call_args, [(None, None)])
 
+        # test UseForeignDTD() is equal to UseForeignDTD(True)
+        handler_call_args[:] = []
+
+        parser = expat.ParserCreate()
+        parser.UseForeignDTD()
+        parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
+        parser.ExternalEntityRefHandler = resolve_entity
+        parser.Parse("<?xml version='1.0'?><element/>")
+        self.assertEqual(handler_call_args, [(None, None)])
+
     def test_ignore_use_foreign_dtd(self):
         """
         If UseForeignDTD is passed True and a document with an external
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -1245,6 +1245,17 @@
             fp.close()
             self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
 
+    def test_unusable_closed_socketio(self):
+        with socket.socket() as sock:
+            fp = sock.makefile("rb", buffering=0)
+            self.assertTrue(fp.readable())
+            self.assertFalse(fp.writable())
+            self.assertFalse(fp.seekable())
+            fp.close()
+            self.assertRaises(ValueError, fp.readable)
+            self.assertRaises(ValueError, fp.writable)
+            self.assertRaises(ValueError, fp.seekable)
+
     def test_pickle(self):
         sock = socket.socket()
         with sock:
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
--- a/Lib/test/test_ssl.py
+++ b/Lib/test/test_ssl.py
@@ -125,12 +125,8 @@
         else:
             self.assertRaises(ssl.SSLError, ssl.RAND_bytes, 16)
 
-        try:
-            ssl.RAND_egd(1)
-        except TypeError:
-            pass
-        else:
-            print("didn't raise TypeError")
+        self.assertRaises(TypeError, ssl.RAND_egd, 1)
+        self.assertRaises(TypeError, ssl.RAND_egd, 'foo', 1)
         ssl.RAND_add("this is a random string", 75.0)
 
     def test_parse_cert(self):
diff --git a/Lib/test/test_startfile.py b/Lib/test/test_startfile.py
--- a/Lib/test/test_startfile.py
+++ b/Lib/test/test_startfile.py
@@ -10,8 +10,8 @@
 import unittest
 from test import support
 import os
+import sys
 from os import path
-from time import sleep
 
 startfile = support.get_attribute(os, 'startfile')
 
@@ -21,13 +21,12 @@
         self.assertRaises(OSError, startfile, "nonexisting.vbs")
 
     def test_empty(self):
-        empty = path.join(path.dirname(__file__), "empty.vbs")
-        startfile(empty)
-        startfile(empty, "open")
-        # Give the child process some time to exit before we finish.
-        # Otherwise the cleanup code will not be able to delete the cwd,
-        # because it is still in use.
-        sleep(0.1)
+        # Switch to an existing, but safe, working directory to let the
+        # cleanup code do its thing without permission errors.
+        with support.temp_cwd(path=path.dirname(sys.executable)):
+            empty = path.join(path.dirname(__file__), "empty.vbs")
+            startfile(empty)
+            startfile(empty, "open")
 
 def test_main():
     support.run_unittest(TestCase)
diff --git a/Lib/test/test_super.py b/Lib/test/test_super.py
--- a/Lib/test/test_super.py
+++ b/Lib/test/test_super.py
@@ -115,6 +115,21 @@
                 return __class__
         self.assertIs(X.f(), X)
 
+    def test_obscure_super_errors(self):
+        def f():
+            super()
+        self.assertRaises(RuntimeError, f)
+        def f(x):
+            del x
+            super()
+        self.assertRaises(RuntimeError, f, None)
+        class X:
+            def f(x):
+                nonlocal __class__
+                del __class__
+                super()
+        self.assertRaises(RuntimeError, X().f)
+
 
 def test_main():
     support.run_unittest(TestSuper)
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -95,6 +95,15 @@
         self.assertFalse(os.path.exists(TESTFN))
         self.assertTrue(os.path.basename(os.getcwd()), here)
 
+    def test_temp_cwd__chdir_warning(self):
+        """Check the warning message when os.chdir() fails."""
+        path = TESTFN + '_does_not_exist'
+        with support.check_warnings() as recorder:
+            with support.temp_cwd(path=path, quiet=True):
+                pass
+            messages = [str(w.message) for w in recorder.warnings]
+        self.assertEqual(messages, ['tests may fail, unable to change the CWD to ' + path])
+
     def test_sortdict(self):
         self.assertEqual(support.sortdict({3:3, 2:2, 1:1}), "{1: 1, 2: 2, 3: 3}")
 
diff --git a/Lib/test/test_textwrap.py b/Lib/test/test_textwrap.py
--- a/Lib/test/test_textwrap.py
+++ b/Lib/test/test_textwrap.py
@@ -22,7 +22,7 @@
             result = []
             for i in range(len(textin)):
                 result.append("  %d: %r" % (i, textin[i]))
-            result = '\n'.join(result)
+            result = "\n".join(result) if result else "  no lines"
         elif isinstance(textin, str):
             result = "  %s\n" % repr(textin)
         return result
@@ -66,6 +66,15 @@
                          "I'm glad to hear it!"])
         self.check_wrap(text, 80, [text])
 
+    def test_empty_string(self):
+        # Check that wrapping the empty string returns an empty list.
+        self.check_wrap("", 6, [])
+        self.check_wrap("", 6, [], drop_whitespace=False)
+
+    def test_empty_string_with_initial_indent(self):
+        # Check that the empty string is not indented.
+        self.check_wrap("", 6, [], initial_indent="++")
+        self.check_wrap("", 6, [], initial_indent="++", drop_whitespace=False)
 
     def test_whitespace(self):
         # Whitespace munging and end-of-sentence detection
@@ -331,7 +340,32 @@
                          ["blah", " ", "(ding", " ", "dong),",
                           " ", "wubba"])
 
-    def test_initial_whitespace(self):
+    def test_drop_whitespace_false(self):
+        # Check that drop_whitespace=False preserves whitespace.
+        # SF patch #1581073
+        text = " This is a    sentence with     much whitespace."
+        self.check_wrap(text, 10,
+                        [" This is a", "    ", "sentence ",
+                         "with     ", "much white", "space."],
+                        drop_whitespace=False)
+
+    def test_drop_whitespace_false_whitespace_only(self):
+        # Check that drop_whitespace=False preserves a whitespace-only string.
+        self.check_wrap("   ", 6, ["   "], drop_whitespace=False)
+
+    def test_drop_whitespace_false_whitespace_only_with_indent(self):
+        # Check that a whitespace-only string gets indented (when
+        # drop_whitespace is False).
+        self.check_wrap("   ", 6, ["     "], drop_whitespace=False,
+                        initial_indent="  ")
+
+    def test_drop_whitespace_whitespace_only(self):
+        # Check drop_whitespace on a whitespace-only string.
+        self.check_wrap("  ", 6, [])
+
+    def test_drop_whitespace_leading_whitespace(self):
+        # Check that drop_whitespace does not drop leading whitespace (if
+        # followed by non-whitespace).
         # SF bug #622849 reported inconsistent handling of leading
         # whitespace; let's test that a bit, shall we?
         text = " This is a sentence with leading whitespace."
@@ -340,13 +374,27 @@
         self.check_wrap(text, 30,
                         [" This is a sentence with", "leading whitespace."])
 
-    def test_no_drop_whitespace(self):
-        # SF patch #1581073
-        text = " This is a    sentence with     much whitespace."
-        self.check_wrap(text, 10,
-                        [" This is a", "    ", "sentence ",
-                         "with     ", "much white", "space."],
+    def test_drop_whitespace_whitespace_line(self):
+        # Check that drop_whitespace skips the whole line if a non-leading
+        # line consists only of whitespace.
+        text = "abcd    efgh"
+        # Include the result for drop_whitespace=False for comparison.
+        self.check_wrap(text, 6, ["abcd", "    ", "efgh"],
                         drop_whitespace=False)
+        self.check_wrap(text, 6, ["abcd", "efgh"])
+
+    def test_drop_whitespace_whitespace_only_with_indent(self):
+        # Check that initial_indent is not applied to a whitespace-only
+        # string.  This checks a special case of the fact that dropping
+        # whitespace occurs before indenting.
+        self.check_wrap("  ", 6, [], initial_indent="++")
+
+    def test_drop_whitespace_whitespace_indent(self):
+        # Check that drop_whitespace does not drop whitespace indents.
+        # This checks a special case of the fact that dropping whitespace
+        # occurs before indenting.
+        self.check_wrap("abcd efgh", 6, ["  abcd", "  efgh"],
+                        initial_indent="  ", subsequent_indent="  ")
 
     def test_split(self):
         # Ensure that the standard _split() method works as advertised
diff --git a/Lib/test/test_threaded_import.py b/Lib/test/test_threaded_import.py
--- a/Lib/test/test_threaded_import.py
+++ b/Lib/test/test_threaded_import.py
@@ -225,9 +225,11 @@
 @reap_threads
 def test_main():
     old_switchinterval = None
+    # Issue #15599: FreeBSD/KVM cannot handle gil_interval == 1.
+    new_switchinterval = 0.00001 if 'freebsd' in sys.platform else 0.00000001
     try:
         old_switchinterval = sys.getswitchinterval()
-        sys.setswitchinterval(0.00000001)
+        sys.setswitchinterval(new_switchinterval)
     except AttributeError:
         pass
     try:
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -791,7 +791,7 @@
         self.assertEqual(C.y, 1)
         self.assertEqual(C.z, 2)
 
-    def test_new_class_exec_body(self):
+    def test_new_class_metaclass_keywords(self):
         #Test that keywords are passed to the metaclass:
         def meta_func(name, bases, ns, **kw):
             return name, bases, ns, kw
diff --git a/Lib/test/test_webbrowser.py b/Lib/test/test_webbrowser.py
new file mode 100644
--- /dev/null
+++ b/Lib/test/test_webbrowser.py
@@ -0,0 +1,192 @@
+import webbrowser
+import unittest
+import subprocess
+from unittest import mock
+from test import support
+
+
+URL = 'http://www.example.com'
+CMD_NAME = 'test'
+
+
+class PopenMock(mock.MagicMock):
+
+    def poll(self):
+        return 0
+
+    def wait(self, seconds=None):
+        return 0
+
+
+class CommandTestMixin:
+
+    def _test(self, meth, *, args=[URL], kw={}, options, arguments):
+        """Given a web browser instance method name along with arguments and
+        keywords for same (which defaults to the single argument URL), creates
+        a browser instance from the class pointed to by self.browser, calls the
+        indicated instance method with the indicated arguments, and compares
+        the resulting options and arguments passed to Popen by the browser
+        instance against the 'options' and 'args' lists.  Options are compared
+        in a position independent fashion, and the arguments are compared in
+        sequence order to whatever is left over after removing the options.
+
+        """
+        popen = PopenMock()
+        support.patch(self, subprocess, 'Popen', popen)
+        browser = self.browser_class(name=CMD_NAME)
+        getattr(browser, meth)(*args, **kw)
+        popen_args = subprocess.Popen.call_args[0][0]
+        self.assertEqual(popen_args[0], CMD_NAME)
+        popen_args.pop(0)
+        for option in options:
+            self.assertIn(option, popen_args)
+            popen_args.pop(popen_args.index(option))
+        self.assertEqual(popen_args, arguments)
+
+
+class GenericBrowserCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.GenericBrowser
+
+    def test_open(self):
+        self._test('open',
+                   options=[],
+                   arguments=[URL])
+
+
+class BackgroundBrowserCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.BackgroundBrowser
+
+    def test_open(self):
+        self._test('open',
+                   options=[],
+                   arguments=[URL])
+
+
+class ChromeCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.Chrome
+
+    def test_open(self):
+        self._test('open',
+                   options=[],
+                   arguments=[URL])
+
+    def test_open_with_autoraise_false(self):
+        self._test('open', kw=dict(autoraise=False),
+                   options=[],
+                   arguments=[URL])
+
+    def test_open_new(self):
+        self._test('open_new',
+                   options=['--new-window'],
+                   arguments=[URL])
+
+    def test_open_new_tab(self):
+        self._test('open_new_tab',
+                   options=[],
+                   arguments=[URL])
+
+
+class MozillaCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.Mozilla
+
+    def test_open(self):
+        self._test('open',
+                   options=['-raise', '-remote'],
+                   arguments=['openURL({})'.format(URL)])
+
+    def test_open_with_autoraise_false(self):
+        self._test('open', kw=dict(autoraise=False),
+                   options=['-noraise', '-remote'],
+                   arguments=['openURL({})'.format(URL)])
+
+    def test_open_new(self):
+        self._test('open_new',
+                   options=['-raise', '-remote'],
+                   arguments=['openURL({},new-window)'.format(URL)])
+
+    def test_open_new_tab(self):
+        self._test('open_new_tab',
+                   options=['-raise', '-remote'],
+                   arguments=['openURL({},new-tab)'.format(URL)])
+
+
+class GaleonCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.Galeon
+
+    def test_open(self):
+        self._test('open',
+                   options=['-n'],
+                   arguments=[URL])
+
+    def test_open_with_autoraise_false(self):
+        self._test('open', kw=dict(autoraise=False),
+                   options=['-noraise', '-n'],
+                   arguments=[URL])
+
+    def test_open_new(self):
+        self._test('open_new',
+                   options=['-w'],
+                   arguments=[URL])
+
+    def test_open_new_tab(self):
+        self._test('open_new_tab',
+                   options=['-w'],
+                   arguments=[URL])
+
+
+class OperaCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.Opera
+
+    def test_open(self):
+        self._test('open',
+                   options=['-remote'],
+                   arguments=['openURL({})'.format(URL)])
+
+    def test_open_with_autoraise_false(self):
+        self._test('open', kw=dict(autoraise=False),
+                   options=['-remote', '-noraise'],
+                   arguments=['openURL({})'.format(URL)])
+
+    def test_open_new(self):
+        self._test('open_new',
+                   options=['-remote'],
+                   arguments=['openURL({},new-window)'.format(URL)])
+
+    def test_open_new(self):
+        self._test('open_new_tab',
+                   options=['-remote'],
+                   arguments=['openURL({},new-page)'.format(URL)])
+
+
+class ELinksCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.Elinks
+
+    def test_open(self):
+        self._test('open', options=['-remote'],
+                           arguments=['openURL({})'.format(URL)])
+
+    def test_open_with_autoraise_false(self):
+        self._test('open',
+                   options=['-remote'],
+                   arguments=['openURL({})'.format(URL)])
+
+    def test_open_new(self):
+        self._test('open_new',
+                   options=['-remote'],
+                   arguments=['openURL({},new-window)'.format(URL)])
+
+    def test_open_new_tab(self):
+        self._test('open_new_tab',
+                   options=['-remote'],
+                   arguments=['openURL({},new-tab)'.format(URL)])
+
+
+if __name__=='__main__':
+    unittest.main()
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -1809,6 +1809,18 @@
         mye = MyElement('joe')
         self.assertEqual(mye.newmethod(), 'joe')
 
+    def test_html_empty_elems_serialization(self):
+        # issue 15970
+        # from http://www.w3.org/TR/html401/index/elements.html
+        for element in ['AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME', 'HR',
+                        'IMG', 'INPUT', 'ISINDEX', 'LINK', 'META', 'PARAM']:
+            for elem in [element, element.lower()]:
+                expected = '<%s>' % elem
+                serialized = serialize(ET.XML('<%s />' % elem), method='html')
+                self.assertEqual(serialized, expected)
+                serialized = serialize(ET.XML('<%s></%s>' % (elem,elem)),
+                                       method='html')
+                self.assertEqual(serialized, expected)
 
 class ElementIterTest(unittest.TestCase):
     def _ilist(self, elem, tag=None):
diff --git a/Lib/test/test_zipimport_support.py b/Lib/test/test_zipimport_support.py
--- a/Lib/test/test_zipimport_support.py
+++ b/Lib/test/test_zipimport_support.py
@@ -29,7 +29,8 @@
 #  test_cmd_line_script (covers the zipimport support in runpy)
 
 # Retrieve some helpers from other test cases
-from test import test_doctest, sample_doctest
+from test import (test_doctest, sample_doctest, sample_doctest_no_doctests,
+                  sample_doctest_no_docstrings)
 
 
 def _run_object_doctest(obj, module):
@@ -105,16 +106,26 @@
                                     "test_zipped_doctest")
         test_src = test_src.replace("test.sample_doctest",
                                     "sample_zipped_doctest")
-        sample_src = inspect.getsource(sample_doctest)
-        sample_src = sample_src.replace("test.test_doctest",
-                                        "test_zipped_doctest")
+        # The sample doctest files rewritten to include in the zipped version.
+        sample_sources = {}
+        for mod in [sample_doctest, sample_doctest_no_doctests,
+                    sample_doctest_no_docstrings]:
+            src = inspect.getsource(mod)
+            src = src.replace("test.test_doctest", "test_zipped_doctest")
+            # Rewrite the module name so that, for example,
+            # "test.sample_doctest" becomes "sample_zipped_doctest".
+            mod_name = mod.__name__.split(".")[-1]
+            mod_name = mod_name.replace("sample_", "sample_zipped_")
+            sample_sources[mod_name] = src
+
         with temp_dir() as d:
             script_name = make_script(d, 'test_zipped_doctest',
                                             test_src)
             zip_name, run_name = make_zip_script(d, 'test_zip',
                                                 script_name)
             z = zipfile.ZipFile(zip_name, 'a')
-            z.writestr("sample_zipped_doctest.py", sample_src)
+            for mod_name, src in sample_sources.items():
+                z.writestr(mod_name + ".py", src)
             z.close()
             if verbose:
                 zip_file = zipfile.ZipFile(zip_name, 'r')
diff --git a/Lib/unittest/__main__.py b/Lib/unittest/__main__.py
--- a/Lib/unittest/__main__.py
+++ b/Lib/unittest/__main__.py
@@ -2,7 +2,14 @@
 
 import sys
 if sys.argv[0].endswith("__main__.py"):
-    sys.argv[0] = "python -m unittest"
+    import os.path
+    # We change sys.argv[0] to make help message more useful
+    # use executable without path, unquoted
+    # (it's just a hint anyway)
+    # (if you have spaces in your executable you get what you deserve!)
+    executable = os.path.basename(sys.executable)
+    sys.argv[0] = executable + " -m unittest"
+    del os
 
 __unittest = True
 
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -731,8 +731,8 @@
         arguments."""
         self = _mock_self
         if not self.call_count == 1:
-            msg = ("Expected to be called once. Called %s times." %
-                   self.call_count)
+            msg = ("Expected '%s' to be called once. Called %s times." %
+                   (self._mock_name or 'mock', self.call_count))
             raise AssertionError(msg)
         return self.assert_called_with(*args, **kwargs)
 
diff --git a/Lib/unittest/runner.py b/Lib/unittest/runner.py
--- a/Lib/unittest/runner.py
+++ b/Lib/unittest/runner.py
@@ -35,7 +35,7 @@
     separator2 = '-' * 70
 
     def __init__(self, stream, descriptions, verbosity):
-        super(TextTestResult, self).__init__()
+        super(TextTestResult, self).__init__(stream, descriptions, verbosity)
         self.stream = stream
         self.showAll = verbosity > 1
         self.dots = verbosity == 1
diff --git a/Lib/unittest/test/test_runner.py b/Lib/unittest/test/test_runner.py
--- a/Lib/unittest/test/test_runner.py
+++ b/Lib/unittest/test/test_runner.py
@@ -149,6 +149,19 @@
         self.assertEqual(runner.resultclass, unittest.TextTestResult)
 
 
+    def test_multiple_inheritance(self):
+        class AResult(unittest.TestResult):
+            def __init__(self, stream, descriptions, verbosity):
+                super(AResult, self).__init__(stream, descriptions, verbosity)
+
+        class ATextResult(unittest.TextTestResult, AResult):
+            pass
+
+        # This used to raise an exception due to TextTestResult not passing
+        # on arguments in its __init__ super call
+        ATextResult(None, None, 1)
+
+
     def testBufferAndFailfast(self):
         class Test(unittest.TestCase):
             def testFoo(self):
diff --git a/Lib/unittest/test/testmock/testmock.py b/Lib/unittest/test/testmock/testmock.py
--- a/Lib/unittest/test/testmock/testmock.py
+++ b/Lib/unittest/test/testmock/testmock.py
@@ -463,6 +463,13 @@
                                 mock.assert_called_with)
 
 
+    def test_assert_called_once_with_message(self):
+        mock = Mock(name='geoffrey')
+        self.assertRaisesRegex(AssertionError,
+                     r"Expected 'geoffrey' to be called once\.",
+                     mock.assert_called_once_with)
+
+
     def test__name__(self):
         mock = Mock()
         self.assertRaises(AttributeError, lambda: mock.__name__)
diff --git a/Lib/webbrowser.py b/Lib/webbrowser.py
--- a/Lib/webbrowser.py
+++ b/Lib/webbrowser.py
@@ -206,12 +206,18 @@
     """Parent class for all Unix browsers with remote functionality."""
 
     raise_opts = None
+    background = False
+    redirect_stdout = True
+    # In remote_args, %s will be replaced with the requested URL.  %action will
+    # be replaced depending on the value of 'new' passed to open.
+    # remote_action is used for new=0 (open).  If newwin is not None, it is
+    # used for new=1 (open_new).  If newtab is not None, it is used for
+    # new=3 (open_new_tab).  After both substitutions are made, any empty
+    # strings in the transformed remote_args list will be removed.
     remote_args = ['%action', '%s']
     remote_action = None
     remote_action_newwin = None
     remote_action_newtab = None
-    background = False
-    redirect_stdout = True
 
     def _invoke(self, args, remote, autoraise):
         raise_opt = []
@@ -224,7 +230,7 @@
         cmdline = [self.name] + raise_opt + args
 
         if remote or self.background:
-            inout = io.open(os.devnull, "r+")
+            inout = subprocess.DEVNULL
         else:
             # for TTY browsers, we need stdin/out
             inout = None
@@ -264,6 +270,7 @@
 
         args = [arg.replace("%s", url).replace("%action", action)
                 for arg in self.remote_args]
+        args = [arg for arg in args if arg]
         success = self._invoke(args, True, autoraise)
         if not success:
             # remote invocation failed, try straight way
@@ -347,7 +354,7 @@
         else:
             action = "openURL"
 
-        devnull = io.open(os.devnull, "r+")
+        devnull = subprocess.DEVNULL
         # if possible, put browser in separate process group, so
         # keyboard interrupts don't affect browser as well as Python
         setsid = getattr(os, 'setsid', None)
diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py
--- a/Lib/xml/etree/ElementTree.py
+++ b/Lib/xml/etree/ElementTree.py
@@ -995,7 +995,7 @@
         write(_escape_cdata(elem.tail))
 
 HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
-              "img", "input", "isindex", "link", "meta" "param")
+              "img", "input", "isindex", "link", "meta", "param")
 
 try:
     HTML_EMPTY = set(HTML_EMPTY)
diff --git a/Makefile.pre.in b/Makefile.pre.in
--- a/Makefile.pre.in
+++ b/Makefile.pre.in
@@ -229,8 +229,8 @@
 
 ##########################################################################
 # Grammar
-GRAMMAR_H=	$(srcdir)/Include/graminit.h
-GRAMMAR_C=	$(srcdir)/Python/graminit.c
+GRAMMAR_H=	Include/graminit.h
+GRAMMAR_C=	Python/graminit.c
 GRAMMAR_INPUT=	$(srcdir)/Grammar/Grammar
 
 
@@ -296,9 +296,9 @@
 
 ##########################################################################
 # AST
-AST_H_DIR=	$(srcdir)/Include
+AST_H_DIR=	Include
 AST_H=		$(AST_H_DIR)/Python-ast.h
-AST_C_DIR=	$(srcdir)/Python
+AST_C_DIR=	Python
 AST_C=		$(AST_C_DIR)/Python-ast.c
 AST_ASDL=	$(srcdir)/Parser/Python.asdl
 
@@ -474,8 +474,13 @@
 	$(RUNSHARED) $(PYTHON_FOR_BUILD) -S -m sysconfig --generate-posix-vars
 
 # Build the shared modules
+# MAKEFLAGS are sorted and normalized. Under GNU make the 's' for
+# -s, --silent or --quiet is always the first char.
 sharedmods: $(BUILDPYTHON) $(SYSCONFIGDATA)
-	case $$MAKEFLAGS in *s*) quiet=-q; esac; \
+	@case "$$MAKEFLAGS" in \
+	    s*) quiet="-q";; \
+	    *) quiet="";; \
+	esac; \
 	$(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' \
 		$(PYTHON_FOR_BUILD) $(srcdir)/setup.py $$quiet build
 
@@ -660,9 +665,11 @@
 Parser/pgenmain.o:	$(srcdir)/Include/parsetok.h
 
 $(AST_H): $(AST_ASDL) $(ASDLGEN_FILES)
+	$(MKDIR_P) $(AST_H_DIR)
 	$(ASDLGEN) -h $(AST_H_DIR) $(AST_ASDL)
 
 $(AST_C): $(AST_H) $(AST_ASDL) $(ASDLGEN_FILES)
+	$(MKDIR_P) $(AST_C_DIR)
 	$(ASDLGEN) -c $(AST_C_DIR) $(AST_ASDL)
 
 Python/compile.o Python/symtable.o Python/ast.o: $(GRAMMAR_H) $(AST_H)
diff --git a/Misc/ACKS b/Misc/ACKS
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -11,6 +11,8 @@
 PS: In the standard Python distribution, this file is encoded in UTF-8
 and the list is in rough alphabetical order by last names.
 
+Aahz
+Michael Abbott
 Rajiv Abraham
 David Abrahams
 Marc Abramowitz
@@ -22,26 +24,32 @@
 Nir Aides
 Yaniv Aknin
 Jyrki Alakuijala
+Steve Alexander
+Fred Allen
 Ray Allen
 Billy G. Allie
 Kevin Altis
 Joe Amenta
+A. Amoroso
 Mark Anacker
 Shashwat Anand
 Anders Andersen
 John Anderson
+Pehr Anderson
 Erik Andersén
 Oliver Andrich
 Ross Andrus
 Juancarlo Añez
 Jérémy Anger
 Jon Anglin
+Heidi Annexstad
 Éric Araujo
 Alicia Arlen
 Jason Asbahr
 David Ascher
 Chris AtLee
 Aymeric Augustin
+Jesús Cea Avión
 John Aycock
 Donovan Baarda
 Attila Babo
@@ -52,8 +60,10 @@
 Greg Ball
 Luigi Ballabio
 Jeff Balogh
+Manuel Balsera
 Matt Bandy
 Michael J. Barber
+Daniel Barclay
 Nicolas Bareil
 Chris Barker
 Anton Barkovsky
@@ -64,6 +74,7 @@
 Cesar Eduardo Barros
 Des Barry
 Ulf Bartelt
+Don Bashford
 Pior Bastida
 Nick Bastin
 Jeff Bauer
@@ -85,6 +96,7 @@
 Eli Bendersky
 Andrew Bennetts
 Andy Bensky
+Bennett Benson
 Ezra Berch
 Michel Van den Bergh
 Julian Berman
@@ -100,6 +112,7 @@
 Philippe Biondi
 Stuart Bishop
 Roy Bixler
+Jonathan Black
 Renaud Blanch
 Mike Bland
 Martin Bless
@@ -109,6 +122,7 @@
 Finn Bock
 Paul Boddie
 Matthew Boedicker
+Robin Boerdijk
 David Bolen
 Gawain Bolton
 Forest Bond
@@ -120,7 +134,9 @@
 Eric Bouck
 Thierry Bousch
 Sebastian Boving
+Michal Bozon
 Jeff Bradberry
+Aaron Brancotti
 Monty Brandenberg
 Georg Brandl
 Christopher Brannon
@@ -130,6 +146,7 @@
 Dave Brennan
 Tom Bridgman
 Anthony Briggs
+Keith Briggs
 Tobias Brink
 Richard Brodie
 Michael Broghton
@@ -140,6 +157,7 @@
 Oleg Broytmann
 Dave Brueck
 Francisco Martín Brugué
+Ian Bruntlett
 Floris Bruynooghe
 Stan Bubrouski
 Erik de Bueger
@@ -167,6 +185,7 @@
 Charles Cazabon
 Per Cederqvist
 Matej Cepl
+Carl Cerecke
 Octavian Cerna
 Pascal Chambon
 John Chandler
@@ -186,8 +205,10 @@
 Anders Chrigström
 Tom Christiansen
 Vadim Chugunov
+Mauro Cicognini
 David Cinege
 Craig Citro
+Gilles Civario
 Chris Clark
 Mike Clarkson
 Andrew Clegg
@@ -222,6 +243,7 @@
 Matthew Dixon Cowles
 Ryan Coyner
 Christopher A. Craig
+Jeremy Craven
 Laura Creighton
 Simon Cross
 Drew Csillag
@@ -249,6 +271,7 @@
 Konrad Delong
 Erik Demaine
 John Dennis
+L. Peter Deutsch
 Roger Dev
 Philippe Devalkeneer
 Raghuram Devarakonda
@@ -265,6 +288,7 @@
 Josip Djolonga
 Jaromir Dolecek
 Ismail Donmez
+Robert Donohue
 Marcos Donolo
 Dima Dorfman
 Yves Dorfsman
@@ -274,6 +298,7 @@
 Derk Drukker
 John DuBois
 Paul Dubois
+Jacques Ducasse
 Graham Dumpleton
 Quinn Dunkan
 Robin Dunn
@@ -282,6 +307,7 @@
 Andy Dustman
 Gary Duzan
 Eugene Dvurechenski
+Josip Dzolonga
 Maxim Dzumanenko
 Walter Dörwald
 Hans Eckardt
@@ -327,19 +353,23 @@
 Sebastian Fernandez
 Florian Festi
 John Feuerstein
+Carl Feynman
 Vincent Fiack
 Tomer Filiba
 Jeffrey Finkelstein
 Russell Finn
+Dan Finnie
 Nils Fischbeck
 Frederik Fix
 Matt Fleming
 Hernán Martínez Foffani
+Arnaud Fontaine
 Michael Foord
 Amaury Forgeot d'Arc
 Doug Fort
 John Fouhy
 Andrew Francis
+Stefan Franke
 Martin Franklin
 Bruce Frederiksen
 Robin Friedrich
@@ -360,6 +390,7 @@
 Lele Gaifax
 Santiago Gala
 Yitzchak Gale
+Matthew Gallagher
 Quentin Gallet-Gilles
 Riccardo Attilio Galli
 Raymund Galvin
@@ -376,25 +407,31 @@
 Gabriel Genellina
 Christos Georgiou
 Ben Gertzfield
+Nadim Ghaznavi
 Dinu Gherman
 Jonathan Giddy
 Johannes Gijsbers
 Michael Gilfix
 Yannick Gingras
+Matt Giuca
 Michael Goderbauer
 Christoph Gohlke
 Tim Golden
 Guilherme Gonçalves
 Tiago Gonçalves
 Chris Gonnerman
+Shelley Gooch
 David Goodger
 Hans de Graaff
+Nathaniel Gray
 Eddy De Greef
+Grant Griffin
 Duncan Grisby
 Fabian Groffen
 Eric Groo
 Dag Gruneau
 Filip Gruszczyński
+Thomas Guettler
 Michael Guravage
 Lars Gustäbel
 Thomas Güttler
@@ -410,7 +447,9 @@
 Jesse Hallio
 Jun Hamano
 Alexandre Hamelin
+Anders Hammarquist
 Mark Hammond
+Harald Hanche-Olsen
 Manus Hand
 Milton L. Hankins
 Stephen Hansen
@@ -420,8 +459,11 @@
 Jason Harper
 Brian Harring
 Jonathan Hartley
+Travis B. Hartwell
 Larry Hastings
+Tim Hatch
 Shane Hathaway
+Janko Hauser
 Rycharde Hawkes
 Ben Hayden
 Jochen Hayek
@@ -451,10 +493,13 @@
 Joerg-Cyril Hoehle
 Gregor Hoffleit
 Chris Hoffman
+Stefan Hoffmeister
 Albert Hofkamp
 Tomas Hoger
 Jonathan Hogg
+Steve Holden
 Akintayo Holder
+Thomas Holenstein
 Gerrit Holl
 Shane Holloway
 Rune Holm
@@ -494,6 +539,7 @@
 Tony Ingraldi
 John Interrante
 Bob Ippolito
+Roger Irwin
 Atsuo Ishimoto
 Adam Jackson
 Ben Jackson
@@ -511,12 +557,15 @@
 Julien Jehannet
 Drew Jenkins
 Flemming Kjær Jensen
+Philip H. Jensen
 MunSic Jeong
 Chris Jerdonek
 Jim Jewett
+Pedro Diaz Jimenez
 Orjan Johansen
 Fredrik Johansson
 Gregory K. Johnson
+Kent Johnson
 Simon Johnston
 Matt Joiner
 Thomas Jollans
@@ -549,16 +598,19 @@
 Dan Kenigsberg
 Randall Kern
 Robert Kern
+Jim Kerr
 Magnus Kessler
 Lawrence Kesteloot
 Vivek Khera
 Mads Kiilerich
 Jason Killen
+Jan Kim
 Taek Joo Kim
 W. Trevor King
 Paul Kippes
 Steve Kirsch
 Sebastian Kirsche
+Kamil Kisiel
 Akira Kitada
 Ron Klatchko
 Reid Kleckner
@@ -574,11 +626,14 @@
 Greg Kochanski
 Damon Kohler
 Marko Kohtala
+Guido Kollerie
 Jacek Konieczny
 Марк Коренберг
 Arkady Koplyarov
+Peter A. Koren
 Vlad Korolev
 Joseph Koshy
+Daniel Kozan
 Jerzy Kozera
 Maksim Kozyarchuk
 Stefan Krah
@@ -592,10 +647,13 @@
 Andrej Krpic
 Ivan Krstić
 Andrew Kuchling
+Dave Kuhlman
 Jon Kuhn
 Vladimir Kushnir
+Erno Kuusela
 Ross Lagerwall
 Cameron Laird
+Thomas Lamb
 Jean-Baptiste "Jiba" Lamy
 Ronan Lamy
 Torsten Landschoff
@@ -619,6 +677,7 @@
 Thomas Lee
 Tennessee Leeuwenburg
 Luc Lefebvre
+Glyph Lefkowitz
 Vincent Legoll
 Kip Lehman
 Joerg Lehmann
@@ -626,7 +685,7 @@
 Petri Lehtinen
 Luke Kenneth Casson Leighton
 Tshepang Lekhonkhobe
-Marc-Andre Lemburg
+Marc-André Lemburg
 John Lenton
 Christopher Tur Lesniewski-Laas
 Alain Leufroy
@@ -638,12 +697,16 @@
 Ross Light
 Shawn Ligocki
 Martin Ligr
+Gediminas Liktaras
 Grant Limberg
 Christopher Lindblad
+Ulf A. Lindgren
 Björn Lindqvist
 Per Lindqvist
 Eric Lindvall
 Gregor Lingl
+Everett Lipman
+Mirko Liss
 Nick Lockwood
 Stephanie Lockwood
 Hugo Lopes Tavares
@@ -661,6 +724,8 @@
 Mikael Lyngvig
 Martin von Löwis
 Guillermo López-Anglada
+Jeff MacDonald
+John Machin
 Andrew I MacIntyre
 Tim MacKenzie
 Nick Maclaren
@@ -671,20 +736,25 @@
 Ken Manheimer
 Vladimir Marangozov
 Colin Marc
+Vincent Marchetti
 David Marek
 Doug Marien
 Sven Marnach
 Alex Martelli
 Anthony Martin
 Owen Martin
+Westley Martínez
 Sébastien Martini
 Sidney San Martín
 Roger Masse
 Nick Mathewson
 Simon Mathieu
+Laura Matson
 Graham Matthews
 Dieter Maurer
+Daniel May
 Arnaud Mazin
+Rebecca McCreary
 Kirk McDonald
 Chris McDonough
 Greg McFarlane
@@ -699,6 +769,7 @@
 Bill van Melle
 Lucas Prado Melo
 Ezio Melotti
+Doug Mennella
 Brian Merrell
 Luke Mewburn
 Carl Meyer
@@ -711,6 +782,7 @@
 Stan Mihai
 Stefan Mihaila
 Aristotelis Mikropoulos
+Paolo Milani
 Chad Miller
 Damien Miller
 Jason V. Miller
@@ -727,9 +799,11 @@
 Skip Montanaro
 Peter Moody
 Paul Moore
+Ross Moore
 Derek Morr
 James A Morrison
 Derek McTavish Mounce
+Alessandro Moura
 Pablo Mouzo
 Mher Movsisyan
 Ruslan Mstoi
@@ -740,6 +814,7 @@
 Neil Muller
 Louis Munro
 R. David Murray
+Dale Nagata
 John Nagle
 Takahiro Nakayama
 Travers Naran
@@ -771,13 +846,16 @@
 John O'Connor
 Kevin O'Connor
 Tim O'Malley
+Zooko O'Whielacronx
 James Oakley
 Jon Oberheide
 Pascal Oberndoerfer
 Jeffrey Ollie
 Adam Olsen
 Grant Olson
+Koray Oner
 Piet van Oostrum
+Tomas Oppelstrup
 Jason Orendorff
 Douglas Orr
 Michele Orrù
@@ -787,6 +865,8 @@
 Michael Otteneder
 R. M. Oudkerk
 Russel Owen
+Joonas Paalasmaa
+Shriphani Palakodety
 Ondrej Palkovsky
 Mike Pall
 Todd R. Palmer
@@ -796,8 +876,10 @@
 Peter Parente
 Alexandre Parenteau
 Dan Parisien
+William Park
 Harri Pasanen
 Gaël Pasgrimaud
+Bo Peng
 Joe Peterson
 Randy Pausch
 Samuele Pedroni
@@ -816,6 +898,7 @@
 Joe Peterson
 Chris Petrilli
 Bjorn Pettersen
+Justin D. Pettit
 Ronny Pfannschmidt
 Geoff Philbrick
 Gavrie Philipson
@@ -856,12 +939,12 @@
 Antti Rasinen
 Sridhar Ratnakumar
 Ysj Ray
-Eric Raymond
+Eric S. Raymond
 Edward K. Ream
 Chris Rebert
 Marc Recht
 John Redford
-Terry Reedy
+Terry J. Reedy
 Gareth Rees
 Steve Reeves
 Lennart Regebro
@@ -883,6 +966,7 @@
 Nicholas Riley
 Jean-Claude Rimbault
 Vlad Riscutia
+Wes Rishel
 Juan M. Bello Rivas
 Davide Rizzo
 Anthony Roach
@@ -903,6 +987,7 @@
 Erik Rose
 Jim Roskind
 Brian Rosner
+Guido van Rossum
 Just van Rossum
 Hugo van Rossum
 Saskia van Rossum
@@ -920,6 +1005,8 @@
 Mark Russell
 Rusty Russell
 Nick Russo
+Chris Ryland
+Constantina S.
 Patrick Sabin
 Sébastien Sablé
 Suman Saha
@@ -932,6 +1019,8 @@
 Ilya Sandler
 Mark Sapiro
 Ty Sarna
+Hugh Sasse
+Bob Savage
 Ben Sayer
 sbt
 Marco Scataglini
@@ -947,6 +1036,7 @@
 Michael Schneider
 Peter Schneider-Kamp
 Arvin Schnell
+Scott Schram
 Robin Schreiber
 Chad J. Schroeder
 Sam Schulenburg
@@ -961,6 +1051,7 @@
 Fred Sells
 Jiwon Seo
 Iñigo Serna
+Joakim Sernbrant
 Roger D. Serwy
 Jerry Seutter
 Denis Severson
@@ -968,6 +1059,8 @@
 Ha Shao
 Mark Shannon
 Richard Shapiro
+Justin Sheehy
+Charlie Shepherd
 Bruce Sherwood
 Alexander Shigin
 Pete Shinners
@@ -975,20 +1068,27 @@
 John W. Shipman
 Joel Shprentz
 Itamar Shtull-Trauring
+Yue Shuaijie
 Eric Siegerman
 Paul Sijben
+SilentGhost
 Tim Silk
+Michael Simcich
+Ionel Simionescu
 Kirill Simonov
 Nathan Paul Simons
 Adam Simpkins
 Janne Sinkkonen
+Ng Pheng Siong
 George Sipe
 J. Sipprell
 Kragen Sitaker
+Michael Sloan
 Christopher Smith
 Eric V. Smith
 Gregory P. Smith
 Mark Smith
+Roy Smith
 Rafal Smotrzyk
 Eric Snow
 Dirk Soede
@@ -997,14 +1097,17 @@
 Edoardo Spadolini
 Clay Spence
 Stefan Sperling
+Nicholas Spies
 Per Spilling
 Joshua Spoerri
 Noah Spurrier
 Nathan Srebro
 RajGopal Srinivasan
+Tage Stabell-Kulo
 Quentin Stafford-Fraser
 Frank Stajano
 Joel Stanley
+Anthony Starks
 Oliver Steele
 Greg Stein
 Baruch Sterin
@@ -1024,6 +1127,7 @@
 Pal Subbiah
 Nathan Sullivan
 Mark Summerfield
+Reuben Sumner
 Hisao Suzuki
 Kalle Svensson
 Andrew Svetlov
@@ -1054,6 +1158,7 @@
 Oren Tirosh
 Jason Tishler
 Christian Tismer
+Jim Tittsler
 Frank J. Tobin
 Bennett Todd
 R Lindsay Todd
@@ -1070,6 +1175,7 @@
 Jason Trowbridge
 Anthony Tuininga
 Erno Tukia
+David Turner
 Stephen Turner
 Theodore Turocy
 Bill Tutt
@@ -1080,6 +1186,7 @@
 Daniel Urban
 Michael Urman
 Hector Urtubia
+Ville Vainio
 Andi Vajda
 Case Van Horsen
 Kyle VanderBeek
@@ -1101,6 +1208,7 @@
 Pauli Virtanen
 Frank Visser
 Johannes Vogel
+Martijn Vries
 Sjoerd de Vries
 Niki W. Waibel
 Wojtek Walczak
@@ -1118,8 +1226,10 @@
 Aaron Watters
 Henrik Weber
 Corran Webster
+Glyn Webster
 Stefan Wehr
 Zack Weinberg
+Bob Weiner
 Edward Welbourne
 Cliff Wells
 Rickard Westman
@@ -1132,14 +1242,17 @@
 Gerry Wiener
 Frank Wierzbicki
 Bryce "Zooko" Wilcox-O'Hearn
+Timothy Wild
 Jakub Wilk
 Gerald S. Williams
 Jason Williams
 John Williams
 Sue Williams
+Steven Willis
 Frank Willison
 Greg V. Wilson
 J Derek Wilson
+Paul Winkler
 Jody Winston
 Collin Winter
 Dik Winter
@@ -1155,6 +1268,7 @@
 Dan Wolfe
 Richard Wolff
 Adam Woodbeck
+Steven Work
 Gordon Worley
 Darren Worrall
 Thomas Wouters
@@ -1168,6 +1282,7 @@
 EungJun Yi
 Bob Yodlowski
 Danny Yoo
+Rory Yorke
 George Yoshida
 Masazumi Yoshikawa
 Arnaud Ysmal
@@ -1179,6 +1294,7 @@
 Siebren van der Zee
 Yuxiao Zeng
 Uwe Zessin
+Cheng Zhang
 Kai Zhu
 Tarek Ziadé
 Peter Åstrand
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -2,6 +2,121 @@
 Python News
 +++++++++++
 
+What's New in Python 3.3.1?
+===========================
+
+*Release date: XX-XX-XXXX*
+
+Core and Builtins
+-----------------
+
+- Issue #15379: Fix passing of non-BMP characters as integers for the charmap
+  decoder (already working as unicode strings).  Patch by Serhiy Storchaka.
+
+- Issue #15144: Fix possible integer overflow when handling pointers as
+  integer values, by using Py_uintptr_t instead of size_t.  Patch by
+  Serhiy Storchaka.
+
+- Issue #15965: Explicitly cast AT_FDCWD as (int).  Required on Solaris 10
+  (which defines AT_FDCWD as 0xffd19553), harmless on other platforms.
+
+- Issue #15839: Convert SystemErrors in super() to RuntimeErrors.
+
+- Issue #15846: Fix SystemError which happened when using ast.parse in an
+  exception handler on code with syntax errors.
+
+- Issue #15801: Make sure mappings passed to '%' formatting are actually
+  subscriptable.
+
+Library
+-------
+
+- Issue #15323: improve failure message of Mock.assert_called_once_with
+
+- Issue #16064: unittest -m claims executable is "python", not "python3"
+
+- Issue #12376: Pass on parameters in TextTestResult.__init__ super call
+
+- Issue #15222: Insert blank line after each message in mbox mailboxes
+
+- Issue #16013: Fix CSV Reader parsing issue with ending quote characters.
+  Patch by Serhiy Storchaka.
+
+- Issue #15421: Fix an OverflowError in Calendar.itermonthdates() after
+  datetime.MAXYEAR.  Patch by Cédric Krier.
+
+- Issue #15970: xml.etree.ElementTree now serializes correctly the empty HTML
+  elements 'meta' and 'param'.
+
+- Issue #15842: The SocketIO.{readable,writable,seekable} methods now
+  raise ValueError when the file-like object is closed.  Patch by Alessandro
+  Moura.
+
+- Issue #15876: Fix a refleak in the curses module: window.encoding.
+
+- Issue #15881: Fixed atexit hook in multiprocessing.  Original patch
+  by Chris McDonough.
+
+- Issue #15340: Fix importing the random module when /dev/urandom cannot
+  be opened.  This was a regression caused by the hash randomization patch.
+
+- Issue #15841: The readable(), writable() and seekable() methods of BytesIO
+  and StringIO objects now raise ValueError when the object has been closed.
+  Patch by Alessandro Moura.
+
+- Issue #15447: Use subprocess.DEVNULL in webbrowser, instead of opening
+  os.devnull explicitly and leaving it open.
+
+- Issue #15509: webbrowser.UnixBrowser no longer passes empty arguments to
+  Popen when %action substitutions produce empty strings.
+
+- Issue #12776,#11839: call argparse type function (specified by add_argument)
+  only once. Before, the type function was called twice in the case where the
+  default was specified and the argument was given as well.  This was
+  especially problematic for the FileType type, as a default file would always
+  be opened, even if a file argument was specified on the command line.
+
+- Issue #15906: Fix a regression in argparse caused by the preceding change,
+  when action='append', type='str' and default=[].
+
+Extension Modules
+-----------------
+
+Tests
+-----
+
+- Issue #15304: Fix warning message when os.chdir() fails inside
+  test.support.temp_cwd().  Patch by Chris Jerdonek.
+
+
+- Issue #15802: Fix test logic in TestMaildir.test_create_tmp. Patch
+  by Serhiy Storchaka.
+
+- Issue #15557: Added a test suite for the webbrowser module, thanks
+  to Anton Barkovsky.
+
+Build
+-----
+
+- Issue #15819: Make sure we can build Python out-of-tree from a readonly
+  source directory.  (Somewhat related to Issue #9860.)
+
+Documentation
+-------------
+
+- Issue #16036: Improve documentation of built-in int()'s signature and
+  arguments.
+
+- Issue #15935: Clarification of argparse docs, re: add_argument() type and
+  default arguments.  Patch contributed by Chris Jerdonek.
+
+- Issue #11964: Document a change in v3.2 to the behavior of the indent
+  parameter of json encoding operations.
+
+Tools/Demos
+-----------
+
+
 What's New in Python 3.3.0?
 ===========================
 
@@ -172,8 +287,6 @@
 
 - Issue #15544: Fix Decimal.__float__ to work with payload-carrying NaNs.
 
-- Issue #15776: Allow pyvenv to work in existing directory with --clean.
-
 - Issue #15249: BytesGenerator now correctly mangles From lines (when
   requested) even if the body contains undecodable bytes.
 
@@ -190,6 +303,9 @@
 
 - Issue #13579: string.Formatter now understands the 'a' conversion specifier.
 
+- Issue #15793: Stack corruption in ssl.RAND_egd().
+  Patch by Serhiy Storchaka.
+
 - Issue #15595: Fix subprocess.Popen(universal_newlines=True)
   for certain locales (utf-16 and utf-32 family). Patch by Chris Jerdonek.
 
@@ -528,6 +644,9 @@
 Extension Modules
 -----------------
 
+- Issue #15676: Now "mmap" check for empty files before doing the
+  offset check.  Patch by Steven Willis.
+
 - Issue #6493: An issue in ctypes on Windows that caused structure bitfields
   of type ctypes.c_uint32 and width 32 to incorrectly be set has been fixed.
 
diff --git a/Modules/_csv.c b/Modules/_csv.c
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -788,9 +788,14 @@
         lineobj = PyIter_Next(self->input_iter);
         if (lineobj == NULL) {
             /* End of input OR exception */
-            if (!PyErr_Occurred() && self->field_len != 0)
-                PyErr_Format(_csvstate_global->error_obj,
-                             "newline inside string");
+            if (!PyErr_Occurred() && (self->field_len != 0 ||
+                                      self->state == IN_QUOTED_FIELD)) {
+                if (self->dialect->strict)
+                    PyErr_SetString(_csvstate_global->error_obj,
+                                    "unexpected end of data");
+                else if (parse_save_field(self) >= 0)
+                    break;
+            }
             return NULL;
         }
         if (!PyUnicode_Check(lineobj)) {
diff --git a/Modules/_cursesmodule.c b/Modules/_cursesmodule.c
--- a/Modules/_cursesmodule.c
+++ b/Modules/_cursesmodule.c
@@ -1938,6 +1938,7 @@
     if (ascii == NULL)
         return -1;
     encoding = strdup(PyBytes_AS_STRING(ascii));
+    Py_DECREF(ascii);
     if (encoding == NULL) {
         PyErr_NoMemory();
         return -1;
diff --git a/Modules/_decimal/tests/bench.py b/Modules/_decimal/tests/bench.py
--- a/Modules/_decimal/tests/bench.py
+++ b/Modules/_decimal/tests/bench.py
@@ -10,7 +10,10 @@
 
 import time
 from math import log, ceil
-from test.support import import_fresh_module
+try:
+    from test.support import import_fresh_module
+except ImportError:
+    from test.test_support import import_fresh_module
 
 C = import_fresh_module('decimal', fresh=['_decimal'])
 P = import_fresh_module('decimal', blocked=['_decimal'])
@@ -67,11 +70,16 @@
 print("#                   Calculating pi, 10000 iterations")
 print("# ======================================================================\n")
 
+to_benchmark = [pi_float, pi_decimal]
+if C is not None:
+    to_benchmark.insert(1, pi_cdecimal)
+
 for prec in [9, 19]:
     print("\nPrecision: %d decimal digits\n" % prec)
-    for func in [pi_float, pi_cdecimal, pi_decimal]:
+    for func in to_benchmark:
         start = time.time()
-        C.getcontext().prec = prec
+        if C is not None:
+            C.getcontext().prec = prec
         P.getcontext().prec = prec
         for i in range(10000):
             x = func()
@@ -84,25 +92,27 @@
 print("#                               Factorial")
 print("# ======================================================================\n")
 
-c = C.getcontext()
-c.prec = C.MAX_PREC
-c.Emax = C.MAX_EMAX
-c.Emin = C.MIN_EMIN
+if C is not None:
+    c = C.getcontext()
+    c.prec = C.MAX_PREC
+    c.Emax = C.MAX_EMAX
+    c.Emin = C.MIN_EMIN
 
 for n in [100000, 1000000]:
 
     print("n = %d\n" % n)
 
-    # C version of decimal
-    start_calc = time.time()
-    x = factorial(C.Decimal(n), 0)
-    end_calc = time.time()
-    start_conv = time.time()
-    sx = str(x)
-    end_conv = time.time()
-    print("cdecimal:")
-    print("calculation time: %fs" % (end_calc-start_calc))
-    print("conversion time: %fs\n" % (end_conv-start_conv))
+    if C is not None:
+        # C version of decimal
+        start_calc = time.time()
+        x = factorial(C.Decimal(n), 0)
+        end_calc = time.time()
+        start_conv = time.time()
+        sx = str(x)
+        end_conv = time.time()
+        print("cdecimal:")
+        print("calculation time: %fs" % (end_calc-start_calc))
+        print("conversion time: %fs\n" % (end_conv-start_conv))
 
     # Python integers
     start_calc = time.time()
@@ -116,4 +126,5 @@
     print("calculation time: %fs" % (end_calc-start_calc))
     print("conversion time: %fs\n\n" % (end_conv-start_conv))
 
-    assert(sx == sy)
+    if C is not None:
+        assert(sx == sy)
diff --git a/Modules/_elementtree.c b/Modules/_elementtree.c
--- a/Modules/_elementtree.c
+++ b/Modules/_elementtree.c
@@ -98,7 +98,7 @@
    info. */
 #define JOIN_GET(p) ((Py_uintptr_t) (p) & 1)
 #define JOIN_SET(p, flag) ((void*) ((Py_uintptr_t) (JOIN_OBJ(p)) | (flag)))
-#define JOIN_OBJ(p) ((PyObject*) ((Py_uintptr_t) (p) & ~1))
+#define JOIN_OBJ(p) ((PyObject*) ((Py_uintptr_t) (p) & ~(Py_uintptr_t)1))
 
 /* glue functions (see the init function for details) */
 static PyObject* elementtree_parseerror_obj;
diff --git a/Modules/_io/_iomodule.c b/Modules/_io/_iomodule.c
--- a/Modules/_io/_iomodule.c
+++ b/Modules/_io/_iomodule.c
@@ -185,7 +185,7 @@
 "\n"
 "* On output, if newline is None, any '\\n' characters written are\n"
 "  translated to the system default line separator, os.linesep. If\n"
-"  newline is '' or '\n', no translation takes place. If newline is any\n"
+"  newline is '' or '\\n', no translation takes place. If newline is any\n"
 "  of the other legal values, any '\\n' characters written are translated\n"
 "  to the given string.\n"
 "\n"
diff --git a/Modules/_io/bytesio.c b/Modules/_io/bytesio.c
--- a/Modules/_io/bytesio.c
+++ b/Modules/_io/bytesio.c
@@ -121,7 +121,7 @@
 }
 
 /* Internal routine for writing a string of bytes to the buffer of a BytesIO
-   object. Returns the number of bytes wrote, or -1 on error. */
+   object. Returns the number of bytes written, or -1 on error. */
 static Py_ssize_t
 write_bytes(bytesio *self, const char *bytes, Py_ssize_t len)
 {
@@ -171,10 +171,20 @@
     }
 }
 
+PyDoc_STRVAR(readable_doc,
+"readable() -> bool. Returns True if the IO object can be read.");
+
+PyDoc_STRVAR(writable_doc,
+"writable() -> bool. Returns True if the IO object can be written.");
+
+PyDoc_STRVAR(seekable_doc,
+"seekable() -> bool. Returns True if the IO object can be seeked.");
+
 /* Generic getter for the writable, readable and seekable properties */
 static PyObject *
-return_true(bytesio *self)
+return_not_closed(bytesio *self)
 {
+    CHECK_CLOSED(self);
     Py_RETURN_TRUE;
 }
 
@@ -682,8 +692,10 @@
     }
     else {
         dict = PyDict_Copy(self->dict);
-        if (dict == NULL)
+        if (dict == NULL) {
+            Py_DECREF(initvalue);
             return NULL;
+        }
     }
 
     state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
@@ -867,9 +879,9 @@
 };
 
 static struct PyMethodDef bytesio_methods[] = {
-    {"readable",   (PyCFunction)return_true,        METH_NOARGS, NULL},
-    {"seekable",   (PyCFunction)return_true,        METH_NOARGS, NULL},
-    {"writable",   (PyCFunction)return_true,        METH_NOARGS, NULL},
+    {"readable",   (PyCFunction)return_not_closed,  METH_NOARGS, readable_doc},
+    {"seekable",   (PyCFunction)return_not_closed,  METH_NOARGS, seekable_doc},
+    {"writable",   (PyCFunction)return_not_closed,  METH_NOARGS, writable_doc},
     {"close",      (PyCFunction)bytesio_close,      METH_NOARGS, close_doc},
     {"flush",      (PyCFunction)bytesio_flush,      METH_NOARGS, flush_doc},
     {"isatty",     (PyCFunction)bytesio_isatty,     METH_NOARGS, isatty_doc},
diff --git a/Modules/_io/iobase.c b/Modules/_io/iobase.c
--- a/Modules/_io/iobase.c
+++ b/Modules/_io/iobase.c
@@ -442,7 +442,7 @@
     "\n"
     "If limit is specified, at most limit bytes will be read.\n"
     "\n"
-    "The line terminator is always b'\n' for binary files; for text\n"
+    "The line terminator is always b'\\n' for binary files; for text\n"
     "files, the newlines argument to open can be used to select the line\n"
     "terminator(s) recognized.\n");
 
diff --git a/Modules/_io/stringio.c b/Modules/_io/stringio.c
--- a/Modules/_io/stringio.c
+++ b/Modules/_io/stringio.c
@@ -760,10 +760,21 @@
 }
 
 /* Properties and pseudo-properties */
+
+PyDoc_STRVAR(stringio_readable_doc,
+"readable() -> bool. Returns True if the IO object can be read.");
+
+PyDoc_STRVAR(stringio_writable_doc,
+"writable() -> bool. Returns True if the IO object can be written.");
+
+PyDoc_STRVAR(stringio_seekable_doc,
+"seekable() -> bool. Returns True if the IO object can be seeked.");
+
 static PyObject *
 stringio_seekable(stringio *self, PyObject *args)
 {
     CHECK_INITIALIZED(self);
+    CHECK_CLOSED(self);
     Py_RETURN_TRUE;
 }
 
@@ -771,6 +782,7 @@
 stringio_readable(stringio *self, PyObject *args)
 {
     CHECK_INITIALIZED(self);
+    CHECK_CLOSED(self);
     Py_RETURN_TRUE;
 }
 
@@ -778,6 +790,7 @@
 stringio_writable(stringio *self, PyObject *args)
 {
     CHECK_INITIALIZED(self);
+    CHECK_CLOSED(self);
     Py_RETURN_TRUE;
 }
 
@@ -956,9 +969,9 @@
     {"seek",     (PyCFunction)stringio_seek,     METH_VARARGS, stringio_seek_doc},
     {"write",    (PyCFunction)stringio_write,    METH_O,       stringio_write_doc},
 
-    {"seekable", (PyCFunction)stringio_seekable, METH_NOARGS},
-    {"readable", (PyCFunction)stringio_readable, METH_NOARGS},
-    {"writable", (PyCFunction)stringio_writable, METH_NOARGS},
+    {"seekable", (PyCFunction)stringio_seekable, METH_NOARGS, stringio_seekable_doc},
+    {"readable", (PyCFunction)stringio_readable, METH_NOARGS, stringio_readable_doc},
+    {"writable", (PyCFunction)stringio_writable, METH_NOARGS, stringio_writable_doc},
 
     {"__getstate__", (PyCFunction)stringio_getstate, METH_NOARGS},
     {"__setstate__", (PyCFunction)stringio_setstate, METH_O},
diff --git a/Modules/_io/textio.c b/Modules/_io/textio.c
--- a/Modules/_io/textio.c
+++ b/Modules/_io/textio.c
@@ -648,7 +648,7 @@
     "\n"
     "* On output, if newline is None, any '\\n' characters written are\n"
     "  translated to the system default line separator, os.linesep. If\n"
-    "  newline is '' or '\n', no translation takes place. If newline is any\n"
+    "  newline is '' or '\\n', no translation takes place. If newline is any\n"
     "  of the other legal values, any '\\n' characters written are translated\n"
     "  to the given string.\n"
     "\n"
diff --git a/Modules/_ssl.c b/Modules/_ssl.c
--- a/Modules/_ssl.c
+++ b/Modules/_ssl.c
@@ -2488,7 +2488,7 @@
     PyObject *path;
     int bytes;
 
-    if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
+    if (!PyArg_ParseTuple(args, "O&:RAND_egd",
                           PyUnicode_FSConverter, &path))
         return NULL;
 
diff --git a/Modules/_testbuffer.c b/Modules/_testbuffer.c
--- a/Modules/_testbuffer.c
+++ b/Modules/_testbuffer.c
@@ -16,6 +16,7 @@
 static const char *simple_fmt = "B";
 PyObject *simple_format = NULL;
 #define SIMPLE_FORMAT(fmt) (fmt == NULL || strcmp(fmt, "B") == 0)
+#define FIX_FORMAT(fmt) (fmt == NULL ? "B" : fmt)
 
 
 /**************************************************************************/
@@ -513,10 +514,8 @@
 cmp_structure(Py_buffer *dest, Py_buffer *src)
 {
     Py_ssize_t i;
-    int same_fmt = ((dest->format == NULL && src->format == NULL) || \
-                    (strcmp(dest->format, src->format) == 0));
-
-    if (!same_fmt ||
+
+    if (strcmp(FIX_FORMAT(dest->format), FIX_FORMAT(src->format)) != 0 ||
         dest->itemsize != src->itemsize ||
         dest->ndim != src->ndim)
         return -1;
diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c
--- a/Modules/mmapmodule.c
+++ b/Modules/mmapmodule.c
@@ -1163,6 +1163,11 @@
     if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
         if (map_size == 0) {
             off_t calc_size;
+            if (st.st_size == 0) {
+                PyErr_SetString(PyExc_ValueError,
+                                "cannot mmap an empty file");
+                return NULL;
+            }
             if (offset >= st.st_size) {
                 PyErr_SetString(PyExc_ValueError,
                                 "mmap offset is greater than file size");
@@ -1359,6 +1364,12 @@
             }
 
             size = (((PY_LONG_LONG) high) << 32) + low;
+            if (size == 0) {
+                PyErr_SetString(PyExc_ValueError,
+                                "cannot mmap an empty file");
+                Py_DECREF(m_obj);
+                return NULL;
+            }
             if (offset >= size) {
                 PyErr_SetString(PyExc_ValueError,
                                 "mmap offset is greater than file size");
diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
--- a/Modules/posixmodule.c
+++ b/Modules/posixmodule.c
@@ -414,7 +414,14 @@
 
 
 #ifdef AT_FDCWD
-#define DEFAULT_DIR_FD AT_FDCWD
+/*
+ * Why the (int) cast?  Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
+ * without the int cast, the value gets interpreted as uint (4291925331),
+ * which doesn't play nicely with all the initializer lines in this file that
+ * look like this:
+ *      int dir_fd = DEFAULT_DIR_FD;
+ */
+#define DEFAULT_DIR_FD (int)AT_FDCWD
 #else
 #define DEFAULT_DIR_FD (-100)
 #endif
diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c
--- a/Modules/selectmodule.c
+++ b/Modules/selectmodule.c
@@ -239,7 +239,7 @@
 #else
         /* 64-bit OS X has struct timeval.tv_usec as an int (and thus still 4
            bytes as required), but no longer defined by a long. */
-        long tv_usec = tv.tv_usec;
+        long tv_usec;
         if (_PyTime_ObjectToTimeval(tout, &tv.tv_sec, &tv_usec) == -1)
             return NULL;
         tv.tv_usec = tv_usec;
diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c
--- a/Modules/socketmodule.c
+++ b/Modules/socketmodule.c
@@ -1674,7 +1674,8 @@
             if (len == 0) {
                 ifr.ifr_ifindex = 0;
             } else if (len < sizeof(ifr.ifr_name)) {
-                strcpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName));
+                strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
+                ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
                 if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
                     s->errorhandler();
                     Py_DECREF(interfaceName);
diff --git a/Modules/zipimport.c b/Modules/zipimport.c
--- a/Modules/zipimport.c
+++ b/Modules/zipimport.c
@@ -236,12 +236,16 @@
         return NULL;
     }
 
-    if (!PyUnicode_AsUCS4(prefix, p, len, 0))
+    if (!PyUnicode_AsUCS4(prefix, p, len, 0)) {
+        PyMem_Free(buf);
         return NULL;
+    }
     p += PyUnicode_GET_LENGTH(prefix);
     len -= PyUnicode_GET_LENGTH(prefix);
-    if (!PyUnicode_AsUCS4(name, p, len, 1))
+    if (!PyUnicode_AsUCS4(name, p, len, 1)) {
+        PyMem_Free(buf);
         return NULL;
+    }
     for (; *p; p++) {
         if (*p == '.')
             *p = SEP;
diff --git a/Objects/classobject.c b/Objects/classobject.c
--- a/Objects/classobject.c
+++ b/Objects/classobject.c
@@ -219,7 +219,7 @@
 {
     PyObject *self = a->im_self;
     PyObject *func = a->im_func;
-    PyObject *klass = (PyObject*)Py_TYPE(self);
+    PyObject *klass;
     PyObject *funcname = NULL ,*klassname = NULL, *result = NULL;
     char *defname = "?";
 
@@ -227,6 +227,7 @@
         PyErr_BadInternalCall();
         return NULL;
     }
+    klass = (PyObject*)Py_TYPE(self);
 
     funcname = _PyObject_GetAttrId(func, &PyId___name__);
     if (funcname == NULL) {
diff --git a/Objects/longobject.c b/Objects/longobject.c
--- a/Objects/longobject.c
+++ b/Objects/longobject.c
@@ -30,7 +30,7 @@
 */
 static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
 #ifdef COUNT_ALLOCS
-int quick_int_allocs, quick_neg_int_allocs;
+Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
 #endif
 
 static PyObject *
@@ -1628,8 +1628,10 @@
         strlen++;
     }
     if (writer) {
-        if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1)
+        if (_PyUnicodeWriter_Prepare(writer, strlen, '9') == -1) {
+            Py_DECREF(scratch);
             return -1;
+        }
         kind = writer->kind;
         str = NULL;
     }
@@ -4283,8 +4285,8 @@
             string = PyByteArray_AS_STRING(x);
         else
             string = PyBytes_AS_STRING(x);
-        if (strlen(string) != (size_t)size) {
-            /* We only see this if there's a null byte in x,
+        if (strlen(string) != (size_t)size || !size) {
+            /* We only see this if there's a null byte in x or x is empty,
                x is a bytes or buffer, *and* a base is given. */
             PyErr_Format(PyExc_ValueError,
                          "invalid literal for int() with base %d: %R",
diff --git a/Objects/memoryobject.c b/Objects/memoryobject.c
--- a/Objects/memoryobject.c
+++ b/Objects/memoryobject.c
@@ -2861,28 +2861,74 @@
     return PyBool_FromLong(MV_ANY_CONTIGUOUS(self->flags));
 }
 
+PyDoc_STRVAR(memory_obj_doc,
+             "The underlying object of the memoryview.");
+PyDoc_STRVAR(memory_nbytes_doc,
+             "The amount of space in bytes that the array would use in\n"
+             " a contiguous representation.");
+PyDoc_STRVAR(memory_readonly_doc,
+             "A bool indicating whether the memory is read only.");
+PyDoc_STRVAR(memory_itemsize_doc,
+             "The size in bytes of each element of the memoryview.");
+PyDoc_STRVAR(memory_format_doc,
+             "A string containing the format (in struct module style)\n"
+             " for each element in the view.");
+PyDoc_STRVAR(memory_ndim_doc,
+             "An integer indicating how many dimensions of a multi-dimensional\n"
+             " array the memory represents.");
+PyDoc_STRVAR(memory_shape_doc,
+             "A tuple of ndim integers giving the shape of the memory\n"
+             " as an N-dimensional array.");
+PyDoc_STRVAR(memory_strides_doc,
+             "A tuple of ndim integers giving the size in bytes to access\n"
+             " each element for each dimension of the array.");
+PyDoc_STRVAR(memory_suboffsets_doc,
+             "A tuple of integers used internally for PIL-style arrays.");
+PyDoc_STRVAR(memory_c_contiguous_doc,
+             "A bool indicating whether the memory is C contiguous.");
+PyDoc_STRVAR(memory_f_contiguous_doc,
+             "A bool indicating whether the memory is Fortran contiguous.");
+PyDoc_STRVAR(memory_contiguous_doc,
+             "A bool indicating whether the memory is contiguous.");
+
 static PyGetSetDef memory_getsetlist[] = {
-    {"obj",             (getter)memory_obj_get,        NULL, NULL},
-    {"nbytes",          (getter)memory_nbytes_get,     NULL, NULL},
-    {"readonly",        (getter)memory_readonly_get,   NULL, NULL},
-    {"itemsize",        (getter)memory_itemsize_get,   NULL, NULL},
-    {"format",          (getter)memory_format_get,     NULL, NULL},
-    {"ndim",            (getter)memory_ndim_get,       NULL, NULL},
-    {"shape",           (getter)memory_shape_get,      NULL, NULL},
-    {"strides",         (getter)memory_strides_get,    NULL, NULL},
-    {"suboffsets",      (getter)memory_suboffsets_get, NULL, NULL},
-    {"c_contiguous",    (getter)memory_c_contiguous,   NULL, NULL},
-    {"f_contiguous",    (getter)memory_f_contiguous,   NULL, NULL},
-    {"contiguous",      (getter)memory_contiguous,     NULL, NULL},
+    {"obj",             (getter)memory_obj_get,        NULL, memory_obj_doc},
+    {"nbytes",          (getter)memory_nbytes_get,     NULL, memory_nbytes_doc},
+    {"readonly",        (getter)memory_readonly_get,   NULL, memory_readonly_doc},
+    {"itemsize",        (getter)memory_itemsize_get,   NULL, memory_itemsize_doc},
+    {"format",          (getter)memory_format_get,     NULL, memory_format_doc},
+    {"ndim",            (getter)memory_ndim_get,       NULL, memory_ndim_doc},
+    {"shape",           (getter)memory_shape_get,      NULL, memory_shape_doc},
+    {"strides",         (getter)memory_strides_get,    NULL, memory_strides_doc},
+    {"suboffsets",      (getter)memory_suboffsets_get, NULL, memory_suboffsets_doc},
+    {"c_contiguous",    (getter)memory_c_contiguous,   NULL, memory_c_contiguous_doc},
+    {"f_contiguous",    (getter)memory_f_contiguous,   NULL, memory_f_contiguous_doc},
+    {"contiguous",      (getter)memory_contiguous,     NULL, memory_contiguous_doc},
     {NULL, NULL, NULL, NULL},
 };
 
+PyDoc_STRVAR(memory_release_doc,
+"M.release() -> None\n\
+\n\
+Release the underlying buffer exposed by the memoryview object.");
+PyDoc_STRVAR(memory_tobytes_doc,
+"M.tobytes() -> bytes\n\
+\n\
+Return the data in the buffer as a byte string.");
+PyDoc_STRVAR(memory_tolist_doc,
+"M.tolist() -> list\n\
+\n\
+Return the data in the buffer as a list of elements.");
+PyDoc_STRVAR(memory_cast_doc,
+"M.cast(format[, shape]) -> memoryview\n\
+\n\
+Cast a memoryview to a new format or shape.");
 
 static PyMethodDef memory_methods[] = {
-    {"release",     (PyCFunction)memory_release, METH_NOARGS, NULL},
-    {"tobytes",     (PyCFunction)memory_tobytes, METH_NOARGS, NULL},
-    {"tolist",      (PyCFunction)memory_tolist, METH_NOARGS, NULL},
-    {"cast",        (PyCFunction)memory_cast, METH_VARARGS|METH_KEYWORDS, NULL},
+    {"release",     (PyCFunction)memory_release, METH_NOARGS, memory_release_doc},
+    {"tobytes",     (PyCFunction)memory_tobytes, METH_NOARGS, memory_tobytes_doc},
+    {"tolist",      (PyCFunction)memory_tolist, METH_NOARGS, memory_tolist_doc},
+    {"cast",        (PyCFunction)memory_cast, METH_VARARGS|METH_KEYWORDS, memory_cast_doc},
     {"__enter__",   memory_enter, METH_NOARGS, NULL},
     {"__exit__",    memory_exit, METH_VARARGS, NULL},
     {NULL,          NULL}
diff --git a/Objects/obmalloc.c b/Objects/obmalloc.c
--- a/Objects/obmalloc.c
+++ b/Objects/obmalloc.c
@@ -138,7 +138,6 @@
  */
 #define ALIGNMENT               8               /* must be 2^N */
 #define ALIGNMENT_SHIFT         3
-#define ALIGNMENT_MASK          (ALIGNMENT - 1)
 
 /* Return the number of bytes in size class I, as a uint. */
 #define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
@@ -314,14 +313,12 @@
     struct arena_object* prevarena;
 };
 
-#undef  ROUNDUP
-#define ROUNDUP(x)              (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
-#define POOL_OVERHEAD           ROUNDUP(sizeof(struct pool_header))
+#define POOL_OVERHEAD   _Py_SIZE_ROUND_UP(sizeof(struct pool_header), ALIGNMENT)
 
 #define DUMMY_SIZE_IDX          0xffff  /* size class of newly cached pools */
 
 /* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
-#define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
+#define POOL_ADDR(P) ((poolp)_Py_ALIGN_DOWN((P), POOL_SIZE))
 
 /* Return total number of blocks in pool of size index I, as a uint. */
 #define NUMBLOCKS(I) ((uint)(POOL_SIZE - POOL_OVERHEAD) / INDEX2SIZE(I))
diff --git a/Objects/setobject.c b/Objects/setobject.c
--- a/Objects/setobject.c
+++ b/Objects/setobject.c
@@ -831,10 +831,10 @@
     if (!list)
         return NULL;
 
-    /* copy the itertor state */
+    /* copy the iterator state */
     tmp = *si;
     Py_XINCREF(tmp.si_set);
-    
+
     /* iterate the temporary into a list */
     for(;;) {
         PyObject *element = setiter_iternext(&tmp);
diff --git a/Objects/stringlib/codecs.h b/Objects/stringlib/codecs.h
--- a/Objects/stringlib/codecs.h
+++ b/Objects/stringlib/codecs.h
@@ -2,9 +2,6 @@
 
 #if STRINGLIB_IS_UNICODE
 
-/* Mask to check or force alignment of a pointer to C 'long' boundaries */
-#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
-
 /* Mask to quickly check whether a C 'long' contains a
    non-ASCII, UTF8-encoded char. */
 #if (SIZEOF_LONG == 8)
@@ -25,7 +22,7 @@
 {
     Py_UCS4 ch;
     const char *s = *inptr;
-    const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
+    const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
     STRINGLIB_CHAR *p = dest + *outpos;
 
     while (s < end) {
@@ -39,7 +36,7 @@
                First, check if we can do an aligned read, as most CPUs have
                a penalty for unaligned reads.
             */
-            if (!((size_t) s & LONG_PTR_MASK)) {
+            if (_Py_IS_ALIGNED(s, SIZEOF_LONG)) {
                 /* Help register allocation */
                 register const char *_s = s;
                 register STRINGLIB_CHAR *_p = p;
@@ -453,7 +450,7 @@
 {
     Py_UCS4 ch;
     const unsigned char *aligned_end =
-            (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
+            (const unsigned char *) _Py_ALIGN_DOWN(e, SIZEOF_LONG);
     const unsigned char *q = *inptr;
     STRINGLIB_CHAR *p = dest + *outpos;
     /* Offsets from q for retrieving byte pairs in the right order. */
@@ -468,7 +465,7 @@
         Py_UCS4 ch2;
         /* First check for possible aligned read of a C 'long'. Unaligned
            reads are more expensive, better to defer to another iteration. */
-        if (!((size_t) q & LONG_PTR_MASK)) {
+        if (_Py_IS_ALIGNED(q, SIZEOF_LONG)) {
             /* Fast path for runs of in-range non-surrogate chars. */
             register const unsigned char *_q = q;
             while (_q < aligned_end) {
@@ -565,7 +562,6 @@
 #undef FAST_CHAR_MASK
 #undef STRIPPED_MASK
 #undef SWAB
-#undef LONG_PTR_MASK
 
 
 Py_LOCAL_INLINE(void)
@@ -588,7 +584,7 @@
         _PyUnicode_CONVERT_BYTES(STRINGLIB_CHAR, unsigned short, in, end, out);
 # endif
     } else {
-        const STRINGLIB_CHAR *unrolled_end = in + (len & ~ (Py_ssize_t) 3);
+        const STRINGLIB_CHAR *unrolled_end = in + _Py_SIZE_ROUND_DOWN(len, 4);
         while (in < unrolled_end) {
             out[0] = SWAB2(in[0]);
             out[1] = SWAB2(in[1]);
diff --git a/Objects/stringlib/fastsearch.h b/Objects/stringlib/fastsearch.h
--- a/Objects/stringlib/fastsearch.h
+++ b/Objects/stringlib/fastsearch.h
@@ -43,8 +43,7 @@
 
 #define DO_MEMCHR(memchr, s, needle, nchars) do { \
     candidate = memchr((const void *) (s), (needle), (nchars) * sizeof(STRINGLIB_CHAR)); \
-    found = (const STRINGLIB_CHAR *) \
-        ((Py_ssize_t) candidate & (~ ((Py_ssize_t) sizeof(STRINGLIB_CHAR) - 1))); \
+    found = (const STRINGLIB_CHAR *) _Py_ALIGN_DOWN(candidate, sizeof(STRINGLIB_CHAR)); \
     } while (0)
 
     if (mode == FAST_SEARCH) {
diff --git a/Objects/stringlib/find_max_char.h b/Objects/stringlib/find_max_char.h
--- a/Objects/stringlib/find_max_char.h
+++ b/Objects/stringlib/find_max_char.h
@@ -2,9 +2,6 @@
 
 #if STRINGLIB_IS_UNICODE
 
-/* Mask to check or force alignment of a pointer to C 'long' boundaries */
-#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
-
 /* Mask to quickly check whether a C 'long' contains a
    non-ASCII, UTF8-encoded char. */
 #if (SIZEOF_LONG == 8)
@@ -21,10 +18,11 @@
 STRINGLIB(find_max_char)(const STRINGLIB_CHAR *begin, const STRINGLIB_CHAR *end)
 {
     const unsigned char *p = (const unsigned char *) begin;
-    const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
+    const unsigned char *aligned_end =
+            (const unsigned char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
 
     while (p < end) {
-        if (!((size_t) p & LONG_PTR_MASK)) {
+        if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
             /* Help register allocation */
             register const unsigned char *_p = p;
             while (_p < aligned_end) {
@@ -43,7 +41,6 @@
     return 127;
 }
 
-#undef LONG_PTR_MASK
 #undef ASCII_CHAR_MASK
 
 #else /* STRINGLIB_SIZEOF_CHAR == 1 */
@@ -72,7 +69,7 @@
     register Py_UCS4 mask;
     Py_ssize_t n = end - begin;
     const STRINGLIB_CHAR *p = begin;
-    const STRINGLIB_CHAR *unrolled_end = begin + (n & ~ (Py_ssize_t) 3);
+    const STRINGLIB_CHAR *unrolled_end = begin + _Py_SIZE_ROUND_DOWN(n, 4);
     Py_UCS4 max_char;
 
     max_char = MAX_CHAR_ASCII;
diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c
--- a/Objects/tupleobject.c
+++ b/Objects/tupleobject.c
@@ -210,8 +210,10 @@
 
     va_start(vargs, n);
     result = PyTuple_New(n);
-    if (result == NULL)
+    if (result == NULL) {
+        va_end(vargs);
         return NULL;
+    }
     items = ((PyTupleObject *)result)->ob_item;
     for (i = 0; i < n; i++) {
         o = va_arg(vargs, PyObject *);
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -691,8 +691,10 @@
         mod = NULL;
     }
     name = type_qualname(type, NULL);
-    if (name == NULL)
+    if (name == NULL) {
+        Py_XDECREF(mod);
         return NULL;
+    }
 
     if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
         rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
@@ -3128,8 +3130,10 @@
         mod = NULL;
     }
     name = type_qualname(type, NULL);
-    if (name == NULL)
+    if (name == NULL) {
+        Py_XDECREF(mod);
         return NULL;
+    }
     if (mod != NULL && PyUnicode_CompareWithASCIIString(mod, "builtins"))
         rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
     else
@@ -5988,7 +5992,7 @@
         descr = _PyType_Lookup(type, p->name_strobj);
         if (descr == NULL) {
             if (ptr == (void**)&type->tp_iternext) {
-                specific = _PyObject_NextNotImplemented;
+                specific = (void *)_PyObject_NextNotImplemented;
             }
             continue;
         }
@@ -6035,7 +6039,7 @@
             /* We specifically allow __hash__ to be set to None
                to prevent inheritance of the default
                implementation from object.__hash__ */
-            specific = PyObject_HashNotImplemented;
+            specific = (void *)PyObject_HashNotImplemented;
         }
         else {
             use_generic = 1;
@@ -6250,7 +6254,7 @@
             continue;
         if (PyDict_GetItem(dict, p->name_strobj))
             continue;
-        if (*ptr == PyObject_HashNotImplemented) {
+        if (*ptr == (void *)PyObject_HashNotImplemented) {
             /* Classes may prevent the inheritance of the tp_hash
                slot by storing PyObject_HashNotImplemented in it. Make it
                visible as a None value for the __hash__ attribute. */
@@ -6502,18 +6506,18 @@
         PyCodeObject *co = f->f_code;
         Py_ssize_t i, n;
         if (co == NULL) {
-            PyErr_SetString(PyExc_SystemError,
+            PyErr_SetString(PyExc_RuntimeError,
                             "super(): no code object");
             return -1;
         }
         if (co->co_argcount == 0) {
-            PyErr_SetString(PyExc_SystemError,
+            PyErr_SetString(PyExc_RuntimeError,
                             "super(): no arguments");
             return -1;
         }
         obj = f->f_localsplus[0];
         if (obj == NULL) {
-            PyErr_SetString(PyExc_SystemError,
+            PyErr_SetString(PyExc_RuntimeError,
                             "super(): arg[0] deleted");
             return -1;
         }
@@ -6532,18 +6536,18 @@
                     PyTuple_GET_SIZE(co->co_cellvars) + i;
                 PyObject *cell = f->f_localsplus[index];
                 if (cell == NULL || !PyCell_Check(cell)) {
-                    PyErr_SetString(PyExc_SystemError,
+                    PyErr_SetString(PyExc_RuntimeError,
                       "super(): bad __class__ cell");
                     return -1;
                 }
                 type = (PyTypeObject *) PyCell_GET(cell);
                 if (type == NULL) {
-                    PyErr_SetString(PyExc_SystemError,
+                    PyErr_SetString(PyExc_RuntimeError,
                       "super(): empty __class__ cell");
                     return -1;
                 }
                 if (!PyType_Check(type)) {
-                    PyErr_Format(PyExc_SystemError,
+                    PyErr_Format(PyExc_RuntimeError,
                       "super(): __class__ is not a type (%s)",
                       Py_TYPE(type)->tp_name);
                     return -1;
@@ -6552,7 +6556,7 @@
             }
         }
         if (type == NULL) {
-            PyErr_SetString(PyExc_SystemError,
+            PyErr_SetString(PyExc_RuntimeError,
                             "super(): __class__ cell not found");
             return -1;
         }
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -159,7 +159,7 @@
         const from_type *_end = (end);                  \
         Py_ssize_t n = (_end) - (_iter);                \
         const from_type *_unrolled_end =                \
-            _iter + (n & ~ (Py_ssize_t) 3);             \
+            _iter + _Py_SIZE_ROUND_DOWN(n, 4);          \
         while (_iter < (_unrolled_end)) {               \
             _to[0] = (to_type) _iter[0];                \
             _to[1] = (to_type) _iter[1];                \
@@ -4635,9 +4635,6 @@
 #include "stringlib/codecs.h"
 #include "stringlib/undef.h"
 
-/* Mask to check or force alignment of a pointer to C 'long' boundaries */
-#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
-
 /* Mask to quickly check whether a C 'long' contains a
    non-ASCII, UTF8-encoded char. */
 #if (SIZEOF_LONG == 8)
@@ -4652,11 +4649,11 @@
 ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
 {
     const char *p = start;
-    const char *aligned_end = (const char *) ((size_t) end & ~LONG_PTR_MASK);
+    const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
 
 #if SIZEOF_LONG <= SIZEOF_VOID_P
-    assert(!((size_t) dest & LONG_PTR_MASK));
-    if (!((size_t) p & LONG_PTR_MASK)) {
+    assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
+    if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
         /* Fast path, see in STRINGLIB(utf8_decode) for
            an explanation. */
         /* Help register allocation */
@@ -4682,7 +4679,7 @@
     while (p < end) {
         /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
            for an explanation. */
-        if (!((size_t) p & LONG_PTR_MASK)) {
+        if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
             /* Help register allocation */
             register const char *_p = p;
             while (_p < aligned_end) {
@@ -5390,7 +5387,7 @@
         return NULL;
 
     /* output buffer is 2-bytes aligned */
-    assert(((Py_uintptr_t)PyBytes_AS_STRING(v) & 1) == 0);
+    assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
     out = (unsigned short *)PyBytes_AS_STRING(v);
     if (byteorder == 0)
         *out++ = 0xFEFF;
@@ -7528,9 +7525,10 @@
             /* Apply mapping */
             if (PyLong_Check(x)) {
                 long value = PyLong_AS_LONG(x);
-                if (value < 0 || value > 65535) {
-                    PyErr_SetString(PyExc_TypeError,
-                                    "character mapping must be in range(65536)");
+                if (value < 0 || value > MAX_UNICODE) {
+                    PyErr_Format(PyExc_TypeError,
+                                 "character mapping must be in range(0x%lx)",
+                                 (unsigned long)MAX_UNICODE + 1);
                     Py_DECREF(x);
                     goto onError;
                 }
@@ -9145,7 +9143,7 @@
             /* We do not need to compare 0 and len(substring)-1 because
                the if statement above ensured already that they are equal
                when we end up here. */
-            // TODO: honor direction and do a forward or backwards search
+            /* TODO: honor direction and do a forward or backwards search */
             for (i = 1; i < end_sub; ++i) {
                 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
                     PyUnicode_READ(kind_sub, data_sub, i))
@@ -13462,8 +13460,7 @@
         arglen = -1;
         argidx = -2;
     }
-    if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
-        !PyUnicode_Check(args))
+    if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
         dict = args;
 
     while (--fmtcnt >= 0) {
diff --git a/Parser/node.c b/Parser/node.c
--- a/Parser/node.c
+++ b/Parser/node.c
@@ -71,7 +71,7 @@
  * capacity.  The code is tricky to avoid that.
  */
 #define XXXROUNDUP(n) ((n) <= 1 ? (n) :                 \
-               (n) <= 128 ? (((n) + 3) & ~3) :          \
+               (n) <= 128 ? _Py_SIZE_ROUND_UP((n), 4) : \
                fancy_roundup(n))
 
 
diff --git a/Python/ast.c b/Python/ast.c
--- a/Python/ast.c
+++ b/Python/ast.c
@@ -545,9 +545,9 @@
 }
 
 static identifier
-new_identifier(const char* n, struct compiling *c)
+new_identifier(const char *n, struct compiling *c)
 {
-    PyObject* id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
+    PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
     if (!id)
         return NULL;
     /* PyUnicode_DecodeUTF8 should always return a ready string. */
@@ -574,79 +574,43 @@
 
 #define NEW_IDENTIFIER(n) new_identifier(STR(n), c)
 
-/* This routine provides an invalid object for the syntax error.
-   The outermost routine must unpack this error and create the
-   proper object.  We do this so that we don't have to pass
-   the filename to everything function.
-
-   XXX Maybe we should just pass the filename...
-*/
-
 static int
-ast_error(const node *n, const char *errstr)
+ast_error(struct compiling *c, const node *n, const char *errmsg)
 {
-    PyObject *u = Py_BuildValue("zii", errstr, LINENO(n), n->n_col_offset);
-    if (!u)
-        return 0;
-    PyErr_SetObject(PyExc_SyntaxError, u);
-    Py_DECREF(u);
-    return 0;
-}
-
-static void
-ast_error_finish(const char *filename)
-{
-    PyObject *type, *value, *tback, *errstr, *offset, *loc, *tmp;
+    PyObject *value, *errstr, *loc, *tmp;
     PyObject *filename_obj;
-    long lineno;
-
-    assert(PyErr_Occurred());
-    if (!PyErr_ExceptionMatches(PyExc_SyntaxError))
-        return;
-
-    PyErr_Fetch(&type, &value, &tback);
-    errstr = PyTuple_GetItem(value, 0);
-    if (!errstr)
-        return;
-    Py_INCREF(errstr);
-    lineno = PyLong_AsLong(PyTuple_GetItem(value, 1));
-    if (lineno == -1) {
-        Py_DECREF(errstr);
-        return;
-    }
-    offset = PyTuple_GetItem(value, 2);
-    if (!offset) {
-        Py_DECREF(errstr);
-        return;
-    }
-    Py_DECREF(value);
-
-    loc = PyErr_ProgramText(filename, lineno);
+
+    loc = PyErr_ProgramText(c->c_filename, LINENO(n));
     if (!loc) {
         Py_INCREF(Py_None);
         loc = Py_None;
     }
-    if (filename != NULL)
-        filename_obj = PyUnicode_DecodeFSDefault(filename);
-    else {
+    if (c->c_filename) {
+        filename_obj = PyUnicode_DecodeFSDefault(c->c_filename);
+        if (!filename_obj) {
+            Py_DECREF(loc);
+            return 0;
+        }
+    } else {
         Py_INCREF(Py_None);
         filename_obj = Py_None;
     }
-    if (filename_obj != NULL)
-        tmp = Py_BuildValue("(NlOO)", filename_obj, lineno, offset, loc);
-    else
-        tmp = NULL;
-    Py_DECREF(loc);
-    if (!tmp) {
-        Py_DECREF(errstr);
-        return;
+    tmp = Py_BuildValue("(NiiN)", filename_obj, LINENO(n), n->n_col_offset, loc);
+    if (!tmp)
+        return 0;
+    errstr = PyUnicode_FromString(errmsg);
+    if (!errstr) {
+        Py_DECREF(tmp);
+        return 0;
     }
     value = PyTuple_Pack(2, errstr, tmp);
     Py_DECREF(errstr);
     Py_DECREF(tmp);
-    if (!value)
-        return;
-    PyErr_Restore(type, value, tback);
+    if (value) {
+        PyErr_SetObject(PyExc_SyntaxError, value);
+        Py_DECREF(value);
+    }
+    return 0;
 }
 
 /* num_stmts() returns number of contained statements.
@@ -724,11 +688,14 @@
     struct compiling c;
     mod_ty res = NULL;
 
+    c.c_arena = arena;
+    c.c_filename = filename;
+    c.c_normalize = c.c_normalize_args = NULL;
     if (flags && flags->cf_flags & PyCF_SOURCE_IS_UTF8) {
         c.c_encoding = "utf-8";
         if (TYPE(n) == encoding_decl) {
 #if 0
-            ast_error(n, "encoding declaration in Unicode string");
+            ast_error(c, n, "encoding declaration in Unicode string");
             goto out;
 #endif
             n = CHILD(n, 0);
@@ -740,9 +707,6 @@
         /* PEP 3120 */
         c.c_encoding = "utf-8";
     }
-    c.c_arena = arena;
-    c.c_filename = filename;
-    c.c_normalize = c.c_normalize_args = NULL;
 
     k = 0;
     switch (TYPE(n)) {
@@ -835,8 +799,6 @@
         PyTuple_SET_ITEM(c.c_normalize_args, 1, NULL);
         Py_DECREF(c.c_normalize_args);
     }
-    if (!res)
-        ast_error_finish(filename);
     return res;
 }
 
@@ -882,18 +844,18 @@
 };
 
 static int
-forbidden_name(identifier name, const node *n, int full_checks)
+forbidden_name(struct compiling *c, identifier name, const node *n, int full_checks)
 {
     assert(PyUnicode_Check(name));
     if (PyUnicode_CompareWithASCIIString(name, "__debug__") == 0) {
-        ast_error(n, "assignment to keyword");
+        ast_error(c, n, "assignment to keyword");
         return 1;
     }
     if (full_checks) {
         const char **p;
         for (p = FORBIDDEN; *p; p++) {
             if (PyUnicode_CompareWithASCIIString(name, *p) == 0) {
-                ast_error(n, "assignment to keyword");
+                ast_error(c, n, "assignment to keyword");
                 return 1;
             }
         }
@@ -929,7 +891,7 @@
     switch (e->kind) {
         case Attribute_kind:
             e->v.Attribute.ctx = ctx;
-            if (ctx == Store && forbidden_name(e->v.Attribute.attr, n, 1))
+            if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1))
                 return 0;
             break;
         case Subscript_kind:
@@ -942,7 +904,7 @@
             break;
         case Name_kind:
             if (ctx == Store) {
-                if (forbidden_name(e->v.Name.id, n, 1))
+                if (forbidden_name(c, e->v.Name.id, n, 1))
                     return 0; /* forbidden_name() calls ast_error() */
             }
             e->v.Name.ctx = ctx;
@@ -1016,7 +978,7 @@
                       "can't %s %s",
                       ctx == Store ? "assign to" : "delete",
                       expr_name);
-        return ast_error(n, buf);
+        return ast_error(c, n, buf);
     }
 
     /* If the LHS is a list or tuple, we need to set the assignment
@@ -1164,7 +1126,7 @@
     name = NEW_IDENTIFIER(ch);
     if (!name)
         return NULL;
-    if (forbidden_name(name, ch, 0))
+    if (forbidden_name(c, name, ch, 0))
         return NULL;
 
     if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) {
@@ -1194,7 +1156,7 @@
     int j = 0; /* index for kwdefaults and kwonlyargs */
 
     if (kwonlyargs == NULL) {
-        ast_error(CHILD(n, start), "named arguments must follow bare *");
+        ast_error(c, CHILD(n, start), "named arguments must follow bare *");
         return -1;
     }
     assert(kwdefaults != NULL);
@@ -1226,7 +1188,7 @@
                 argname = NEW_IDENTIFIER(ch);
                 if (!argname)
                     goto error;
-                if (forbidden_name(argname, ch, 0))
+                if (forbidden_name(c, argname, ch, 0))
                     goto error;
                 arg = arg(argname, annotation, c->c_arena);
                 if (!arg)
@@ -1237,7 +1199,7 @@
             case DOUBLESTAR:
                 return i;
             default:
-                ast_error(ch, "unexpected node");
+                ast_error(c, ch, "unexpected node");
                 goto error;
         }
     }
@@ -1329,7 +1291,7 @@
         return NULL;
 
     if (nposargs + nkwonlyargs > 255) {
-        ast_error(n, "more than 255 arguments");
+        ast_error(c, n, "more than 255 arguments");
         return NULL;
     }
 
@@ -1357,7 +1319,7 @@
                     found_default = 1;
                 }
                 else if (found_default) {
-                    ast_error(n,
+                    ast_error(c, n,
                              "non-default argument follows default argument");
                     return NULL;
                 }
@@ -1369,7 +1331,7 @@
                 break;
             case STAR:
                 if (i+1 >= NCH(n)) {
-                    ast_error(CHILD(n, i),
+                    ast_error(c, CHILD(n, i),
                         "named arguments must follow bare *");
                     return NULL;
                 }
@@ -1386,7 +1348,7 @@
                     vararg = NEW_IDENTIFIER(CHILD(ch, 0));
                     if (!vararg)
                         return NULL;
-                    if (forbidden_name(vararg, CHILD(ch, 0), 0))
+                    if (forbidden_name(c, vararg, CHILD(ch, 0), 0))
                         return NULL;
                     if (NCH(ch) > 1) {
                         /* there is an annotation on the vararg */
@@ -1417,7 +1379,7 @@
                     if (!kwargannotation)
                         return NULL;
                 }
-                if (forbidden_name(kwarg, CHILD(ch, 0), 0))
+                if (forbidden_name(c, kwarg, CHILD(ch, 0), 0))
                     return NULL;
                 i += 3;
                 break;
@@ -1536,7 +1498,7 @@
     name = NEW_IDENTIFIER(CHILD(n, name_i));
     if (!name)
         return NULL;
-    if (forbidden_name(name, CHILD(n, name_i), 0))
+    if (forbidden_name(c, name, CHILD(n, name_i), 0))
         return NULL;
     args = ast_for_arguments(c, CHILD(n, name_i + 1));
     if (!args)
@@ -1877,10 +1839,10 @@
                     char buf[128];
                     s = _PyUnicode_AsString(errstr);
                     PyOS_snprintf(buf, sizeof(buf), "(unicode error) %s", s);
-                    ast_error(n, buf);
+                    ast_error(c, n, buf);
                     Py_DECREF(errstr);
                 } else {
-                    ast_error(n, "(unicode error) unknown error");
+                    ast_error(c, n, "(unicode error) unknown error");
                 }
                 Py_DECREF(type);
                 Py_DECREF(value);
@@ -2465,14 +2427,14 @@
         }
     }
     if (ngens > 1 || (ngens && (nargs || nkeywords))) {
-        ast_error(n, "Generator expression must be parenthesized "
+        ast_error(c, n, "Generator expression must be parenthesized "
                   "if not sole argument");
         return NULL;
     }
 
     if (nargs + nkeywords + ngens > 255) {
-      ast_error(n, "more than 255 arguments");
-      return NULL;
+        ast_error(c, n, "more than 255 arguments");
+        return NULL;
     }
 
     args = asdl_seq_new(nargs + ngens, c->c_arena);
@@ -2489,12 +2451,12 @@
             expr_ty e;
             if (NCH(ch) == 1) {
                 if (nkeywords) {
-                    ast_error(CHILD(ch, 0),
+                    ast_error(c, CHILD(ch, 0),
                               "non-keyword arg after keyword arg");
                     return NULL;
                 }
                 if (vararg) {
-                    ast_error(CHILD(ch, 0),
+                    ast_error(c, CHILD(ch, 0),
                               "only named arguments may follow *expression");
                     return NULL;
                 }
@@ -2524,19 +2486,19 @@
                  * then is very confusing.
                  */
                 if (e->kind == Lambda_kind) {
-                    ast_error(CHILD(ch, 0), "lambda cannot contain assignment");
+                    ast_error(c, CHILD(ch, 0), "lambda cannot contain assignment");
                     return NULL;
                 } else if (e->kind != Name_kind) {
-                    ast_error(CHILD(ch, 0), "keyword can't be an expression");
+                    ast_error(c, CHILD(ch, 0), "keyword can't be an expression");
                     return NULL;
-                } else if (forbidden_name(e->v.Name.id, ch, 1)) {
+                } else if (forbidden_name(c, e->v.Name.id, ch, 1)) {
                     return NULL;
                 }
                 key = e->v.Name.id;
                 for (k = 0; k < nkeywords; k++) {
                     tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg;
                     if (!PyUnicode_Compare(tmp, key)) {
-                        ast_error(CHILD(ch, 0), "keyword argument repeated");
+                        ast_error(c, CHILD(ch, 0), "keyword argument repeated");
                         return NULL;
                     }
                 }
@@ -2629,7 +2591,7 @@
             case Subscript_kind:
                 break;
             default:
-                ast_error(ch, "illegal expression for augmented assignment");
+                ast_error(c, ch, "illegal expression for augmented assignment");
                 return NULL;
         }
 
@@ -2662,7 +2624,7 @@
             expr_ty e;
             node *ch = CHILD(n, i);
             if (TYPE(ch) == yield_expr) {
-                ast_error(ch, "assignment to yield expression not possible");
+                ast_error(c, ch, "assignment to yield expression not possible");
                 return NULL;
             }
             e = ast_for_testlist(c, ch);
@@ -2809,11 +2771,11 @@
                 str = NEW_IDENTIFIER(str_node);
                 if (!str)
                     return NULL;
-                if (store && forbidden_name(str, str_node, 0))
+                if (store && forbidden_name(c, str, str_node, 0))
                     return NULL;
             }
             else {
-                if (forbidden_name(name, name_node, 0))
+                if (forbidden_name(c, name, name_node, 0))
                     return NULL;
             }
             return alias(name, str, c->c_arena);
@@ -2832,7 +2794,7 @@
                 a->asname = NEW_IDENTIFIER(asname_node);
                 if (!a->asname)
                     return NULL;
-                if (forbidden_name(a->asname, asname_node, 0))
+                if (forbidden_name(c, a->asname, asname_node, 0))
                     return NULL;
                 return a;
             }
@@ -2843,7 +2805,7 @@
                 name = NEW_IDENTIFIER(name_node);
                 if (!name)
                     return NULL;
-                if (store && forbidden_name(name, name_node, 0))
+                if (store && forbidden_name(c, name, name_node, 0))
                     return NULL;
                 return alias(name, NULL, c->c_arena);
             }
@@ -2972,13 +2934,13 @@
             n = CHILD(n, idx);
             n_children = NCH(n);
             if (n_children % 2 == 0) {
-                ast_error(n, "trailing comma not allowed without"
+                ast_error(c, n, "trailing comma not allowed without"
                              " surrounding parentheses");
                 return NULL;
             }
             break;
         default:
-            ast_error(n, "Unexpected node-type in from-import");
+            ast_error(c, n, "Unexpected node-type in from-import");
             return NULL;
         }
 
@@ -3384,7 +3346,7 @@
         identifier e = NEW_IDENTIFIER(CHILD(exc, 3));
         if (!e)
             return NULL;
-        if (forbidden_name(e, CHILD(exc, 3), 0))
+        if (forbidden_name(c, e, CHILD(exc, 3), 0))
             return NULL;
         expression = ast_for_expr(c, CHILD(exc, 1));
         if (!expression)
@@ -3443,7 +3405,7 @@
         }
     }
     else if (TYPE(CHILD(n, nch - 3)) != except_clause) {
-        ast_error(n, "malformed 'try' statement");
+        ast_error(c, n, "malformed 'try' statement");
         return NULL;
     }
 
@@ -3535,7 +3497,7 @@
         classname = NEW_IDENTIFIER(CHILD(n, 1));
         if (!classname)
             return NULL;
-        if (forbidden_name(classname, CHILD(n, 3), 0))
+        if (forbidden_name(c, classname, CHILD(n, 3), 0))
             return NULL;
         return ClassDef(classname, NULL, NULL, NULL, NULL, s, decorator_seq,
                         LINENO(n), n->n_col_offset, c->c_arena);
@@ -3548,7 +3510,7 @@
         classname = NEW_IDENTIFIER(CHILD(n, 1));
         if (!classname)
             return NULL;
-        if (forbidden_name(classname, CHILD(n, 3), 0))
+        if (forbidden_name(c, classname, CHILD(n, 3), 0))
             return NULL;
         return ClassDef(classname, NULL, NULL, NULL, NULL, s, decorator_seq,
                         LINENO(n), n->n_col_offset, c->c_arena);
@@ -3573,7 +3535,7 @@
     classname = NEW_IDENTIFIER(CHILD(n, 1));
     if (!classname)
         return NULL;
-    if (forbidden_name(classname, CHILD(n, 1), 0))
+    if (forbidden_name(c, classname, CHILD(n, 1), 0))
         return NULL;
 
     return ClassDef(classname, call->v.Call.args, call->v.Call.keywords,
@@ -3832,10 +3794,10 @@
     }
     if (*bytesmode) {
         /* Disallow non-ascii characters (but not escapes) */
-        const char *c;
-        for (c = s; *c; c++) {
-            if (Py_CHARMASK(*c) >= 0x80) {
-                ast_error(n, "bytes can only contain ASCII "
+        const char *ch;
+        for (ch = s; *ch; ch++) {
+            if (Py_CHARMASK(*ch) >= 0x80) {
+                ast_error(c, n, "bytes can only contain ASCII "
                           "literal characters.");
                 return NULL;
             }
@@ -3883,7 +3845,8 @@
             if (s == NULL)
                 goto onError;
             if (*bytesmode != subbm) {
-                ast_error(n, "cannot mix bytes and nonbytes literals");
+                ast_error(c, n, "cannot mix bytes and nonbytes literals");
+                Py_DECREF(s);
                 goto onError;
             }
             if (PyBytes_Check(v) && PyBytes_Check(s)) {
diff --git a/Python/formatter_unicode.c b/Python/formatter_unicode.c
--- a/Python/formatter_unicode.c
+++ b/Python/formatter_unicode.c
@@ -1099,7 +1099,7 @@
                          &locale, 0);
 
 done:
-    Py_DECREF(unicode_tmp);
+    Py_XDECREF(unicode_tmp);
     free_locale_info(&locale);
     return result;
 }
diff --git a/Python/getargs.c b/Python/getargs.c
--- a/Python/getargs.c
+++ b/Python/getargs.c
@@ -1742,6 +1742,7 @@
     assert(min >= 0);
     assert(min <= max);
     if (!PyTuple_Check(args)) {
+        va_end(vargs);
         PyErr_SetString(PyExc_SystemError,
             "PyArg_UnpackTuple() argument list is not a tuple");
         return 0;
diff --git a/Python/importlib.h b/Python/importlib.h
--- a/Python/importlib.h
+++ b/Python/importlib.h
[stripped]
diff --git a/Python/pyarena.c b/Python/pyarena.c
--- a/Python/pyarena.c
+++ b/Python/pyarena.c
@@ -12,8 +12,6 @@
 
 #define DEFAULT_BLOCK_SIZE 8192
 #define ALIGNMENT               8
-#define ALIGNMENT_MASK          (ALIGNMENT - 1)
-#define ROUNDUP(x)              (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
 
 typedef struct _block {
     /* Total number of bytes owned by this block available to pass out.
@@ -85,8 +83,8 @@
     b->ab_size = size;
     b->ab_mem = (void *)(b + 1);
     b->ab_next = NULL;
-    b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) -
-      (Py_uintptr_t)(b->ab_mem);
+    b->ab_offset = (char *)_Py_ALIGN_UP(b->ab_mem, ALIGNMENT) -
+            (char *)(b->ab_mem);
     return b;
 }
 
@@ -104,7 +102,7 @@
 {
     void *p;
     assert(b);
-    size = ROUNDUP(size);
+    size = _Py_SIZE_ROUND_UP(size, ALIGNMENT);
     if (b->ab_offset + size > b->ab_size) {
         /* If we need to allocate more memory than will fit in
            the default block, allocate a one-off block that is
diff --git a/Python/structmember.c b/Python/structmember.c
--- a/Python/structmember.c
+++ b/Python/structmember.c
@@ -254,12 +254,8 @@
         char *string;
         Py_ssize_t len;
 
-        if (!PyUnicode_Check(v)) {
-            PyErr_BadArgument();
-            return -1;
-        }
         string = _PyUnicode_AsStringAndSize(v, &len);
-        if (len != 1) {
+        if (string == NULL || len != 1) {
             PyErr_BadArgument();
             return -1;
         }
diff --git a/Python/symtable.c b/Python/symtable.c
--- a/Python/symtable.c
+++ b/Python/symtable.c
@@ -24,16 +24,18 @@
         void *key, int lineno, int col_offset)
 {
     PySTEntryObject *ste = NULL;
-    PyObject *k;
+    PyObject *k = NULL;
 
     k = PyLong_FromVoidPtr(key);
     if (k == NULL)
         goto fail;
     ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
-    if (ste == NULL)
+    if (ste == NULL) {
+        Py_DECREF(k);
         goto fail;
+    }
     ste->ste_table = st;
-    ste->ste_id = k;
+    ste->ste_id = k; /* ste owns reference to k */
 
     ste->ste_name = name;
     Py_INCREF(name);
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -1788,6 +1788,8 @@
                 mkpath(ffi_builddir)
                 config_args = [arg for arg in sysconfig.get_config_var("CONFIG_ARGS").split()
                                if (('--host=' in arg) or ('--build=' in arg))]
+                if not self.verbose:
+                    config_args.append("-q")
 
                 # Pass empty CFLAGS because we'll just append the resulting
                 # CFLAGS to Python's; -g or -O2 is to be avoided.

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list