merge mostly from default

This commit is contained in:
Benjamin Peterson 2012-09-29 14:14:19 -04:00
commit 14fb44e1ba
149 changed files with 5371 additions and 4401 deletions

View File

@ -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

View File

@ -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!

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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+')

View File

@ -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

View File

@ -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

View File

@ -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::

View File

@ -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.

View File

@ -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")

View File

@ -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:

View File

@ -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:

View File

@ -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*.

View File

@ -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

View File

@ -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]])
.. 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 @@ 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])
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 @@ 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

View File

@ -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

View File

@ -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

View File

@ -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.

View File

@ -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

View File

@ -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")

View File

@ -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).

View File

@ -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))

View File

@ -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

View File

@ -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`]

View File

@ -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

View File

@ -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

View File

@ -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()

View File

@ -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

View File

@ -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.

View File

@ -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.

View File

@ -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*

View File

@ -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.

View File

@ -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.

View File

@ -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

View File

@ -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)

View File

@ -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.

View File

@ -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"""

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -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::

View File

@ -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):"

1 c-api/arg :ref PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
124 library/functions :stop a[start:stop, i]
125 library/functions :stop a[start:stop:step]
126 library/hotshot :lineno ncalls tottime percall cumtime percall filename:lineno(function)
127 library/http.client 52 :port host:port
128 library/http.cookies ` !#$%&'*+-.^_`|~:
library/httplib :port host:port
129 library/imaplib :MM "DD-Mmm-YYYY HH:MM:SS
130 library/imaplib :SS "DD-Mmm-YYYY HH:MM:SS
131 library/inspect :int >>> def foo(a, *, b:int, **kwargs):

View File

@ -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

View File

@ -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.
>>>

View File

@ -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

View File

@ -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'):

View File

@ -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()

View File

@ -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.

View File

@ -962,7 +962,7 @@ with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.
*/
/* 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;

View File

@ -181,12 +181,9 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
#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( \

View File

@ -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 @@ extern "C" {
| 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. /
---------------------------------------------------------------------
*/
/*

View File

@ -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 */

View File

@ -895,12 +895,18 @@ class BytesIO(BufferedIOBase):
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 @@ class TextIOWrapper(TextIOBase):
return self._buffer
def seekable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return self._seekable
def readable(self):

View File

@ -1725,10 +1725,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
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 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
# 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))

View File

@ -161,7 +161,11 @@ class Calendar(object):
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

View File

@ -2334,7 +2334,12 @@ def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
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()

View File

@ -670,9 +670,9 @@ def _test():
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__':

View File

@ -1825,7 +1825,7 @@ def lwp_cookie_str(cookie):
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 @@ class LWPCookieJar(FileCookieJar):
"""
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

View File

@ -419,8 +419,8 @@ def cache_from_source(path, debug_override=None):
.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 @@ def __import__(name, globals=None, locals=None, fromlist=(), level=0):
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)

View File

@ -274,9 +274,9 @@ def find_root(node):
"""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):

View File

@ -445,7 +445,7 @@ class RefactoringTool(object):
try:
find_root(node)
except AssertionError:
except ValueError:
# this node has been cut off from a
# previous transformation ; skip
continue

View File

@ -208,6 +208,9 @@ class Mailbox:
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 @@ class Mailbox:
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 @@ class Mailbox:
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 @@ class Mailbox:
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 @@ class mbox(_mboxMMDF):
_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):
stops.append(line_pos - len(linesep))
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:
stops.append(line_pos)
if last_was_empty:
stops.append(line_pos - len(linesep))
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()

View File

