summaryrefslogtreecommitdiff
path: root/Doc/library
diff options
context:
space:
mode:
Diffstat (limited to 'Doc/library')
-rw-r--r--Doc/library/binascii.rst11
-rw-r--r--Doc/library/collections.rst3
-rw-r--r--Doc/library/compileall.rst12
-rw-r--r--Doc/library/crypt.rst2
-rw-r--r--Doc/library/datetime.rst135
-rw-r--r--Doc/library/decimal.rst13
-rw-r--r--Doc/library/dis.rst22
-rw-r--r--Doc/library/enum.rst12
-rw-r--r--Doc/library/faulthandler.rst3
-rw-r--r--Doc/library/fileinput.rst9
-rw-r--r--Doc/library/grp.rst3
-rw-r--r--Doc/library/imaplib.rst11
-rw-r--r--Doc/library/imp.rst15
-rw-r--r--Doc/library/importlib.rst129
-rw-r--r--Doc/library/inspect.rst25
-rw-r--r--Doc/library/logging.handlers.rst14
-rw-r--r--Doc/library/mmap.rst9
-rw-r--r--Doc/library/multiprocessing.rst9
-rw-r--r--Doc/library/os.rst32
-rw-r--r--Doc/library/pathlib.rst2
-rw-r--r--Doc/library/pickle.rst19
-rw-r--r--Doc/library/socketserver.rst6
-rw-r--r--Doc/library/spwd.rst3
-rw-r--r--Doc/library/stdtypes.rst15
-rw-r--r--Doc/library/string.rst10
-rw-r--r--Doc/library/sys.rst7
-rw-r--r--Doc/library/sysconfig.rst2
-rw-r--r--Doc/library/telnetlib.rst11
-rw-r--r--Doc/library/test.rst42
-rw-r--r--Doc/library/time.rst4
-rw-r--r--Doc/library/tracemalloc.rst45
-rw-r--r--Doc/library/unittest.mock.rst28
-rw-r--r--Doc/library/urllib.parse.rst18
-rw-r--r--Doc/library/urllib.robotparser.rst30
-rw-r--r--Doc/library/warnings.rst16
-rw-r--r--Doc/library/zipfile.rst17
-rw-r--r--Doc/library/zlib.rst11
37 files changed, 646 insertions, 109 deletions
diff --git a/Doc/library/binascii.rst b/Doc/library/binascii.rst
index ff2bddaf9d..632ecf7f0f 100644
--- a/Doc/library/binascii.rst
+++ b/Doc/library/binascii.rst
@@ -52,13 +52,14 @@ The :mod:`binascii` module defines the following functions:
than one line may be passed at a time.
-.. function:: b2a_base64(data)
+.. function:: b2a_base64(data, \*, newline=True)
Convert binary data to a line of ASCII characters in base64 coding. The return
- value is the converted line, including a newline char. The newline is
- added because the original use case for this function was to feed it a
- series of 57 byte input lines to get output lines that conform to the
- MIME-base64 standard. Otherwise the output conforms to :rfc:`3548`.
+ value is the converted line, including a newline char if *newline* is
+ true. The output of this function conforms to :rfc:`3548`.
+
+ .. versionchanged:: 3.6
+ Added the *newline* parameter.
.. function:: a2b_qp(data, header=False)
diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst
index 858a5665dc..728cd485a1 100644
--- a/Doc/library/collections.rst
+++ b/Doc/library/collections.rst
@@ -958,6 +958,9 @@ customize a prototype instance:
constructor that is convenient for use cases where named tuples are being
subclassed.
+ * :meth:`types.SimpleNamespace` for a mutable namespace based on an underlying
+ dictionary instead of a tuple.
+
:class:`OrderedDict` objects
----------------------------
diff --git a/Doc/library/compileall.rst b/Doc/library/compileall.rst
index c5736f2043..679c2b4858 100644
--- a/Doc/library/compileall.rst
+++ b/Doc/library/compileall.rst
@@ -103,7 +103,8 @@ Public functions
.. function:: compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1)
Recursively descend the directory tree named by *dir*, compiling all :file:`.py`
- files along the way.
+ files along the way. Return a true value if all the files compiled successfully,
+ and a false value otherwise.
The *maxlevels* parameter is used to limit the depth of the recursion; it
defaults to ``10``.
@@ -155,7 +156,8 @@ Public functions
.. function:: compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1)
- Compile the file with path *fullname*.
+ Compile the file with path *fullname*. Return a true value if the file
+ compiled successfully, and a false value otherwise.
If *ddir* is given, it is prepended to the path to the file being compiled
for use in compilation time tracebacks, and is also compiled in to the
@@ -191,8 +193,10 @@ Public functions
.. function:: compile_path(skip_curdir=True, maxlevels=0, force=False, quiet=0, legacy=False, optimize=-1)
- Byte-compile all the :file:`.py` files found along ``sys.path``. If
- *skip_curdir* is true (the default), the current directory is not included
+ Byte-compile all the :file:`.py` files found along ``sys.path``. Return a
+ true value if all the files compiled successfully, and a false value otherwise.
+
+ If *skip_curdir* is true (the default), the current directory is not included
in the search. All other parameters are passed to the :func:`compile_dir`
function. Note that unlike the other compile functions, ``maxlevels``
defaults to ``0``.
diff --git a/Doc/library/crypt.rst b/Doc/library/crypt.rst
index b4c90cd592..04ffdb289b 100644
--- a/Doc/library/crypt.rst
+++ b/Doc/library/crypt.rst
@@ -64,7 +64,7 @@ Module Attributes
A list of available password hashing algorithms, as
``crypt.METHOD_*`` objects. This list is sorted from strongest to
- weakest, and is guaranteed to have at least ``crypt.METHOD_CRYPT``.
+ weakest.
Module Functions
diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst
index 980dfcff6c..d73e97b1cf 100644
--- a/Doc/library/datetime.rst
+++ b/Doc/library/datetime.rst
@@ -605,7 +605,8 @@ Instance methods:
.. method:: date.__format__(format)
Same as :meth:`.date.strftime`. This makes it possible to specify a format
- string for a :class:`.date` object when using :meth:`str.format`. For a
+ string for a :class:`.date` object in :ref:`formatted string
+ literals <f-strings>` and when using :meth:`str.format`. For a
complete list of formatting directives, see
:ref:`strftime-strptime-behavior`.
@@ -1133,7 +1134,7 @@ Instance methods:
``self.date().isocalendar()``.
-.. method:: datetime.isoformat(sep='T')
+.. method:: datetime.isoformat(sep='T', timespec='auto')
Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
@@ -1154,6 +1155,37 @@ Instance methods:
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
+ The optional argument *timespec* specifies the number of additional
+ components of the time to include (the default is ``'auto'``).
+ It can be one of the following:
+
+ - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
+ same as ``'microseconds'`` otherwise.
+ - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
+ - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
+ - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
+ in HH:MM:SS format.
+ - ``'milliseconds'``: Include full time, but truncate fractional second
+ part to milliseconds. HH:MM:SS.sss format.
+ - ``'microseconds'``: Include full time in HH:MM:SS.mmmmmm format.
+
+ .. note::
+
+ Excluded time components are truncated, not rounded.
+
+ :exc:`ValueError` will be raised on an invalid *timespec* argument.
+
+
+ >>> from datetime import datetime
+ >>> datetime.now().isoformat(timespec='minutes')
+ '2002-12-25T00:00'
+ >>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
+ >>> dt.isoformat(timespec='microseconds')
+ '2015-01-01T12:30:59.000000'
+
+ .. versionadded:: 3.6
+ Added the *timespec* argument.
+
.. method:: datetime.__str__()
@@ -1180,7 +1212,8 @@ Instance methods:
.. method:: datetime.__format__(format)
Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
- string for a :class:`.datetime` object when using :meth:`str.format`. For a
+ string for a :class:`.datetime` object in :ref:`formatted string
+ literals <f-strings>` and when using :meth:`str.format`. For a
complete list of formatting directives, see
:ref:`strftime-strptime-behavior`.
@@ -1402,13 +1435,46 @@ Instance methods:
aware :class:`.time`, without conversion of the time data.
-.. method:: time.isoformat()
+.. method:: time.isoformat(timespec='auto')
Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
- self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
+ :attr:`microsecond` is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
6-character string is appended, giving the UTC offset in (signed) hours and
minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM
+ The optional argument *timespec* specifies the number of additional
+ components of the time to include (the default is ``'auto'``).
+ It can be one of the following:
+
+ - ``'auto'``: Same as ``'seconds'`` if :attr:`microsecond` is 0,
+ same as ``'microseconds'`` otherwise.
+ - ``'hours'``: Include the :attr:`hour` in the two-digit HH format.
+ - ``'minutes'``: Include :attr:`hour` and :attr:`minute` in HH:MM format.
+ - ``'seconds'``: Include :attr:`hour`, :attr:`minute`, and :attr:`second`
+ in HH:MM:SS format.
+ - ``'milliseconds'``: Include full time, but truncate fractional second
+ part to milliseconds. HH:MM:SS.sss format.
+ - ``'microseconds'``: Include full time in HH:MM:SS.mmmmmm format.
+
+ .. note::
+
+ Excluded time components are truncated, not rounded.
+
+ :exc:`ValueError` will be raised on an invalid *timespec* argument.
+
+
+ >>> from datetime import time
+ >>> time(hours=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
+ '12:34'
+ >>> dt = time(hours=12, minute=34, second=56, microsecond=0)
+ >>> dt.isoformat(timespec='microseconds')
+ '12:34:56.000000'
+ >>> dt.isoformat(timespec='auto')
+ '12:34:56'
+
+ .. versionadded:: 3.6
+ Added the *timespec* argument.
+
.. method:: time.__str__()
@@ -1425,7 +1491,8 @@ Instance methods:
.. method:: time.__format__(format)
Same as :meth:`.time.strftime`. This makes it possible to specify a format string
- for a :class:`.time` object when using :meth:`str.format`. For a
+ for a :class:`.time` object in :ref:`formatted string
+ literals <f-strings>` and when using :meth:`str.format`. For a
complete list of formatting directives, see
:ref:`strftime-strptime-behavior`.
@@ -1734,10 +1801,7 @@ made to civil time.
otherwise :exc:`ValueError` is raised.
The *name* argument is optional. If specified it must be a string that
- is used as the value returned by the ``tzname(dt)`` method. Otherwise,
- ``tzname(dt)`` returns a string 'UTCsHH:MM', where s is the sign of
- *offset*, HH and MM are two digits of ``offset.hours`` and
- ``offset.minutes`` respectively.
+ will be used as the value returned by the :meth:`datetime.tzname` method.
.. versionadded:: 3.2
@@ -1750,11 +1814,19 @@ made to civil time.
.. method:: timezone.tzname(dt)
- Return the fixed value specified when the :class:`timezone` instance is
- constructed or a string 'UTCsHH:MM', where s is the sign of
- *offset*, HH and MM are two digits of ``offset.hours`` and
+ Return the fixed value specified when the :class:`timezone` instance
+ is constructed. If *name* is not provided in the constructor, the
+ name returned by ``tzname(dt)`` is generated from the value of the
+ ``offset`` as follows. If *offset* is ``timedelta(0)``, the name
+ is "UTC", otherwise it is a string 'UTC±HH:MM', where ± is the sign
+ of ``offset``, HH and MM are two digits of ``offset.hours`` and
``offset.minutes`` respectively.
+ .. versionchanged:: 3.6
+ Name generated from ``offset=timedelta(0)`` is now plain 'UTC', not
+ 'UTC+00:00'.
+
+
.. method:: timezone.dst(dt)
Always returns ``None``.
@@ -1904,6 +1976,34 @@ format codes.
| ``%%`` | A literal ``'%'`` character. | % | |
+-----------+--------------------------------+------------------------+-------+
+Several additional directives not required by the C89 standard are included for
+convenience. These parameters all correspond to ISO 8601 date values. These
+may not be available on all platforms when used with the :meth:`strftime`
+method. The ISO 8601 year and ISO 8601 week directives are not interchangeable
+with the year and week number directives above. Calling :meth:`strptime` with
+incomplete or ambiguous ISO 8601 directives will raise a :exc:`ValueError`.
+
++-----------+--------------------------------+------------------------+-------+
+| Directive | Meaning | Example | Notes |
++===========+================================+========================+=======+
+| ``%G`` | ISO 8601 year with century | 0001, 0002, ..., 2013, | \(8) |
+| | representing the year that | 2014, ..., 9998, 9999 | |
+| | contains the greater part of | | |
+| | the ISO week (``%V``). | | |
++-----------+--------------------------------+------------------------+-------+
+| ``%u`` | ISO 8601 weekday as a decimal | 1, 2, ..., 7 | |
+| | number where 1 is Monday. | | |
++-----------+--------------------------------+------------------------+-------+
+| ``%V`` | ISO 8601 week as a decimal | 01, 02, ..., 53 | \(8) |
+| | number with Monday as | | |
+| | the first day of the week. | | |
+| | Week 01 is the week containing | | |
+| | Jan 4. | | |
++-----------+--------------------------------+------------------------+-------+
+
+.. versionadded:: 3.6
+ ``%G``, ``%u`` and ``%V`` were added.
+
Notes:
(1)
@@ -1968,7 +2068,14 @@ Notes:
(7)
When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
- in calculations when the day of the week and the year are specified.
+ in calculations when the day of the week and the calendar year (``%Y``)
+ are specified.
+
+(8)
+ Similar to ``%U`` and ``%W``, ``%V`` is only used in calculations when the
+ day of the week and the ISO year (``%G``) are specified in a
+ :meth:`strptime` format string. Also note that ``%G`` and ``%Y`` are not
+ interchangable.
.. rubric:: Footnotes
diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst
index d46f850fd7..6796f8adba 100644
--- a/Doc/library/decimal.rst
+++ b/Doc/library/decimal.rst
@@ -445,6 +445,19 @@ Decimal objects
``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
position of the most significant digit with respect to the decimal point.
+ .. method:: as_integer_ratio()
+
+ Return a pair ``(n, d)`` of integers that represent the given
+ :class:`Decimal` instance as a fraction, in lowest terms and
+ with a positive denominator::
+
+ >>> Decimal('-3.14').as_integer_ratio()
+ (-157, 50)
+
+ The conversion is exact. Raise OverflowError on infinities and ValueError
+ on NaNs.
+
+ .. versionadded:: 3.6
.. method:: as_tuple()
diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst
index 1bcb3a4a07..7222636545 100644
--- a/Doc/library/dis.rst
+++ b/Doc/library/dis.rst
@@ -989,6 +989,28 @@ the more significant byte last.
arguments.
+.. opcode:: FORMAT_VALUE (flags)
+
+ Used for implementing formatted literal strings (f-strings). Pops
+ an optional *fmt_spec* from the stack, then a required *value*.
+ *flags* is interpreted as follows:
+
+ * ``(flags & 0x03) == 0x00``: *value* is formatted as-is.
+ * ``(flags & 0x03) == 0x01``: call :func:`str` on *value* before
+ formatting it.
+ * ``(flags & 0x03) == 0x02``: call :func:`repr` on *value* before
+ formatting it.
+ * ``(flags & 0x03) == 0x03``: call :func:`ascii` on *value* before
+ formatting it.
+ * ``(flags & 0x04) == 0x04``: pop *fmt_spec* from the stack and use
+ it, else use an empty *fmt_spec*.
+
+ Formatting is performed using :c:func:`PyObject_Format`. The
+ result is pushed on the stack.
+
+ .. versionadded:: 3.6
+
+
.. opcode:: HAVE_ARGUMENT
This is not really an opcode. It identifies the dividing line between
diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index 8a02a55ed2..b3691ca4ea 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -558,7 +558,8 @@ Some rules:
4. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
:meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
`%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
-5. :meth:`str.format` (or :func:`format`) will use the mixed-in
+5. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
+ and :func:`format` will use the mixed-in
type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
:func:`repr` is desired, use the `!s` or `!r` format codes.
@@ -747,6 +748,15 @@ besides the :class:`Enum` member you looking for::
.. versionchanged:: 3.5
+Boolean evaluation: Enum classes that are mixed with non-Enum types (such as
+:class:`int`, :class:`str`, etc.) are evaluated according to the mixed-in
+type's rules; otherwise, all members evaluate as ``True``. To make your own
+Enum's boolean evaluation depend on the member's value add the following to
+your class::
+
+ def __bool__(self):
+ return bool(self.value)
+
The :attr:`__members__` attribute is only available on the class.
If you give your :class:`Enum` subclass extra methods, like the `Planet`_
diff --git a/Doc/library/faulthandler.rst b/Doc/library/faulthandler.rst
index 3a5badd0ff..3c49649c74 100644
--- a/Doc/library/faulthandler.rst
+++ b/Doc/library/faulthandler.rst
@@ -68,6 +68,9 @@ Fault handler state
.. versionchanged:: 3.5
Added support for passing file descriptor to this function.
+ .. versionchanged:: 3.6
+ On Windows, a handler for Windows exception is also installed.
+
.. function:: disable()
Disable the fault handler: uninstall the signal handlers installed by
diff --git a/Doc/library/fileinput.rst b/Doc/library/fileinput.rst
index 9510f76332..6ca4008399 100644
--- a/Doc/library/fileinput.rst
+++ b/Doc/library/fileinput.rst
@@ -71,9 +71,8 @@ The following function is the primary interface of this module:
.. versionchanged:: 3.2
Can be used as a context manager.
- .. versionchanged:: 3.5.2
- The *bufsize* parameter is no longer used.
-
+ .. deprecated-removed:: 3.6 3.8
+ The *bufsize* parameter.
The following functions use the global state created by :func:`fileinput.input`;
if there is no active state, :exc:`RuntimeError` is raised.
@@ -166,8 +165,8 @@ available for subclassing as well:
.. deprecated:: 3.4
The ``'rU'`` and ``'U'`` modes.
- .. versionchanged:: 3.5.2
- The *bufsize* parameter is no longer used.
+ .. deprecated-removed:: 3.6 3.8
+ The *bufsize* parameter.
**Optional in-place filtering:** if the keyword argument ``inplace=True`` is
diff --git a/Doc/library/grp.rst b/Doc/library/grp.rst
index 88821406a3..c840cfe67a 100644
--- a/Doc/library/grp.rst
+++ b/Doc/library/grp.rst
@@ -42,6 +42,9 @@ It defines the following items:
Return the group database entry for the given numeric group ID. :exc:`KeyError`
is raised if the entry asked for cannot be found.
+ .. deprecated:: 3.6
+ Since Python 3.6 the support of non-integer arguments like floats or
+ strings in :func:`getgrgid` is deprecated.
.. function:: getgrnam(name)
diff --git a/Doc/library/imaplib.rst b/Doc/library/imaplib.rst
index 15b0932973..cd214ffe01 100644
--- a/Doc/library/imaplib.rst
+++ b/Doc/library/imaplib.rst
@@ -500,6 +500,17 @@ An :class:`IMAP4` instance has the following methods:
M.store(num, '+FLAGS', '\\Deleted')
M.expunge()
+ .. note::
+
+ Creating flags containing ']' (for example: "[test]") violates
+ :rfc:`3501` (the IMAP protocol). However, imaplib has historically
+ allowed creation of such tags, and popular IMAP servers, such as Gmail,
+ accept and produce such flags. There are non-Python programs which also
+ create such tags. Although it is an RFC violation and IMAP clients and
+ servers are supposed to be strict, imaplib nontheless continues to allow
+ such tags to be created for backward compatibility reasons, and as of
+ python 3.6, handles them if they are sent from the server, since this
+ improves real-world compatibility.
.. method:: IMAP4.subscribe(mailbox)
diff --git a/Doc/library/imp.rst b/Doc/library/imp.rst
index 68a6b681ef..420031ab48 100644
--- a/Doc/library/imp.rst
+++ b/Doc/library/imp.rst
@@ -81,7 +81,9 @@ This module provides an interface to the mechanisms used to implement the
.. deprecated:: 3.3
Use :func:`importlib.util.find_spec` instead unless Python 3.3
compatibility is required, in which case use
- :func:`importlib.find_loader`.
+ :func:`importlib.find_loader`. For example usage of the former case,
+ see the :ref:`importlib-examples` section of the :mod:`importlib`
+ documentation.
.. function:: load_module(name, file, pathname, description)
@@ -108,9 +110,12 @@ This module provides an interface to the mechanisms used to implement the
If previously used in conjunction with :func:`imp.find_module` then
consider using :func:`importlib.import_module`, otherwise use the loader
returned by the replacement you chose for :func:`imp.find_module`. If you
- called :func:`imp.load_module` and related functions directly then use the
- classes in :mod:`importlib.machinery`, e.g.
- ``importlib.machinery.SourceFileLoader(name, path).load_module()``.
+ called :func:`imp.load_module` and related functions directly with file
+ path arguments then use a combination of
+ :func:`importlib.util.spec_from_file_location` and
+ :func:`importlib.util.module_from_spec`. See the :ref:`importlib-examples`
+ section of the :mod:`importlib` documentation for details of the various
+ approaches.
.. function:: new_module(name)
@@ -119,7 +124,7 @@ This module provides an interface to the mechanisms used to implement the
in ``sys.modules``.
.. deprecated:: 3.4
- Use :class:`types.ModuleType` instead.
+ Use :func:`importlib.util.module_from_spec` instead.
.. function:: reload(module)
diff --git a/Doc/library/importlib.rst b/Doc/library/importlib.rst
index 43b34e9005..1a1348f3b3 100644
--- a/Doc/library/importlib.rst
+++ b/Doc/library/importlib.rst
@@ -256,7 +256,7 @@ ABC hierarchy::
module and *path* will be the value of :attr:`__path__` from the
parent package. If a spec cannot be found, ``None`` is returned.
When passed in, ``target`` is a module object that the finder may
- use to make a more educated about what spec to return.
+ use to make a more educated guess about what spec to return.
.. versionadded:: 3.4
@@ -306,7 +306,7 @@ ABC hierarchy::
within the :term:`path entry` to which it is assigned. If a spec
cannot be found, ``None`` is returned. When passed in, ``target``
is a module object that the finder may use to make a more educated
- about what spec to return.
+ guess about what spec to return.
.. versionadded:: 3.4
@@ -921,6 +921,10 @@ find and load modules.
Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
specifying the name of the module to load is optional.
+ .. deprecated:: 3.6
+
+ Use :meth:`importlib.abc.Loader.exec_module` instead.
+
.. class:: SourcelessFileLoader(fullname, path)
@@ -960,6 +964,10 @@ find and load modules.
Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
specifying the name of the module to load is optional.
+ .. deprecated:: 3.6
+
+ Use :meth:`importlib.abc.Loader.exec_module` instead.
+
.. class:: ExtensionFileLoader(fullname, path)
@@ -1300,3 +1308,120 @@ an :term:`importer`.
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))
+
+.. _importlib-examples:
+
+Examples
+--------
+
+To programmatically import a module, use :func:`importlib.import_module`.
+::
+
+ import importlib
+
+ itertools = importlib.import_module('itertools')
+
+If you need to find out if a module can be imported without actually doing the
+import, then you should use :func:`importlib.util.find_spec`.
+::
+
+ import importlib.util
+ import sys
+
+ # For illustrative purposes.
+ name = 'itertools'
+
+ spec = importlib.util.find_spec(name)
+ if spec is None:
+ print("can't find the itertools module")
+ else:
+ # If you chose to perform the actual import ...
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ # Adding the module to sys.modules is optional.
+ sys.modules[name] = module
+
+To import a Python source file directly, use the following recipe
+(Python 3.4 and newer only)::
+
+ import importlib.util
+ import sys
+
+ # For illustrative purposes.
+ import tokenize
+ file_path = tokenize.__file__
+ module_name = tokenize.__name__
+
+ spec = importlib.util.spec_from_file_location(module_name, file_path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ # Optional; only necessary if you want to be able to import the module
+ # by name later.
+ sys.modules[module_name] = module
+
+For deep customizations of import, you typically want to implement an
+:term:`importer`. This means managing both the :term:`finder` and :term:`loader`
+side of things. For finders there are two flavours to choose from depending on
+your needs: a :term:`meta path finder` or a :term:`path entry finder`. The
+former is what you would put on :attr:`sys.meta_path` while the latter is what
+you create using a :term:`path entry hook` on :attr:`sys.path_hooks` which works
+with :attr:`sys.path` entries to potentially create a finder. This example will
+show you how to register your own importers so that import will use them (for
+creating an importer for yourself, read the documentation for the appropriate
+classes defined within this package)::
+
+ import importlib.machinery
+ import sys
+
+ # For illustrative purposes only.
+ SpamMetaPathFinder = importlib.machinery.PathFinder
+ SpamPathEntryFinder = importlib.machinery.FileFinder
+ loader_details = (importlib.machinery.SourceFileLoader,
+ importlib.machinery.SOURCE_SUFFIXES)
+
+ # Setting up a meta path finder.
+ # Make sure to put the finder in the proper location in the list in terms of
+ # priority.
+ sys.meta_path.append(SpamMetaPathFinder)
+
+ # Setting up a path entry finder.
+ # Make sure to put the path hook in the proper location in the list in terms
+ # of priority.
+ sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))
+
+Import itself is implemented in Python code, making it possible to
+expose most of the import machinery through importlib. The following
+helps illustrate the various APIs that importlib exposes by providing an
+approximate implementation of
+:func:`importlib.import_module` (Python 3.4 and newer for the importlib usage,
+Python 3.6 and newer for other parts of the code).
+::
+
+ import importlib.util
+ import sys
+
+ def import_module(name, package=None):
+ """An approximate implementation of import."""
+ absolute_name = importlib.util.resolve_name(name, package)
+ try:
+ return sys.modules[absolute_name]
+ except KeyError:
+ pass
+
+ path = None
+ if '.' in absolute_name:
+ parent_name, _, child_name = absolute_name.rpartition('.')
+ parent_module = import_module(parent_name)
+ path = parent_module.spec.submodule_search_locations
+ for finder in sys.meta_path:
+ spec = finder.find_spec(absolute_name, path)
+ if spec is not None:
+ break
+ else:
+ raise ImportError(f'No module named {absolute_name!r}')
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ sys.modules[absolute_name] = module
+ if path is not None:
+ setattr(parent_module, child_name, module)
+ return module
diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst
index 8d25b1e04c..aa8a181f36 100644
--- a/Doc/library/inspect.rst
+++ b/Doc/library/inspect.rst
@@ -234,24 +234,6 @@ attributes:
listed in the metaclass' custom :meth:`__dir__`.
-.. function:: getmoduleinfo(path)
-
- Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
- of values that describe how Python will interpret the file identified by
- *path* if it is a module, or ``None`` if it would not be identified as a
- module. In that tuple, *name* is the name of the module without the name of
- any enclosing package, *suffix* is the trailing part of the file name (which
- may not be a dot-delimited extension), *mode* is the :func:`open` mode that
- would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
- the type of the module. *module_type* will have a value which can be
- compared to the constants defined in the :mod:`imp` module; see the
- documentation for that module for more information on module types.
-
- .. deprecated:: 3.3
- You may check the file path's suffix against the supported suffixes
- listed in :mod:`importlib.machinery` to infer the same information.
-
-
.. function:: getmodulename(path)
Return the name of the module named by the file *path*, without including the
@@ -265,8 +247,7 @@ attributes:
still return ``None``.
.. versionchanged:: 3.3
- This function is now based directly on :mod:`importlib` rather than the
- deprecated :func:`getmoduleinfo`.
+ The function is based directly on :mod:`importlib`.
.. function:: ismodule(object)
@@ -848,8 +829,6 @@ Classes and functions
from kwonlyargs to defaults. *annotations* is a dictionary mapping argument
names to annotations.
- The first four items in the tuple correspond to :func:`getargspec`.
-
.. versionchanged:: 3.4
This function is now based on :func:`signature`, but still ignores
``__wrapped__`` attributes and includes the already bound first
@@ -878,7 +857,7 @@ Classes and functions
.. function:: formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])
Format a pretty argument spec from the values returned by
- :func:`getargspec` or :func:`getfullargspec`.
+ :func:`getfullargspec`.
The first seven arguments are (``args``, ``varargs``, ``varkw``,
``defaults``, ``kwonlyargs``, ``kwonlydefaults``, ``annotations``).
diff --git a/Doc/library/logging.handlers.rst b/Doc/library/logging.handlers.rst
index 629cd34d49..90efc45d35 100644
--- a/Doc/library/logging.handlers.rst
+++ b/Doc/library/logging.handlers.rst
@@ -162,11 +162,19 @@ for this value.
first call to :meth:`emit`. By default, the file grows indefinitely.
+ .. method:: reopenIfNeeded()
+
+ Checks to see if the file has changed. If it has, the existing stream is
+ flushed and closed and the file opened again, typically as a precursor to
+ outputting the record to the file.
+
+ .. versionadded:: 3.6
+
+
.. method:: emit(record)
- Outputs the record to the file, but first checks to see if the file has
- changed. If it has, the existing stream is flushed and closed and the
- file opened again, before outputting the record to the file.
+ Outputs the record to the file, but first calls :meth:`reopenIfNeeded` to
+ reopen the file if it has changed.
.. _base-rotating-handler:
diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst
index 33baf2bfae..fb24728105 100644
--- a/Doc/library/mmap.rst
+++ b/Doc/library/mmap.rst
@@ -263,13 +263,18 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
.. method:: write(bytes)
Write the bytes in *bytes* into memory at the current position of the
- file pointer; the file position is updated to point after the bytes that
- were written. If the mmap was created with :const:`ACCESS_READ`, then
+ file pointer and return the number of bytes written (never less than
+ ``len(bytes)``, since if the write fails, a :exc:`ValueError` will be
+ raised). The file position is updated to point after the bytes that
+ were written. If the mmap was created with :const:`ACCESS_READ`, then
writing to it will raise a :exc:`TypeError` exception.
.. versionchanged:: 3.5
Writable :term:`bytes-like object` is now accepted.
+ .. versionchanged:: 3.6
+ The number of bytes written is now returned.
+
.. method:: write_byte(byte)
diff --git a/Doc/library/multiprocessing.rst b/Doc/library/multiprocessing.rst
index 684a59f086..6440f5c988 100644
--- a/Doc/library/multiprocessing.rst
+++ b/Doc/library/multiprocessing.rst
@@ -883,8 +883,13 @@ Miscellaneous
.. function:: cpu_count()
- Return the number of CPUs in the system. May raise
- :exc:`NotImplementedError`.
+ Return the number of CPUs in the system.
+
+ This number is not equivalent to the number of CPUs the current process can
+ use. The number of usable CPUs can be obtained with
+ ``len(os.sched_getaffinity(0))``
+
+ May raise :exc:`NotImplementedError`.
.. seealso::
:func:`os.cpu_count`
diff --git a/Doc/library/os.rst b/Doc/library/os.rst
index 5cd023f21c..289276a9a5 100644
--- a/Doc/library/os.rst
+++ b/Doc/library/os.rst
@@ -1891,14 +1891,29 @@ features:
:attr:`~DirEntry.path` attributes of each :class:`DirEntry` will be of
the same type as *path*.
+ The :func:`scandir` iterator supports the :term:`context manager` protocol
+ and has the following method:
+
+ .. method:: scandir.close()
+
+ Close the iterator and free acquired resources.
+
+ This is called automatically when the iterator is exhausted or garbage
+ collected, or when an error happens during iterating. However it
+ is advisable to call it explicitly or use the :keyword:`with`
+ statement.
+
+ .. versionadded:: 3.6
+
The following example shows a simple use of :func:`scandir` to display all
the files (excluding directories) in the given *path* that don't start with
``'.'``. The ``entry.is_file()`` call will generally not make an additional
system call::
- for entry in os.scandir(path):
- if not entry.name.startswith('.') and entry.is_file():
- print(entry.name)
+ with os.scandir(path) as it:
+ for entry in it:
+ if not entry.name.startswith('.') and entry.is_file():
+ print(entry.name)
.. note::
@@ -1914,6 +1929,12 @@ features:
.. versionadded:: 3.5
+ .. versionadded:: 3.6
+ Added support for the :term:`context manager` protocol and the
+ :func:`~scandir.close()` method. If a :func:`scandir` iterator is neither
+ exhausted nor explicitly closed a :exc:`ResourceWarning` will be emitted
+ in its destructor.
+
.. class:: DirEntry
@@ -3606,6 +3627,11 @@ Miscellaneous System Information
Return the number of CPUs in the system. Returns None if undetermined.
+ This number is not equivalent to the number of CPUs the current process can
+ use. The number of usable CPUs can be obtained with
+ ``len(os.sched_getaffinity(0))``
+
+
.. versionadded:: 3.4
diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst
index a7ce18df33..5ff8be8980 100644
--- a/Doc/library/pathlib.rst
+++ b/Doc/library/pathlib.rst
@@ -195,7 +195,7 @@ Paths of a different flavour compare unequal and cannot be ordered::
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
- TypeError: unorderable types: PureWindowsPath() < PurePosixPath()
+ TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'
Operators
diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst
index 7e09b03cc6..24192774dd 100644
--- a/Doc/library/pickle.rst
+++ b/Doc/library/pickle.rst
@@ -488,7 +488,7 @@ methods:
.. method:: object.__getnewargs_ex__()
- In protocols 4 and newer, classes that implements the
+ In protocols 2 and newer, classes that implements the
:meth:`__getnewargs_ex__` method can dictate the values passed to the
:meth:`__new__` method upon unpickling. The method must return a pair
``(args, kwargs)`` where *args* is a tuple of positional arguments
@@ -500,15 +500,22 @@ methods:
class requires keyword-only arguments. Otherwise, it is recommended for
compatibility to implement :meth:`__getnewargs__`.
+ .. versionchanged:: 3.6
+ :meth:`__getnewargs_ex__` is now used in protocols 2 and 3.
+
.. method:: object.__getnewargs__()
- This method serve a similar purpose as :meth:`__getnewargs_ex__` but
- for protocols 2 and newer. It must return a tuple of arguments ``args``
- which will be passed to the :meth:`__new__` method upon unpickling.
+ This method serve a similar purpose as :meth:`__getnewargs_ex__`, but
+ supports only positional arguments. It must return a tuple of arguments
+ ``args`` which will be passed to the :meth:`__new__` method upon unpickling.
+
+ :meth:`__getnewargs__` will not be called if :meth:`__getnewargs_ex__` is
+ defined.
- In protocols 4 and newer, :meth:`__getnewargs__` will not be called if
- :meth:`__getnewargs_ex__` is defined.
+ .. versionchanged:: 3.6
+ Before Python 3.6, :meth:`__getnewargs__` was called instead of
+ :meth:`__getnewargs_ex__` in protocols 2 and 3.
.. method:: object.__getstate__()
diff --git a/Doc/library/socketserver.rst b/Doc/library/socketserver.rst
index f0cfc80bf3..aaaa61e9d9 100644
--- a/Doc/library/socketserver.rst
+++ b/Doc/library/socketserver.rst
@@ -304,7 +304,11 @@ Server Objects
This function is called if the :meth:`~BaseRequestHandler.handle`
method of a :attr:`RequestHandlerClass` instance raises
an exception. The default action is to print the traceback to
- standard output and continue handling further requests.
+ standard error and continue handling further requests.
+
+ .. versionchanged:: 3.6
+ Now only called for exceptions derived from the :exc:`Exception`
+ class.
.. method:: handle_timeout()
diff --git a/Doc/library/spwd.rst b/Doc/library/spwd.rst
index 58be78f017..53f8c09e09 100644
--- a/Doc/library/spwd.rst
+++ b/Doc/library/spwd.rst
@@ -54,6 +54,9 @@ The following functions are defined:
Return the shadow password database entry for the given user name.
+ .. versionchanged:: 3.6
+ Raises a :exc:`PermissionError` instead of :exc:`KeyError` if the user
+ doesn't have privileges.
.. function:: getspall()
diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst
index 1a1b74c762..43a3cdafb7 100644
--- a/Doc/library/stdtypes.rst
+++ b/Doc/library/stdtypes.rst
@@ -1450,8 +1450,8 @@ multiple fragments.
For more information on the ``str`` class and its methods, see
:ref:`textseq` and the :ref:`string-methods` section below. To output
- formatted strings, see the :ref:`formatstrings` section. In addition,
- see the :ref:`stringservices` section.
+ formatted strings, see the :ref:`f-strings` and :ref:`formatstrings`
+ sections. In addition, see the :ref:`stringservices` section.
.. index::
@@ -2053,8 +2053,8 @@ expression support in the :mod:`re` module).
.. index::
single: formatting, string (%)
single: interpolation, string (%)
- single: string; formatting
- single: string; interpolation
+ single: string; formatting, printf
+ single: string; interpolation, printf
single: printf-style formatting
single: sprintf-style formatting
single: % formatting
@@ -2064,9 +2064,10 @@ expression support in the :mod:`re` module).
The formatting operations described here exhibit a variety of quirks that
lead to a number of common errors (such as failing to display tuples and
- dictionaries correctly). Using the newer :meth:`str.format` interface
- helps avoid these errors, and also provides a generally more powerful,
- flexible and extensible approach to formatting text.
+ dictionaries correctly). Using the newer :ref:`formatted
+ string literals <f-strings>` or the :meth:`str.format` interface
+ helps avoid these errors. These alternatives also provide more powerful,
+ flexible and extensible approaches to formatting text.
String objects have one unique built-in operation: the ``%`` operator (modulo).
This is also known as the string *formatting* or *interpolation* operator.
diff --git a/Doc/library/string.rst b/Doc/library/string.rst
index 1da0c670a9..4eb2db41c4 100644
--- a/Doc/library/string.rst
+++ b/Doc/library/string.rst
@@ -188,7 +188,9 @@ Format String Syntax
The :meth:`str.format` method and the :class:`Formatter` class share the same
syntax for format strings (although in the case of :class:`Formatter`,
-subclasses can define their own format string syntax).
+subclasses can define their own format string syntax). The syntax is
+related to that of :ref:`formatted string literals <f-strings>`, but
+there are differences.
Format strings contain "replacement fields" surrounded by curly braces ``{}``.
Anything that is not contained in braces is considered literal text, which is
@@ -283,7 +285,8 @@ Format Specification Mini-Language
"Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented (see
-:ref:`formatstrings`). They can also be passed directly to the built-in
+:ref:`formatstrings` and :ref:`f-strings`).
+They can also be passed directly to the built-in
:func:`format` function. Each formattable type may define how the format
specification is to be interpreted.
@@ -308,7 +311,8 @@ The general form of a *standard format specifier* is:
If a valid *align* value is specified, it can be preceded by a *fill*
character that can be any character and defaults to a space if omitted.
It is not possible to use a literal curly brace ("``{``" or "``}``") as
-the *fill* character when using the :meth:`str.format`
+the *fill* character in a :ref:`formatted string literal
+<f-strings>` or when using the :meth:`str.format`
method. However, it is possible to insert a curly brace
with a nested replacement field. This limitation doesn't
affect the :func:`format` function.
diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst
index 36e8ee4087..34947f8e2c 100644
--- a/Doc/library/sys.rst
+++ b/Doc/library/sys.rst
@@ -255,7 +255,7 @@ always available.
(defaulting to zero), or another type of object. If it is an integer, zero
is considered "successful termination" and any nonzero value is considered
"abnormal termination" by shells and the like. Most systems require it to be
- in the range 0-127, and produce undefined results otherwise. Some systems
+ in the range 0--127, and produce undefined results otherwise. Some systems
have a convention for assigning specific meanings to specific exit codes, but
these are generally underdeveloped; Unix programs generally use 2 for command
line syntax errors and 1 for all other kind of errors. If another type of
@@ -268,6 +268,11 @@ always available.
the process when called from the main thread, and the exception is not
intercepted.
+ .. versionchanged:: 3.6
+ If an error occurs in the cleanup after the Python interpreter
+ has caught :exc:`SystemExit` (such as an error flushing buffered data
+ in the standard streams), the exit status is changed to 120.
+
.. data:: flags
diff --git a/Doc/library/sysconfig.rst b/Doc/library/sysconfig.rst
index 535ac54b3c..47f3900eeb 100644
--- a/Doc/library/sysconfig.rst
+++ b/Doc/library/sysconfig.rst
@@ -163,7 +163,7 @@ Other functions
.. function:: get_python_version()
Return the ``MAJOR.MINOR`` Python version number as a string. Similar to
- ``sys.version[:3]``.
+ ``'%d.%d' % sys.version_info[:2]``.
.. function:: get_platform()
diff --git a/Doc/library/telnetlib.rst b/Doc/library/telnetlib.rst
index 4040f72ee8..ce406ca2e6 100644
--- a/Doc/library/telnetlib.rst
+++ b/Doc/library/telnetlib.rst
@@ -43,6 +43,17 @@ Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).
:exc:`EOFError` when the end of the connection is read, because they can return
an empty string for other reasons. See the individual descriptions below.
+ A :class:`Telnet` object is a context manager and can be used in a
+ :keyword:`with` statement. When the :keyword:`with` block ends, the
+ :meth:`close` method is called::
+
+ >>> from telnetlib import Telnet
+ >>> with Telnet('localhost', 23) as tn:
+ ... tn.interact()
+ ...
+
+ .. versionchanged:: 3.6 Context manager support added
+
.. seealso::
diff --git a/Doc/library/test.rst b/Doc/library/test.rst
index db2da1b67f..6d1ffb817e 100644
--- a/Doc/library/test.rst
+++ b/Doc/library/test.rst
@@ -580,6 +580,48 @@ The :mod:`test.support` module defines the following functions:
.. versionadded:: 3.5
+.. function:: check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())
+
+ Assert that the ``__all__`` variable of *module* contains all public names.
+
+ The module's public names (its API) are detected automatically
+ based on whether they match the public name convention and were defined in
+ *module*.
+
+ The *name_of_module* argument can specify (as a string or tuple thereof) what
+ module(s) an API could be defined in in order to be detected as a public
+ API. One case for this is when *module* imports part of its public API from
+ other modules, possibly a C backend (like ``csv`` and its ``_csv``).
+
+ The *extra* argument can be a set of names that wouldn't otherwise be automatically
+ detected as "public", like objects without a proper ``__module__``
+ attribute. If provided, it will be added to the automatically detected ones.
+
+ The *blacklist* argument can be a set of names that must not be treated as part of
+ the public API even though their names indicate otherwise.
+
+ Example use::
+
+ import bar
+ import foo
+ import unittest
+ from test import support
+
+ class MiscTestCase(unittest.TestCase):
+ def test__all__(self):
+ support.check__all__(self, foo)
+
+ class OtherTestCase(unittest.TestCase):
+ def test__all__(self):
+ extra = {'BAR_CONST', 'FOO_CONST'}
+ blacklist = {'baz'} # Undocumented name.
+ # bar imports part of its API from _bar.
+ support.check__all__(self, bar, ('bar', '_bar'),
+ extra=extra, blacklist=blacklist)
+
+ .. versionadded:: 3.6
+
+
The :mod:`test.support` module defines the following classes:
.. class:: TransientResource(exc, **kwargs)
diff --git a/Doc/library/time.rst b/Doc/library/time.rst
index 8b53bbb0ed..c3c75d5526 100644
--- a/Doc/library/time.rst
+++ b/Doc/library/time.rst
@@ -636,11 +636,11 @@ The module defines the following functions and data items:
it is possible to refer to February 29.
:samp:`M{m}.{n}.{d}`
- The *d*'th day (0 <= *d* <= 6) or week *n* of month *m* of the year (1
+ The *d*'th day (0 <= *d* <= 6) of week *n* of month *m* of the year (1
<= *n* <= 5, 1 <= *m* <= 12, where week 5 means "the last *d* day in
month *m*" which may occur in either the fourth or the fifth
week). Week 1 is the first week in which the *d*'th day occurs. Day
- zero is Sunday.
+ zero is a Sunday.
``time`` has the same format as ``offset`` except that no leading sign
('-' or '+') is allowed. The default, if time is not given, is 02:00:00.
diff --git a/Doc/library/tracemalloc.rst b/Doc/library/tracemalloc.rst
index 5feb2d9e89..9d1cb177d7 100644
--- a/Doc/library/tracemalloc.rst
+++ b/Doc/library/tracemalloc.rst
@@ -355,10 +355,32 @@ Functions
See also the :func:`get_object_traceback` function.
+DomainFilter
+^^^^^^^^^^^^
+
+.. class:: DomainFilter(inclusive: bool, domain: int)
+
+ Filter traces of memory blocks by their address space (domain).
+
+ .. versionadded:: 3.6
+
+ .. attribute:: inclusive
+
+ If *inclusive* is ``True`` (include), match memory blocks allocated
+ in the address space :attr:`domain`.
+
+ If *inclusive* is ``False`` (exclude), match memory blocks not allocated
+ in the address space :attr:`domain`.
+
+ .. attribute:: domain
+
+ Address space of a memory block (``int``). Read-only property.
+
+
Filter
^^^^^^
-.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False)
+.. class:: Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None)
Filter on traces of memory blocks.
@@ -378,9 +400,17 @@ Filter
.. versionchanged:: 3.5
The ``'.pyo'`` file extension is no longer replaced with ``'.py'``.
+ .. versionchanged:: 3.6
+ Added the :attr:`domain` attribute.
+
+
+ .. attribute:: domain
+
+ Address space of a memory block (``int`` or ``None``).
+
.. attribute:: inclusive
- If *inclusive* is ``True`` (include), only trace memory blocks allocated
+ If *inclusive* is ``True`` (include), only match memory blocks allocated
in a file with a name matching :attr:`filename_pattern` at line number
:attr:`lineno`.
@@ -395,7 +425,7 @@ Filter
.. attribute:: filename_pattern
- Filename pattern of the filter (``str``).
+ Filename pattern of the filter (``str``). Read-only property.
.. attribute:: all_frames
@@ -458,14 +488,17 @@ Snapshot
.. method:: filter_traces(filters)
Create a new :class:`Snapshot` instance with a filtered :attr:`traces`
- sequence, *filters* is a list of :class:`Filter` instances. If *filters*
- is an empty list, return a new :class:`Snapshot` instance with a copy of
- the traces.
+ sequence, *filters* is a list of :class:`DomainFilter` and
+ :class:`Filter` instances. If *filters* is an empty list, return a new
+ :class:`Snapshot` instance with a copy of the traces.
All inclusive filters are applied at once, a trace is ignored if no
inclusive filters match it. A trace is ignored if at least one exclusive
filter matches it.
+ .. versionchanged:: 3.6
+ :class:`DomainFilter` instances are now also accepted in *filters*.
+
.. classmethod:: load(filename)
diff --git a/Doc/library/unittest.mock.rst b/Doc/library/unittest.mock.rst
index 9a51194b8a..c4dc4ed566 100644
--- a/Doc/library/unittest.mock.rst
+++ b/Doc/library/unittest.mock.rst
@@ -259,6 +259,34 @@ the *new_callable* argument to :func:`patch`.
used to set attributes on the mock after it is created. See the
:meth:`configure_mock` method for details.
+ .. method:: assert_called(*args, **kwargs)
+
+ Assert that the mock was called at least once.
+
+ >>> mock = Mock()
+ >>> mock.method()
+ <Mock name='mock.method()' id='...'>
+ >>> mock.method.assert_called()
+
+ .. versionadded:: 3.6
+
+ .. method:: assert_called_once(*args, **kwargs)
+
+ Assert that the mock was called exactly once.
+
+ >>> mock = Mock()
+ >>> mock.method()
+ <Mock name='mock.method()' id='...'>
+ >>> mock.method.assert_called_once()
+ >>> mock.method()
+ <Mock name='mock.method()' id='...'>
+ >>> mock.method.assert_called_once()
+ Traceback (most recent call last):
+ ...
+ AssertionError: Expected 'method' to have been called once. Called 2 times.
+
+ .. versionadded:: 3.6
+
.. method:: assert_called_with(*args, **kwargs)
diff --git a/Doc/library/urllib.parse.rst b/Doc/library/urllib.parse.rst
index 21c82f5262..0008740793 100644
--- a/Doc/library/urllib.parse.rst
+++ b/Doc/library/urllib.parse.rst
@@ -115,8 +115,9 @@ or on combining URL components into a URL string.
| | | if present | |
+------------------+-------+--------------------------+----------------------+
- See section :ref:`urlparse-result-object` for more information on the result
- object.
+ Reading the :attr:`port` attribute will raise a :exc:`ValueError` if
+ an invalid port is specified in the URL. See section
+ :ref:`urlparse-result-object` for more information on the result object.
.. versionchanged:: 3.2
Added IPv6 URL parsing capabilities.
@@ -126,6 +127,10 @@ or on combining URL components into a URL string.
false), in accordance with :rfc:`3986`. Previously, a whitelist of
schemes that support fragments existed.
+ .. versionchanged:: 3.6
+ Out-of-range port numbers now raise :exc:`ValueError`, instead of
+ returning :const:`None`.
+
.. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')
@@ -228,8 +233,13 @@ or on combining URL components into a URL string.
| | | if present | |
+------------------+-------+-------------------------+----------------------+
- See section :ref:`urlparse-result-object` for more information on the result
- object.
+ Reading the :attr:`port` attribute will raise a :exc:`ValueError` if
+ an invalid port is specified in the URL. See section
+ :ref:`urlparse-result-object` for more information on the result object.
+
+ .. versionchanged:: 3.6
+ Out-of-range port numbers now raise :exc:`ValueError`, instead of
+ returning :const:`None`.
.. function:: urlunsplit(parts)
diff --git a/Doc/library/urllib.robotparser.rst b/Doc/library/urllib.robotparser.rst
index f179de2f92..c2e1bef8bb 100644
--- a/Doc/library/urllib.robotparser.rst
+++ b/Doc/library/urllib.robotparser.rst
@@ -53,15 +53,41 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
Sets the time the ``robots.txt`` file was last fetched to the current
time.
+ .. method:: crawl_delay(useragent)
-The following example demonstrates basic use of the RobotFileParser class.
+ Returns the value of the ``Crawl-delay`` parameter from ``robots.txt``
+ for the *useragent* in question. If there is no such parameter or it
+ doesn't apply to the *useragent* specified or the ``robots.txt`` entry
+ for this parameter has invalid syntax, return ``None``.
+
+ .. versionadded:: 3.6
+
+ .. method:: request_rate(useragent)
+
+ Returns the contents of the ``Request-rate`` parameter from
+ ``robots.txt`` in the form of a :func:`~collections.namedtuple`
+ ``(requests, seconds)``. If there is no such parameter or it doesn't
+ apply to the *useragent* specified or the ``robots.txt`` entry for this
+ parameter has invalid syntax, return ``None``.
+
+ .. versionadded:: 3.6
+
+
+The following example demonstrates basic use of the :class:`RobotFileParser`
+class::
>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
+ >>> rrate = rp.request_rate("*")
+ >>> rrate.requests
+ 3
+ >>> rrate.seconds
+ 20
+ >>> rp.crawl_delay("*")
+ 6
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True
-
diff --git a/Doc/library/warnings.rst b/Doc/library/warnings.rst
index 8a538adb9b..4fec365716 100644
--- a/Doc/library/warnings.rst
+++ b/Doc/library/warnings.rst
@@ -300,7 +300,7 @@ Available Functions
-------------------
-.. function:: warn(message, category=None, stacklevel=1)
+.. function:: warn(message, category=None, stacklevel=1, source=None)
Issue a warning, or maybe ignore it or raise an exception. The *category*
argument, if given, must be a warning category class (see above); it defaults to
@@ -318,8 +318,14 @@ Available Functions
source of :func:`deprecation` itself (since the latter would defeat the purpose
of the warning message).
+ *source*, if supplied, is the destroyed object which emitted a
+ :exc:`ResourceWarning`.
-.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None)
+ .. versionchanged:: 3.6
+ Added *source* parameter.
+
+
+.. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)
This is a low-level interface to the functionality of :func:`warn`, passing in
explicitly the message, category, filename and line number, and optionally the
@@ -335,6 +341,12 @@ Available Functions
source for modules found in zipfiles or other non-filesystem import
sources).
+ *source*, if supplied, is the destroyed object which emitted a
+ :exc:`ResourceWarning`.
+
+ .. versionchanged:: 3.6
+ Add the *source* parameter.
+
.. function:: showwarning(message, category, filename, lineno, file=None, line=None)
diff --git a/Doc/library/zipfile.rst b/Doc/library/zipfile.rst
index 9b0d18a365..19b354daee 100644
--- a/Doc/library/zipfile.rst
+++ b/Doc/library/zipfile.rst
@@ -464,6 +464,22 @@ Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and
:meth:`.infolist` methods of :class:`ZipFile` objects. Each object stores
information about a single member of the ZIP archive.
+There is one classmethod to make a :class:`ZipInfo` instance for a filesystem
+file:
+
+.. classmethod:: ZipInfo.from_file(filename, arcname=None)
+
+ Construct a :class:`ZipInfo` instance for a file on the filesystem, in
+ preparation for adding it to a zip file.
+
+ *filename* should be the path to a file or directory on the filesystem.
+
+ If *arcname* is specified, it is used as the name within the archive.
+ If *arcname* is not specified, the name will be the same as *filename*, but
+ with any drive letter and leading path separators removed.
+
+ .. versionadded:: 3.6
+
Instances have the following attributes:
@@ -573,4 +589,5 @@ Instances have the following attributes:
Size of the uncompressed file.
+
.. _PKZIP Application Note: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
diff --git a/Doc/library/zlib.rst b/Doc/library/zlib.rst
index 1869bb8aac..09026cb155 100644
--- a/Doc/library/zlib.rst
+++ b/Doc/library/zlib.rst
@@ -46,14 +46,19 @@ The available exception and functions in this module are:
platforms, use ``adler32(data) & 0xffffffff``.
-.. function:: compress(data[, level])
+.. function:: compress(data, level=-1)
Compresses the bytes in *data*, returning a bytes object containing compressed data.
- *level* is an integer from ``0`` to ``9`` controlling the level of compression;
+ *level* is an integer from ``0`` to ``9`` or ``-1`` controlling the level of compression;
``1`` is fastest and produces the least compression, ``9`` is slowest and
- produces the most. ``0`` is no compression. The default value is ``6``.
+ produces the most. ``0`` is no compression. The default value is ``-1``
+ (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default
+ compromise between speed and compression (currently equivalent to level 6).
Raises the :exc:`error` exception if any error occurs.
+ .. versionchanged:: 3.6
+ Keyword arguments are now supported.
+
.. function:: compressobj(level=-1, method=DEFLATED, wbits=15, memLevel=8, strategy=Z_DEFAULT_STRATEGY[, zdict])