summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorBenjamin Peterson <benjamin@python.org>2012-09-29 18:14:19 (GMT)
committerBenjamin Peterson <benjamin@python.org>2012-09-29 18:14:19 (GMT)
commit14fb44e1bab9db128770f1d91d244916a669e7c3 (patch)
tree278d9ccc8f819b05f8114c3154087c70b88ed69c /Doc
parent1764c80925795b6f059e961c5a352c5ece5a7fff (diff)
parent99a247fd01c1cd780c0c3ee1116657627f1ee744 (diff)
downloadcpython-14fb44e1bab9db128770f1d91d244916a669e7c3.zip
cpython-14fb44e1bab9db128770f1d91d244916a669e7c3.tar.gz
cpython-14fb44e1bab9db128770f1d91d244916a669e7c3.tar.bz2
merge mostly from default
Diffstat (limited to 'Doc')
-rw-r--r--Doc/ACKS.txt239
-rw-r--r--Doc/about.rst9
-rw-r--r--Doc/c-api/import.rst2
-rw-r--r--Doc/extending/newtypes.rst6
-rw-r--r--Doc/faq/windows.rst10
-rw-r--r--Doc/howto/regex.rst26
-rw-r--r--Doc/howto/unicode.rst27
-rw-r--r--Doc/library/argparse.rst23
-rw-r--r--Doc/library/collections.rst2
-rw-r--r--Doc/library/configparser.rst19
-rw-r--r--Doc/library/crypt.rst10
-rw-r--r--Doc/library/crypto.rst1
-rw-r--r--Doc/library/csv.rst28
-rw-r--r--Doc/library/curses.rst46
-rw-r--r--Doc/library/doctest.rst12
-rw-r--r--Doc/library/functions.rst77
-rw-r--r--Doc/library/http.client.rst8
-rw-r--r--Doc/library/inspect.rst4
-rw-r--r--Doc/library/itertools.rst3
-rw-r--r--Doc/library/json.rst18
-rw-r--r--Doc/library/lzma.rst12
-rw-r--r--Doc/library/mailbox.rst19
-rw-r--r--Doc/library/multiprocessing.rst5
-rw-r--r--Doc/library/nntplib.rst6
-rw-r--r--Doc/library/optparse.rst17
-rw-r--r--Doc/library/os.rst5
-rw-r--r--Doc/library/ossaudiodev.rst3
-rw-r--r--Doc/library/pyexpat.rst2
-rw-r--r--Doc/library/random.rst11
-rw-r--r--Doc/library/site.rst2
-rw-r--r--Doc/library/smtpd.rst13
-rw-r--r--Doc/library/socket.rst3
-rw-r--r--Doc/library/stdtypes.rst11
-rw-r--r--Doc/library/subprocess.rst14
-rw-r--r--Doc/library/syslog.rst3
-rw-r--r--Doc/library/textwrap.rst19
-rw-r--r--Doc/library/threading.rst6
-rw-r--r--Doc/library/timeit.rst20
-rw-r--r--Doc/library/tkinter.tix.rst2
-rw-r--r--Doc/library/types.rst2
-rw-r--r--Doc/library/unittest.mock.rst4
-rw-r--r--Doc/library/unittest.rst2
-rw-r--r--Doc/library/urllib.parse.rst5
-rw-r--r--Doc/license.rst6
-rw-r--r--Doc/reference/compound_stmts.rst10
-rw-r--r--Doc/reference/datamodel.rst26
-rw-r--r--Doc/tools/sphinxext/susp-ignored.csv3
-rw-r--r--Doc/tutorial/datastructures.rst2
-rw-r--r--Doc/tutorial/interpreter.rst8
-rw-r--r--Doc/tutorial/introduction.rst3
-rw-r--r--Doc/tutorial/stdlib.rst2
-rw-r--r--Doc/tutorial/stdlib2.rst8
-rw-r--r--Doc/whatsnew/3.3.rst114
53 files changed, 456 insertions, 482 deletions
diff --git a/Doc/ACKS.txt b/Doc/ACKS.txt
deleted file mode 100644
index 5636e05..0000000
--- 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@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
index 2c229e6..d316f09 100644
--- a/Doc/about.rst
+++ b/Doc/about.rst
@@ -29,8 +29,13 @@ Many thanks go to:
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
index c3c8f42..270152e 100644
--- a/Doc/c-api/import.rst
+++ b/Doc/c-api/import.rst
@@ -76,7 +76,7 @@ Importing Modules
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
index b90d35c..376d09a 100644
--- a/Doc/extending/newtypes.rst
+++ b/Doc/extending/newtypes.rst
@@ -1277,9 +1277,9 @@ that the slots are present and should be checked by the interpreter. (The flag
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
index 68a1b5c..84e3ff4 100644
--- a/Doc/faq/windows.rst
+++ b/Doc/faq/windows.rst
@@ -464,13 +464,13 @@ to console subprocesses which are designed to handle those signals. See
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 @@ It helps to think of share points as being like drive letters. Example::
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
index 3ac03ca..3beca38 100644
--- a/Doc/howto/regex.rst
+++ b/Doc/howto/regex.rst
@@ -260,7 +260,7 @@ performing string substitutions. ::
>>> 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 @@ Python interpreter, import the :mod:`re` module, and compile a RE::
>>> 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 @@ case, :meth:`match` will return a :class:`MatchObject`, so you should store the
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 @@ case. ::
>>> 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 @@ result. The :meth:`finditer` method returns a sequence of :class:`MatchObject`
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 @@ the RE string added as the first argument, and still return either ``None`` or a
>>> 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 @@ given location, they can obviously be matched an infinite number of times.
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 @@ given location, they can obviously be matched an infinite number of times.
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 @@ given location, they can obviously be matched an infinite number of times.
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 @@ given location, they can obviously be matched an infinite number of times.
>>> 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 @@ compute the desired replacement string and return it.
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
index 045fd33..f9eeae4 100644
--- a/Doc/howto/unicode.rst
+++ b/Doc/howto/unicode.rst
@@ -257,13 +257,13 @@ converted according to the encoding's rules. Legal values for this argument are
'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 @@ XML's character references. The following example shows the different results::
>>> 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 @@ point. The ``\U`` escape sequence is similar, but expects eight hex digits,
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
index 4203e8b..9f6a1ea 100644
--- a/Doc/library/argparse.rst
+++ b/Doc/library/argparse.rst
@@ -130,9 +130,12 @@ command-line arguments from :data:`sys.argv`.
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 @@ was not present at the command line::
>>> 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 @@ types and functions can be used directly as the value of the ``type`` argument::
>>> 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
index 4c5b649..dc76ea5 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -1012,7 +1012,7 @@ are deleted. But when new keys are added, the keys are appended
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
index afceb8d..c202cf2 100644
--- a/Doc/library/configparser.rst
+++ b/Doc/library/configparser.rst
@@ -1007,7 +1007,7 @@ ConfigParser Objects
.. 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 @@ ConfigParser Objects
(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 @@ ConfigParser Objects
*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 @@ ConfigParser Objects
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
index 1ba2ed3..b4c90cd 100644
--- a/Doc/library/crypt.rst
+++ b/Doc/library/crypt.rst
@@ -121,11 +121,14 @@ The :mod:`crypt` module defines the following functions:
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 @@ A simple example illustrating typical use::
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 @@ To generate a hash of a password using the strongest available method and
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
index a233561..469ede49 100644
--- a/Doc/library/crypto.rst
+++ b/Doc/library/crypto.rst
@@ -8,6 +8,7 @@ Cryptographic Services
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
index 5d8368b..4f19cee 100644
--- a/Doc/library/csv.rst
+++ b/Doc/library/csv.rst
@@ -71,9 +71,10 @@ The :mod:`csv` module defines the following functions:
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 @@ The :mod:`csv` module defines the following functions:
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 @@ The :mod:`csv` module defines the following classes:
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
index c424148..9e5cb55 100644
--- a/Doc/library/curses.rst
+++ b/Doc/library/curses.rst
@@ -377,7 +377,8 @@ The module :mod:`curses` defines the following functions:
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 @@ Window objects, as returned by :func:`initscr` and :func:`newwin` above, have
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 @@ the following methods and attributes:
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 @@ the following methods and attributes:
*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 @@ the following methods and attributes:
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 @@ the following methods and attributes:
.. 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 @@ the following methods and attributes:
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 following methods and attributes:
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 @@ the following methods and attributes:
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 following methods and attributes:
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 @@ the following methods and attributes:
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 @@ the following methods and attributes:
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 @@ the following methods and attributes:
: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
index cdd6c26..ed53f06 100644
--- a/Doc/library/doctest.rst
+++ b/Doc/library/doctest.rst
@@ -338,7 +338,7 @@ The fine print:
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 @@ from text files and modules with doctests:
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
index 61e4932..c2b3b21 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -629,14 +629,19 @@ are always available. They are listed here in alphabetical order.
to provide elaborate line editing and history features.
-.. function:: int([number | string[, base]])
-
- 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
+.. function:: int(x=0)
+ int(x, base=10)
+
+ 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 @@ are always available. They are listed here in alphabetical order.
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 @@ are always available. They are listed here in alphabetical order.
:ref:`typememoryview` for more information.
-.. function:: min(iterable[, args...], *[, key])
+.. function:: min(iterable, *[, key])
+ min(arg1, arg2, *args[, key])
+
+ Return the smallest item in an iterable or the smallest of two or more
+ arguments.
- 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.
+ 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 @@ are always available. They are listed here in alphabetical order.
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 @@ are always available. They are listed here in alphabetical order.
.. _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 @@ are always available. They are listed here in alphabetical order.
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 @@ are always available. They are listed here in alphabetical order.
``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
index efb4c41..5599dac 100644
--- a/Doc/library/http.client.rst
+++ b/Doc/library/http.client.rst
@@ -27,7 +27,8 @@ HTTPS protocols. It is normally not used directly --- the module
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 @@ The module provides the following classes:
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
index 83b7702..4050ab3 100644
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -471,7 +471,7 @@ function.
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 @@ function.
... 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
index da3e690..1eb554a 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -401,7 +401,8 @@ loops that truncate the stream.
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
index 0229ab5..95f120c 100644
--- a/Doc/library/json.rst
+++ b/Doc/library/json.rst
@@ -146,9 +146,12 @@ Basic Usage
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 @@ Encoders and Decoders
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
index 402fae2..f09fa08 100644
--- a/Doc/library/lzma.rst
+++ b/Doc/library/lzma.rst
@@ -335,15 +335,15 @@ Examples
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 @@ Writing compressed data to an already-open file::
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 @@ Creating a compressed file using a custom filter chain::
{"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
index 8623630..0f6aba1 100644
--- 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 @@ Maildir, mbox, MH, Babyl, and MMDF.
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 @@ Maildir, mbox, MH, Babyl, and MMDF.
: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 @@ Maildir, mbox, MH, Babyl, and MMDF.
.. 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 @@ When an :class:`MHMessage` instance is created based upon a
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
index 33a3511..616b7cd 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -295,7 +295,8 @@ The :mod:`multiprocessing` package mostly replicates the API of the
: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 @@ process::
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
index 62da72c..87a50b0 100644
--- a/Doc/library/nntplib.rst
+++ b/Doc/library/nntplib.rst
@@ -487,10 +487,10 @@ The following are optional NNTP extensions defined in :rfc:`2980`. Some of
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
index add582e..6a03edf 100644
--- a/Doc/library/optparse.rst
+++ b/Doc/library/optparse.rst
@@ -273,7 +273,8 @@ You're free to define as many short option strings and as many long option
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 @@ long option strings, but you must specify at least one overall option string.
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 @@ must specify for any option using that action.
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
index aec8073..5f149cb 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -1855,9 +1855,8 @@ features:
: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
index 9e5bec9..3002700 100644
--- a/Doc/library/ossaudiodev.rst
+++ b/Doc/library/ossaudiodev.rst
@@ -67,7 +67,8 @@ the standard audio interface for Linux and recent versions of FreeBSD.
``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
index a648cfa..861546c 100644
--- a/Doc/library/pyexpat.rst
+++ b/Doc/library/pyexpat.rst
@@ -402,7 +402,7 @@ otherwise stated.
.. 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
index 23dbd1f..55c9d70 100644
--- a/Doc/library/random.rst
+++ b/Doc/library/random.rst
@@ -52,20 +52,20 @@ from sources provided by the operating system.
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 @@ Bookkeeping functions:
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
index 3bf8a99..36b80c3 100644
--- a/Doc/library/site.rst
+++ b/Doc/library/site.rst
@@ -33,7 +33,7 @@ It starts by constructing up to four directories from a head and a tail part.
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
index 6dd477a..2ca71ff 100644
--- a/Doc/library/smtpd.rst
+++ b/Doc/library/smtpd.rst
@@ -111,12 +111,13 @@ SMTPChannel Objects
.. 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 @@ SMTPChannel Objects
.. 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 @@ SMTPChannel Objects
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
index 02af9ca..5737b40 100644
--- a/Doc/library/socket.rst
+++ b/Doc/library/socket.rst
@@ -1005,7 +1005,8 @@ correspond to Unix system calls applicable to sockets.
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
index 90f3e54..ed5b3ae 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1235,7 +1235,8 @@ The :class:`range` type represents an immutable sequence of numbers and is
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 @@ copying.
.. 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
index c0fc4d7..042f8f4 100644
--- a/Doc/library/subprocess.rst
+++ b/Doc/library/subprocess.rst
@@ -307,10 +307,14 @@ default values. The arguments that are most commonly needed are:
: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 @@ The following attributes are also available:
.. 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
index aa0f5a1..6e90dc0 100644
--- a/Doc/library/syslog.rst
+++ b/Doc/library/syslog.rst
@@ -17,7 +17,8 @@ library that can speak to a syslog server is available in the
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
index 0ac1cc6..c625254 100644
--- a/Doc/library/textwrap.rst
+++ b/Doc/library/textwrap.rst
@@ -25,6 +25,9 @@ otherwise, you should use an instance of :class:`TextWrapper` for efficiency.
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 @@ in a block of text.
.. 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 @@ in a block of text.
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
index 275a578..7ab739b 100644
--- a/Doc/library/threading.rst
+++ b/Doc/library/threading.rst
@@ -255,8 +255,8 @@ daemonic, and cannot be :meth:`~Thread.join`\ ed. They are never deleted,
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 @@ since it is impossible to detect the termination of alien threads.
*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
index c41e59d..6989b1c 100644
--- a/Doc/library/timeit.rst
+++ b/Doc/library/timeit.rst
@@ -31,13 +31,13 @@ The module defines the following public class:
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 @@ The module defines the following public class:
.. 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 @@ The module defines the following public class:
.. 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 @@ The module also defines three convenience functions:
.. 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 @@ attributes. ::
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
index 289bffd..9de73ad 100644
--- a/Doc/library/tkinter.tix.rst
+++ b/Doc/library/tkinter.tix.rst
@@ -504,7 +504,7 @@ Tix Commands
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
index b60b195..695480f 100644
--- a/Doc/library/types.rst
+++ b/Doc/library/types.rst
@@ -69,7 +69,7 @@ implement a Python interpreter. It deliberately avoids including some of
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
index bed698a..3e50031 100644
--- a/Doc/library/unittest.mock.rst
+++ b/Doc/library/unittest.mock.rst
@@ -276,7 +276,7 @@ the `new_callable` argument to `patch`.
>>> 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 @@ extremely handy: :meth:`~Mock.assert_called_with` and
>>> 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
index 0af9038..2657ebd 100644
--- a/Doc/library/unittest.rst
+++ b/Doc/library/unittest.rst
@@ -1265,7 +1265,7 @@ Test cases
.. 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
index d56fe0e..208cb97 100644
--- a/Doc/library/urllib.parse.rst
+++ b/Doc/library/urllib.parse.rst
@@ -145,8 +145,9 @@ or on combining URL components into a URL string.
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
index b47b7cc..6326ce4 100644
--- a/Doc/license.rst
+++ b/Doc/license.rst
@@ -327,7 +327,7 @@ Mersenne Twister
----------------
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 @@ the verbatim comments from the original code::
Any feedback is very welcome.
- http://www.math.keio.ac.jp/matumoto/emt.html
- email: matumoto@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
index 687ba3e..003224b 100644
--- a/Doc/reference/compound_stmts.rst
+++ b/Doc/reference/compound_stmts.rst
@@ -307,11 +307,11 @@ If :keyword:`finally` is present, it specifies a 'cleanup' handler. The
: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
index b2ce4ff..1c8c190 100644
--- a/Doc/reference/datamodel.rst
+++ b/Doc/reference/datamodel.rst
@@ -1271,22 +1271,22 @@ Basic customization
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
index 7317ca2..138e000 100644
--- a/Doc/tools/sphinxext/susp-ignored.csv
+++ b/Doc/tools/sphinxext/susp-ignored.csv
@@ -124,9 +124,8 @@ library/functions,,:step,a[start:stop:step]
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
index ed81ade..bd661e2 100644
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -186,7 +186,7 @@ We can obtain the same result with::
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
index 8f08cd8..cdc2bf2 100644
--- a/Doc/tutorial/interpreter.rst
+++ b/Doc/tutorial/interpreter.rst
@@ -12,7 +12,9 @@ Invoking the Interpreter
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 @@ prints a welcome message stating its version number and a copyright notice
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
index 43ea7aa..b6d94ac 100644
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -94,8 +94,7 @@ A value can be assigned to several variables simultaneously::
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
index 500ca7f..b5771f6 100644
--- a/Doc/tutorial/stdlib.rst
+++ b/Doc/tutorial/stdlib.rst
@@ -148,7 +148,7 @@ Internet Access
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
index 85c88dc..6a48984 100644
--- a/Doc/tutorial/stdlib2.rst
+++ b/Doc/tutorial/stdlib2.rst
@@ -95,7 +95,7 @@ placeholders unchanged if data is missing::
>>> 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 @@ At its simplest, log messages are sent to a file or to ``sys.stderr``::
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 @@ tree searches::
>>> 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
index 8bb0ded..a84d44d 100644
--- a/Doc/whatsnew/3.3.rst
+++ b/Doc/whatsnew/3.3.rst
@@ -66,6 +66,7 @@ New library modules:
* :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 @@ which considerably simplifies writing decorators and any code that validates
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 @@ Some smaller changes made to the core Python language are:
(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 @@ New Modules
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 @@ collections classes. Aliases for ABCs are still present in the
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 @@ datetime
--------
* 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 @@ API changes
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.
+* 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`)
-(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 @@ side channel attacks on digests through timing analysis.
(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
-------
@@ -1680,6 +1748,16 @@ The new functions `types.new_class` and `types.prepare_class` provide support
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
------
@@ -1813,6 +1891,15 @@ Deprecated Python modules, functions and methods
* :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
@@ -1921,7 +2008,7 @@ Porting Python code
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
@@ -1944,11 +2031,6 @@ Porting Python code
: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.
@@ -1989,9 +2071,9 @@ Porting C code
* :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.