@ -225,7 +225,6 @@ class Pool(object):
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 @@ class Pool(object):
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 @@ class Pool(object):
'''
Asynchronous version of `starmap()` method.
'''
assert self._state == RUN
return self._map_async(func, iterable, starmapstar, chunksize,
callback, error_callback)
@ -250,7 +247,8 @@ class Pool(object):
'''
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 @@ class Pool(object):
'''
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 @@ class Pool(object):
'''
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 @@ class Pool(object):
'''
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 @@ class Pool(object):
'''
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)

View File

@ -235,6 +235,12 @@ def _run_finalizers(minpriority=None):
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 @@ def is_exiting():
_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 @@ def _exit_function():
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()

View File

@ -324,12 +324,23 @@ class SocketIO(io.RawIOBase):
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.

View File

@ -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

View File

@ -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

View File

@ -1206,6 +1206,9 @@ class MixinStrUnicodeUserStringTest:
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):

View File

@ -680,7 +680,7 @@ def temp_cwd(name='tempcwd', quiet=False, path=None):
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()

View File

@ -1463,6 +1463,22 @@ class TestFileTypeR(TempDirMixin, ParserTestCase):
('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 @@ class TestMessageContentError(TestCase):
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
# ======================

View File

@ -407,6 +407,14 @@ class ASTHelpers_Test(unittest.TestCase):
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),

View File

@ -6,6 +6,7 @@ from test.script_helper import assert_python_ok
import time
import locale
import sys
import datetime
result_2004_01_text = """
January 2004
@ -464,6 +465,11 @@ class CalendarTestCase(unittest.TestCase):
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):

View File

@ -1692,6 +1692,15 @@ class CharmapTest(unittest.TestCase):
("abc", 3)
)
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 @@ class CharmapTest(unittest.TestCase):
("", 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")

View File

@ -134,15 +134,21 @@ class EncodingTest(unittest.TestCase):
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 @@ class CommandLineTests(unittest.TestCase):
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 @@ class CommandLineTests(unittest.TestCase):
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)

View File

@ -225,6 +225,15 @@ class Test_Csv(unittest.TestCase):
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='\\')

View File

@ -34,7 +34,8 @@ import numbers
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 @@ class FormatTest(unittest.TestCase):
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

View File

@ -1986,6 +1986,31 @@ def test_DocTestSuite():
>>> 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()

View File

@ -154,6 +154,11 @@ class DebuggerTests(unittest.TestCase):
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, '')

View File

@ -591,7 +591,7 @@ class PycacheTests(unittest.TestCase):
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")

View File

@ -1,4 +1,5 @@
from importlib import _bootstrap
import sys
import time
import unittest
import weakref
@ -41,6 +42,17 @@ else:
@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 @@ class DeadlockAvoidanceTests(unittest.TestCase):
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)

View File

@ -305,6 +305,18 @@ class IntTestCases(unittest.TestCase):
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:

View File

@ -2887,6 +2887,11 @@ class MiscIOTest(unittest.TestCase):
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

View File

@ -53,7 +53,7 @@ class TestMailbox(TestBase):
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 @@ class TestMailbox(TestBase):
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 @@ class TestMailbox(TestBase):
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 @@ class TestMailbox(TestBase):
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 @@ class TestMailbox(TestBase):
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 @@ class TestMaildir(TestMailbox, unittest.TestCase):
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 @@ class TestMaildir(TestMailbox, unittest.TestCase):
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 @@ class TestMaildir(TestMailbox, unittest.TestCase):
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 @@ class _TestMboxMMDF(_TestSingleFile):
def test_add_from_string(self):
# Add a string starting with 'From ' to the mailbox
key = self._box.add('From foo@bar blah\nFrom: foo\n\n0')
key = self._box.add('From foo@bar blah\nFrom: foo\n\n0\n')
self.assertEqual(self._box[key].get_from(), 'foo@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@bar blah\nFrom: foo\n\n0')
key = self._box.add(b'From foo@bar blah\nFrom: foo\n\n0\n')
self.assertEqual(self._box[key].get_from(), 'foo@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@bar blah\nFrom: foo\n\n0')
msg = class_('From foo@bar blah\nFrom: foo\n\n0\n')
key = self._box.add(msg)
def test_open_close_open(self):
@ -1116,6 +1116,29 @@ class TestMbox(_TestMboxMMDF, unittest.TestCase):
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@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)

View File

@ -318,9 +318,9 @@ class MemoryTestMixin:
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 @@ class CBytesIOTest(PyBytesIOTest):
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

View File

@ -488,6 +488,15 @@ class MmapTests(unittest.TestCase):
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')

View File

@ -1727,7 +1727,8 @@ class _TestPool(BaseTestCase):
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")

View File

@ -514,23 +514,23 @@ class EnvironTests(mapping_tests.BasicTestMappingProtocol):
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.

View File

@ -641,6 +641,16 @@ class ForeignDTDTests(unittest.TestCase):
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

View File

@ -1245,6 +1245,17 @@ class GeneralModuleTests(unittest.TestCase):
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:

View File

@ -125,12 +125,8 @@ class BasicSocketTests(unittest.TestCase):
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):

View File

@ -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 @@ class TestCase(unittest.TestCase):
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)

View File

@ -115,6 +115,21 @@ class TestSuper(unittest.TestCase):
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)

View File

@ -95,6 +95,15 @@ class TestSupport(unittest.TestCase):
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}")

View File

@ -22,7 +22,7 @@ class BaseTestCase(unittest.TestCase):
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 @@ class WrapTestCase(BaseTestCase):
"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 @@ What a mess!
["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 @@ What a mess!
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

View File

@ -225,9 +225,11 @@ class ThreadedImportTests(unittest.TestCase):
@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:

Some files were not shown because too many files have changed in this diff Show More