While these future statements are given additional special meaning by the
Python compiler, they are still executed like any other import statement and
-the :mod:`__future__` exists and is handled by the import system the same way
+the :mod:`!__future__` exists and is handled by the import system the same way
any other Python module would be. This design serves three purposes:
* To avoid confusing existing tools that analyze import statements and expect to
* To document when incompatible changes were introduced, and when they will be
--- or were --- made mandatory. This is a form of executable documentation, and
- can be inspected programmatically via importing :mod:`__future__` and examining
+ can be inspected programmatically via importing :mod:`!__future__` and examining
its contents.
* To ensure that :ref:`future statements <future>` run under releases prior to
- Python 2.1 at least yield runtime exceptions (the import of :mod:`__future__`
+ Python 2.1 at least yield runtime exceptions (the import of :mod:`!__future__`
will fail, because there was no module of that name prior to 2.1).
Module Contents
---------------
-No feature description will ever be deleted from :mod:`__future__`. Since its
+No feature description will ever be deleted from :mod:`!__future__`. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:
.. note::
- While :mod:`argparse` is the default recommended standard library module
+ While :mod:`!argparse` is the default recommended standard library module
for implementing basic command line applications, authors with more
exacting requirements for exactly how their command line applications
behave may find it doesn't provide the necessary level of control.
--------------
-The :mod:`ast` module helps Python applications to process trees of the Python
+The :mod:`!ast` module helps Python applications to process trees of the Python
abstract syntax grammar. The abstract syntax itself might change with each
Python release; this module helps to find out programmatically what the current
grammar looks like.
This is the base of all AST node classes. The actual node classes are
derived from the :file:`Parser/Python.asdl` file, which is reproduced
:ref:`above <abstract-grammar>`. They are defined in the :mod:`!_ast` C
- module and re-exported in :mod:`ast`.
+ module and re-exported in :mod:`!ast`.
There is one class defined for each left-hand side symbol in the abstract
grammar (for example, :class:`ast.stmt` or :class:`ast.expr`). In addition,
occurrences of the same value (for example, :class:`ast.Add`).
-:mod:`ast` helpers
-------------------
+:mod:`!ast` helpers
+-------------------
-Apart from the node classes, the :mod:`ast` module defines these utility functions
+Apart from the node classes, the :mod:`!ast` module defines these utility functions
and classes for traversing abstract syntax trees:
.. function:: parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None, optimize=-1, module=None)
.. versionadded:: 3.9
-The :mod:`ast` module can be executed as a script from the command line.
+The :mod:`!ast` module can be executed as a script from the command line.
It is as simple as:
.. code-block:: sh
--------------
-The :mod:`atexit` module defines functions to register and unregister cleanup
+The :mod:`!atexit` module defines functions to register and unregister cleanup
functions. Functions thus registered are automatically executed upon normal
-interpreter termination. :mod:`atexit` runs these functions in the *reverse*
+interpreter termination. :mod:`!atexit` runs these functions in the *reverse*
order in which they were registered; if you register ``A``, ``B``, and ``C``,
at interpreter termination time they will be run in the order ``C``, ``B``,
``A``.
Remove *func* from the list of functions to be run at interpreter shutdown.
:func:`unregister` silently does nothing if *func* was not previously
registered. If *func* has been registered more than once, every occurrence
- of that function in the :mod:`atexit` call stack will be removed. Equality
+ of that function in the :mod:`!atexit` call stack will be removed. Equality
comparisons (``==``) are used internally during unregistration, so function
references do not need to have matching identities.
.. seealso::
Module :mod:`readline`
- Useful example of :mod:`atexit` to read and write :mod:`readline` history
+ Useful example of :mod:`!atexit` to read and write :mod:`readline` history
files.
.. _atexit-example:
-:mod:`atexit` Example
----------------------
+:mod:`!atexit` Example
+----------------------
The following simple example demonstrates how a module can initialize a counter
from a file when it is imported and save the counter's updated value
--------------
-The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
+The :mod:`!bdb` module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.
The following exception is defined:
Exception raised by the :class:`Bdb` class for quitting the debugger.
-The :mod:`bdb` module also defines two classes:
+The :mod:`!bdb` module also defines two classes:
.. class:: Breakpoint(self, file, line, temporary=False, cond=None, funcname=None)
--------------
-The :mod:`binascii` module contains a number of methods to convert between
+The :mod:`!binascii` module contains a number of methods to convert between
binary and various ASCII-encoded binary representations. Normally, you will not
use these functions directly but use wrapper modules like
-:mod:`base64` instead. The :mod:`binascii` module contains
+:mod:`base64` instead. The :mod:`!binascii` module contains
low-level functions written in C for greater speed that are used by the
higher-level modules.
ASCII-only unicode strings are now accepted by the ``a2b_*`` functions.
-The :mod:`binascii` module defines the following functions:
+The :mod:`!binascii` module defines the following functions:
.. function:: a2b_uu(string)
expensive comparison operations, this can be an improvement over
linear searches or frequent resorting.
-The module is called :mod:`bisect` because it uses a basic bisection
+The module is called :mod:`!bisect` because it uses a basic bisection
algorithm to do its work. Unlike other bisection tools that search for a
specific value, the functions in this module are designed to locate an
insertion point. Accordingly, the functions never call an :meth:`~object.__eq__`
.. note::
The functions in this module are not thread-safe. If multiple threads
- concurrently use :mod:`bisect` functions on the same sequence, this
+ concurrently use :mod:`!bisect` functions on the same sequence, this
may result in undefined behaviour. Likewise, if the provided sequence
- is mutated by a different thread while a :mod:`bisect` function
+ is mutated by a different thread while a :mod:`!bisect` function
is operating on it, the result is undefined. For example, using
:py:func:`~bisect.insort_left` on the same list from multiple threads
may result in the list becoming unsorted.
This module provides a comprehensive interface for compressing and
decompressing data using the bzip2 compression algorithm.
-The :mod:`bz2` module contains:
+The :mod:`!bz2` module contains:
* The :func:`.open` function and :class:`BZ2File` class for reading and
writing compressed files.
Examples of usage
-----------------
-Below are some examples of typical usage of the :mod:`bz2` module.
+Below are some examples of typical usage of the :mod:`!bz2` module.
Using :func:`compress` and :func:`decompress` to demonstrate round-trip compression:
inverse.
-The :mod:`calendar` module exports the following data attributes:
+The :mod:`!calendar` module exports the following data attributes:
.. data:: day_name
.. versionadded:: 3.12
-The :mod:`calendar` module defines the following exceptions:
+The :mod:`!calendar` module defines the following exceptions:
.. exception:: IllegalMonthError(month)
.. versionadded:: 2.5
-The :mod:`calendar` module can be executed as a script from the command line
+The :mod:`!calendar` module can be executed as a script from the command line
to interactively print a calendar.
.. code-block:: shell
The modulus (absolute value) of a complex number *z* can be
computed using the built-in :func:`abs` function. There is no
- separate :mod:`cmath` module function for this operation.
+ separate :mod:`!cmath` module function for this operation.
.. function:: polar(z)
module :mod:`math`. The reason for having two modules is that some users aren't
interested in complex numbers, and perhaps don't even know what they are. They
would rather have ``math.sqrt(-1)`` raise an exception than return a complex
-number. Also note that the functions defined in :mod:`cmath` always return a
+number. Also note that the functions defined in :mod:`!cmath` always return a
complex number, even if the answer can be expressed as a real number (in which
case the complex number has an imaginary part of zero).
.. sectionauthor:: Raymond Hettinger <python at rcn dot com>
-The :mod:`cmd` module is mainly useful for building custom shells that let a
+The :mod:`!cmd` module is mainly useful for building custom shells that let a
user work with a program interactively.
This section presents a simple example of how to build a shell around a few of
Codec Base Classes
------------------
-The :mod:`codecs` module defines a set of base classes which define the
+The :mod:`!codecs` module defines a set of base classes which define the
interfaces for working with codec objects, and can also be used as the basis
for custom codec implementations.
--------------
-The :mod:`codeop` module provides utilities upon which the Python
+The :mod:`!codeop` module provides utilities upon which the Python
read-eval-print loop can be emulated, as is done in the :mod:`code` module. As
a result, you probably don't want to use the module directly; if you want to
include such a loop in your program you probably want to use the :mod:`code`
#. Remembering which future statements the user has entered, so subsequent
input can be compiled with these in effect.
-The :mod:`codeop` module provides a way of doing each of these things, and a way
+The :mod:`!codeop` module provides a way of doing each of these things, and a way
of doing them both.
To do just the former:
--------------
-The :mod:`colorsys` module defines bidirectional conversions of color values
+The :mod:`!colorsys` module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used in
computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness
Saturation) and HSV (Hue Saturation Value). Coordinates in all of these color
https://poynton.ca/ColorFAQ.html and
https://www.cambridgeincolour.com/tutorials/color-spaces.htm.
-The :mod:`colorsys` module defines the following functions:
+The :mod:`!colorsys` module defines the following functions:
.. function:: rgb_to_yiq(r, g, b)
--------------
-The :mod:`concurrent.futures` module provides a high-level interface for
+The :mod:`!concurrent.futures` module provides a high-level interface for
asynchronously executing callables.
The asynchronous execution can be performed with threads, using
The structure of INI files is described `in the following section
<#supported-ini-file-structure>`_. Essentially, the file
consists of sections, each of which contains keys with values.
-:mod:`configparser` classes can read and write such files. Let's start by
+:mod:`!configparser` classes can read and write such files. Let's start by
creating the above configuration file programmatically.
.. doctest::
.. versionadded:: 3.2
Mapping protocol access is a generic name for functionality that enables using
-custom objects as if they were dictionaries. In case of :mod:`configparser`,
+custom objects as if they were dictionaries. In case of :mod:`!configparser`,
the mapping interface implementation is using the
``parser['section']['option']`` notation.
are changed on a section proxy, they are actually mutated in the original
parser.
-:mod:`configparser` objects behave as close to actual dictionaries as possible.
+:mod:`!configparser` objects behave as close to actual dictionaries as possible.
The mapping interface is complete and adheres to the
:class:`~collections.abc.MutableMapping` ABC.
However, there are a few differences that should be taken into account:
----------------------------
There are nearly as many INI format variants as there are applications using it.
-:mod:`configparser` goes a long way to provide support for the largest sensible
+:mod:`!configparser` goes a long way to provide support for the largest sensible
set of INI styles available. The default functionality is mainly dictated by
historical background and it's very likely that you will want to customize some
of the features.
* *allow_no_value*, default value: ``False``
Some configuration files are known to include settings without values, but
- which otherwise conform to the syntax supported by :mod:`configparser`. The
+ which otherwise conform to the syntax supported by :mod:`!configparser`. The
*allow_no_value* parameter to the constructor can be used to
indicate that such values should be accepted:
prefixes for whole line comments.
.. versionchanged:: 3.2
- In previous versions of :mod:`configparser` behaviour matched
+ In previous versions of :mod:`!configparser` behaviour matched
``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Please note that config parsers don't support escaping of comment prefixes so
parsers in new applications.
.. versionchanged:: 3.2
- In previous versions of :mod:`configparser` behaviour matched
+ In previous versions of :mod:`!configparser` behaviour matched
``strict=False``.
* *empty_lines_in_values*, default value: ``True``
Legacy API Examples
-------------------
-Mainly because of backwards compatibility concerns, :mod:`configparser`
+Mainly because of backwards compatibility concerns, :mod:`!configparser`
provides also a legacy API with explicit ``get``/``set`` methods. While there
are valid use cases for the methods outlined below, mapping protocol access is
preferred for new projects. The legacy API is at times more advanced,
.. exception:: Error
- Base class for all other :mod:`configparser` exceptions.
+ Base class for all other :mod:`!configparser` exceptions.
.. exception:: NoSectionError
--------------------
This section describes some examples and recipes for making effective use of
-the tools provided by :mod:`contextlib`.
+the tools provided by :mod:`!contextlib`.
Supporting a variable number of context managers
Classes can use the same interfaces to control copying that they use to control
pickling. See the description of module :mod:`pickle` for information on these
-methods. In fact, the :mod:`copy` module uses the registered
+methods. In fact, the :mod:`!copy` module uses the registered
pickle functions from the :mod:`copyreg` module.
.. index::
--------------
-The :mod:`copyreg` module offers a way to define functions used while pickling
+The :mod:`!copyreg` module offers a way to define functions used while pickling
specific objects. The :mod:`pickle` and :mod:`copy` modules use those functions
when pickling/copying those objects. The module provides configuration
information about object constructors which are not classes.
efficiently manipulate such data, hiding the details of reading and writing the
data from the programmer.
-The :mod:`csv` module implements classes to read and write tabular data in CSV
+The :mod:`!csv` module implements classes to read and write tabular data in CSV
format. It allows programmers to say, "write this data in the format preferred
by Excel," or "read data from this file which was generated by Excel," without
knowing the precise details of the CSV format used by Excel. Programmers can
also describe the CSV formats understood by other applications or define their
own special-purpose CSV formats.
-The :mod:`csv` module's :class:`reader` and :class:`writer` objects read and
+The :mod:`!csv` module's :class:`reader` and :class:`writer` objects read and
write sequences. Programmers can also read and write data in dictionary form
using the :class:`DictReader` and :class:`DictWriter` classes.
Module Contents
---------------
-The :mod:`csv` module defines the following functions:
+The :mod:`!csv` module defines the following functions:
.. index::
given, this becomes the new limit.
-The :mod:`csv` module defines the following classes:
+The :mod:`!csv` module defines the following classes:
.. class:: DictReader(f, fieldnames=None, restkey=None, restval=None, \
dialect='excel', *args, **kwds)
.. _csv-constants:
-The :mod:`csv` module defines the following constants:
+The :mod:`!csv` module defines the following constants:
.. data:: QUOTE_ALL
.. versionadded:: 3.12
-The :mod:`csv` module defines the following exception:
+The :mod:`!csv` module defines the following exception:
.. exception:: Error
--------------
-:mod:`ctypes` is a foreign function library for Python. It provides C compatible
+:mod:`!ctypes` is a foreign function library for Python. It provides C compatible
data types, and allows calling functions in DLLs or shared libraries. It can be
used to wrap these libraries in pure Python.
Loading dynamic link libraries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
+:mod:`!ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
objects, for loading dynamic link libraries.
You load libraries by accessing them as attributes of these objects. *cdll*
To find out the correct calling convention you have to look into the C header
file or the documentation for the function you want to call.
-On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
+On Windows, :mod:`!ctypes` uses win32 structured exception handling to prevent
crashes from general protection faults when functions are called with invalid
argument values::
OSError: exception: access violation reading 0x00000020
>>>
-There are, however, enough ways to crash Python with :mod:`ctypes`, so you
+There are, however, enough ways to crash Python with :mod:`!ctypes`, so you
should be careful anyway. The :mod:`faulthandler` module can be helpful in
debugging crashes (e.g. from segmentation faults produced by erroneous C library
calls).
:c:expr:`int` type, their value is masked to fit into the C type.
Before we move on calling functions with other parameter types, we have to learn
-more about :mod:`ctypes` data types.
+more about :mod:`!ctypes` data types.
.. _ctypes-fundamental-data-types:
Fundamental data types
^^^^^^^^^^^^^^^^^^^^^^
-:mod:`ctypes` defines a number of primitive C compatible data types:
+:mod:`!ctypes` defines a number of primitive C compatible data types:
+----------------------+------------------------------------------+----------------------------+
| ctypes type | C type | Python type |
>>>
As has been mentioned before, all Python types except integers, strings, and
-bytes objects have to be wrapped in their corresponding :mod:`ctypes` type, so
+bytes objects have to be wrapped in their corresponding :mod:`!ctypes` type, so
that they can be converted to the required C data type::
>>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
Calling functions with your own custom data types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-You can also customize :mod:`ctypes` argument conversion to allow instances of
-your own classes be used as function arguments. :mod:`ctypes` looks for an
+You can also customize :mod:`!ctypes` argument conversion to allow instances of
+your own classes be used as function arguments. :mod:`!ctypes` looks for an
:attr:`!_as_parameter_` attribute and uses this as the function argument. The
-attribute must be an integer, string, bytes, a :mod:`ctypes` instance, or an
+attribute must be an integer, string, bytes, a :mod:`!ctypes` instance, or an
object with an :attr:`!_as_parameter_` attribute::
>>> class Bottles:
whatever is needed to make sure this object is acceptable, and then return the
object itself, its :attr:`!_as_parameter_` attribute, or whatever you want to
pass as the C function argument in this case. Again, the result should be an
-integer, string, bytes, a :mod:`ctypes` instance, or an object with an
+integer, string, bytes, a :mod:`!ctypes` instance, or an object with an
:attr:`!_as_parameter_` attribute.
probably to write into the corresponding location, or if the data is too large
to be passed by value. This is also known as *passing parameters by reference*.
-:mod:`ctypes` exports the :func:`byref` function which is used to pass parameters
+:mod:`!ctypes` exports the :func:`byref` function which is used to pass parameters
by reference. The same effect can be achieved with the :func:`pointer` function,
although :func:`pointer` does a lot more work since it constructs a real pointer
object, so it is faster to use :func:`byref` if you don't need the pointer
^^^^^^^^^^^^^^^^^^^^^
Structures and unions must derive from the :class:`Structure` and :class:`Union`
-base classes which are defined in the :mod:`ctypes` module. Each subclass must
+base classes which are defined in the :mod:`!ctypes` module. Each subclass must
define a :attr:`~Structure._fields_` attribute. :attr:`!_fields_` must be a list of
*2-tuples*, containing a *field name* and a *field type*.
-The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
-derived :mod:`ctypes` type: structure, union, array, pointer.
+The field type must be a :mod:`!ctypes` type like :class:`c_int`, or any other
+derived :mod:`!ctypes` type: structure, union, array, pointer.
Here is a simple example of a POINT structure, which contains two integers named
*x* and *y*, and also shows how to initialize a structure in the constructor::
.. warning::
- :mod:`ctypes` does not support passing unions or structures with bit-fields
+ :mod:`!ctypes` does not support passing unions or structures with bit-fields
to functions by value. While this may work on 32-bit x86, it's not
guaranteed by the library to work in the general case. Unions and
structures with bit-fields should always be passed to functions by pointer.
and/or :attr:`~Structure._align_`, respectively.
See the attribute documentation for details.
-:mod:`ctypes` uses the native byte order for Structures and Unions. To build
+:mod:`!ctypes` uses the native byte order for Structures and Unions. To build
structures with non-native byte order, you can use one of the
:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These
^^^^^^^^
Pointer instances are created by calling the :func:`pointer` function on a
-:mod:`ctypes` type::
+:mod:`!ctypes` type::
>>> from ctypes import *
>>> i = c_int(42)
c_long(42)
>>>
-Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
+Note that :mod:`!ctypes` does not have OOR (original object return), it constructs a
new, equivalent object each time you retrieve an attribute::
>>> pi.contents is i
Behind the scenes, the :func:`pointer` function does more than simply create
pointer instances, it has to create pointer *types* first. This is done with the
-:func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns a
+:func:`POINTER` function, which accepts any :mod:`!ctypes` type, and returns a
new type::
>>> PI = POINTER(c_int)
False
>>>
-:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
+:mod:`!ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
invalid non-\ ``NULL`` pointers would crash Python)::
>>> null_ptr[0]
.. XXX list other conversions...
Sometimes you have instances of incompatible types. In C, you can cast one type
-into another type. :mod:`ctypes` provides a :func:`cast` function which can be
+into another type. :mod:`!ctypes` provides a :func:`cast` function which can be
used in the same way. The ``Bar`` structure defined above accepts
``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
but not instances of other types::
>>>
because the new ``class cell`` is not available in the class statement itself.
-In :mod:`ctypes`, we can define the ``cell`` class and set the
+In :mod:`!ctypes`, we can define the ``cell`` class and set the
:attr:`~Structure._fields_` attribute later, after the class statement::
>>> from ctypes import *
Callback functions
^^^^^^^^^^^^^^^^^^
-:mod:`ctypes` allows creating C callable function pointers from Python callables.
+:mod:`!ctypes` allows creating C callable function pointers from Python callables.
These are sometimes called *callback functions*.
First, you must create a class for the callback function. The class knows the
.. note::
Make sure you keep references to :func:`CFUNCTYPE` objects as long as they
- are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be
+ are used from C code. :mod:`!ctypes` doesn't, and if you don't, they may be
garbage collected, crashing your program when a callback is made.
Also, note that if the callback function is called in a thread created
example in the Python library itself is the :c:data:`Py_Version`, Python
runtime version number encoded in a single constant integer.
-:mod:`ctypes` can access values like this with the :meth:`~_CData.in_dll` class methods of
+:mod:`!ctypes` can access values like this with the :meth:`~_CData.in_dll` class methods of
the type. *pythonapi* is a predefined symbol giving access to the Python C
api::
tricks with this to provide a dynamically created collection of frozen modules.
So manipulating this pointer could even prove useful. To restrict the example
-size, we show only how this table can be read with :mod:`ctypes`::
+size, we show only how this table can be read with :mod:`!ctypes`::
>>> from ctypes import *
>>>
Surprises
^^^^^^^^^
-There are some edges in :mod:`ctypes` where you might expect something other
+There are some edges in :mod:`!ctypes` where you might expect something other
than what actually happens.
Consider the following example::
Variable-sized data types
^^^^^^^^^^^^^^^^^^^^^^^^^
-:mod:`ctypes` provides some support for variable-sized arrays and structures.
+:mod:`!ctypes` provides some support for variable-sized arrays and structures.
The :func:`resize` function can be used to resize the memory buffer of an
existing ctypes object. The function takes the object as first argument, and
IndexError: invalid index
>>>
-Another way to use variable-sized data types with :mod:`ctypes` is to use the
+Another way to use variable-sized data types with :mod:`!ctypes` is to use the
dynamic nature of Python, and (re-)define the data type after the required size
is already known, on a case by case basis.
returns the full pathname, but since there is no predefined naming scheme a call
like ``find_library("c")`` will fail and return ``None``.
-If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
+If wrapping a shared library with :mod:`!ctypes`, it *may* be better to determine
the shared library name at development time, and hardcode that into the wrapper
module instead of using :func:`~ctypes.util.find_library` to locate the library at runtime.
The *use_errno* parameter, when set to true, enables a ctypes mechanism that
allows accessing the system :data:`errno` error number in a safe way.
-:mod:`ctypes` maintains a thread-local copy of the system's :data:`errno`
+:mod:`!ctypes` maintains a thread-local copy of the system's :data:`errno`
variable; if you call foreign functions created with ``use_errno=True`` then the
:data:`errno` value before the function call is swapped with the ctypes private
copy, the same happens immediately after the function call.
LPCWSTR lpCaption,
UINT uType);
-Here is the wrapping with :mod:`ctypes`::
+Here is the wrapping with :mod:`!ctypes`::
>>> from ctypes import c_int, WINFUNCTYPE, windll
>>> from ctypes.wintypes import HWND, LPCWSTR, UINT
HWND hWnd,
LPRECT lpRect);
-Here is the wrapping with :mod:`ctypes`::
+Here is the wrapping with :mod:`!ctypes`::
>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
>>> from ctypes.wintypes import BOOL, HWND, RECT
>>>
If the :attr:`~_CFuncPtr.errcheck` function returns the argument tuple it receives
-unchanged, :mod:`ctypes` continues the normal processing it does on the output
+unchanged, :mod:`!ctypes` continues the normal processing it does on the output
parameters. If you want to return a tuple of window coordinates instead of a
``RECT`` instance, you can retrieve the fields in the function and return them
instead, the normal processing will no longer take place::
Python bytes object or string.
When the ``value`` attribute is retrieved from a ctypes instance, usually
- a new object is returned each time. :mod:`ctypes` does *not* implement
+ a new object is returned each time. :mod:`!ctypes` does *not* implement
original object return, always a new object is constructed. The same is
true for all other ctypes object instances.
Abstract base class for structures in *native* byte order.
Concrete structure and union types must be created by subclassing one of these
- types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
+ types, and at least define a :attr:`_fields_` class variable. :mod:`!ctypes` will
create :term:`descriptor`\s which allow reading and writing the fields by direct
attribute accesses. These are the
Setting :attr:`!_pack_` to 0 is the same as not setting it at all.
Otherwise, the value must be a positive power of two.
The effect is equivalent to ``#pragma pack(N)`` in C, except
- :mod:`ctypes` may allow larger *n* than what the compiler accepts.
+ :mod:`!ctypes` may allow larger *n* than what the compiler accepts.
:attr:`!_pack_` must already be defined
when :attr:`_fields_` is assigned, otherwise it will have no effect.
The value must not be negative.
The effect is equivalent to ``__attribute__((aligned(N)))`` on GCC
- or ``#pragma align(N)`` on MSVC, except :mod:`ctypes` may allow
+ or ``#pragma align(N)`` on MSVC, except :mod:`!ctypes` may allow
values that the compiler would reject.
:attr:`!_align_` can only *increase* a structure's alignment
assigned, otherwise it will have no effect.
The fields listed in this variable must be structure or union type fields.
- :mod:`ctypes` will create descriptors in the structure type that allows
+ :mod:`!ctypes` will create descriptors in the structure type that allows
accessing the nested fields directly, without the need to create the
structure or union field.
Abstract base class for arrays.
The recommended way to create concrete array types is by multiplying any
- :mod:`ctypes` data type with a non-negative integer. Alternatively, you can subclass
+ :mod:`!ctypes` data type with a non-negative integer. Alternatively, you can subclass
this type and define :attr:`_length_` and :attr:`_type_` class variables.
Array elements can be read and written using standard
subscript and slice accesses; for slice reads, the resulting object is
Create an array.
Equivalent to ``type * length``, where *type* is a
- :mod:`ctypes` data type and *length* an integer.
+ :mod:`!ctypes` data type and *length* an integer.
This function is :term:`soft deprecated` in favor of multiplication.
There are no plans to remove it.
--------------
-The :mod:`curses.ascii` module supplies name constants for ASCII characters and
+The :mod:`!curses.ascii` module supplies name constants for ASCII characters and
functions to test membership in various ASCII character classes. The constants
supplied are names for control characters as follows:
Functions
---------
-The module :mod:`curses.panel` defines the following functions:
+The module :mod:`!curses.panel` defines the following functions:
.. function:: bottom_panel()
--------------
-The :mod:`curses` module provides an interface to the curses library, the
+The :mod:`!curses` module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.
While curses is most widely used in the Unix environment, versions are available
Functions
---------
-The module :mod:`curses` defines the following exception:
+The module :mod:`!curses` defines the following exception:
.. exception:: error
default to the current cursor location. Whenever *attr* is optional, it defaults
to :const:`A_NORMAL`.
-The module :mod:`curses` defines the following functions:
+The module :mod:`!curses` defines the following functions:
.. function:: assume_default_colors(fg, bg, /)
after :func:`initscr`.
:func:`start_color` initializes eight basic colors (black, red, green, yellow,
- blue, magenta, cyan, and white), and two global variables in the :mod:`curses`
+ blue, magenta, cyan, and white), and two global variables in the :mod:`!curses`
module, :const:`COLORS` and :const:`COLOR_PAIRS`, containing the maximum number
of colors and color-pairs the terminal can support. It also restores the colors
on the terminal to the values they had when the terminal was just turned on.
.. method:: window.idlok(flag)
- If *flag* is ``True``, :mod:`curses` will try and use hardware line
+ If *flag* is ``True``, :mod:`!curses` will try and use hardware line
editing facilities. Otherwise, line insertion/deletion are disabled.
.. method:: window.keypad(flag)
If *flag* is ``True``, escape sequences generated by some keys (keypad, function keys)
- will be interpreted by :mod:`curses`. If *flag* is ``False``, escape sequences will be
+ will be interpreted by :mod:`!curses`. If *flag* is ``False``, escape sequences will be
left as is in the input stream.
Constants
---------
-The :mod:`curses` module defines the following data members:
+The :mod:`!curses` module defines the following data members:
.. data:: ERR
--------------
-:mod:`dbm` is a generic interface to variants of the DBM database:
+:mod:`!dbm` is a generic interface to variants of the DBM database:
* :mod:`dbm.sqlite3`
* :mod:`dbm.gnu`
.. versionchanged:: 3.2
:meth:`!get` and :meth:`!setdefault` methods are now available for all
- :mod:`dbm` backends.
+ :mod:`!dbm` backends.
.. versionchanged:: 3.4
Added native support for the context management protocol to the objects
instead of :exc:`KeyError`.
.. versionchanged:: 3.13
- :meth:`!clear` methods are now available for all :mod:`dbm` backends.
+ :meth:`!clear` methods are now available for all :mod:`!dbm` backends.
The following example records some hostnames and a corresponding title, and
--------------
This module uses the standard library :mod:`sqlite3` module to provide an
-SQLite backend for the :mod:`dbm` module.
+SQLite backend for the :mod:`!dbm` module.
The files created by :mod:`dbm.sqlite3` can thus be opened by :mod:`sqlite3`,
or any other SQLite browser, including the SQLite CLI.
.. note::
While reorganizing, as much as two times the size of the original database is required
- in free disk space. However, be aware that this factor changes for each :mod:`dbm` submodule.
+ in free disk space. However, be aware that this factor changes for each :mod:`!dbm` submodule.
.. versionadded:: 3.15
.. note::
While reorganizing, as much as one time the size of the original database is required
- in free disk space. However, be aware that this factor changes for each :mod:`dbm` submodule.
+ in free disk space. However, be aware that this factor changes for each :mod:`!dbm` submodule.
.. method:: gdbm.sync()
.. note::
The :mod:`dbm.dumb` module is intended as a last resort fallback for the
- :mod:`dbm` module when a more robust module is not available. The :mod:`dbm.dumb`
+ :mod:`!dbm` module when a more robust module is not available. The :mod:`dbm.dumb`
module is not written for speed and is not nearly as heavily used as the other
database modules.
The :mod:`dbm.dumb` module provides a persistent :class:`dict`-like
interface which is written entirely in Python.
-Unlike other :mod:`dbm` backends, such as :mod:`dbm.gnu`, no
+Unlike other :mod:`!dbm` backends, such as :mod:`dbm.gnu`, no
external library is required.
The :mod:`!dbm.dumb` module defines the following:
.. note::
While reorganizing, no additional free disk space is required. However, be aware
- that this factor changes for each :mod:`dbm` submodule.
+ that this factor changes for each :mod:`!dbm` submodule.
.. versionadded:: 3.15
--------------
-The :mod:`decimal` module provides support for fast correctly rounded
+The :mod:`!decimal` module provides support for fast correctly rounded
decimal floating-point arithmetic. It offers several advantages over the
:class:`float` datatype:
:meth:`Context` constructor. To make an alternate active, use the :func:`setcontext`
function.
-In accordance with the standard, the :mod:`decimal` module provides two ready to
+In accordance with the standard, the :mod:`!decimal` module provides two ready to
use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
former is especially useful for debugging because many of the traps are
enabled:
>>> u * (v+w)
Decimal('0.0060000')
-The :mod:`decimal` module makes it possible to restore the identities by
+The :mod:`!decimal` module makes it possible to restore the identities by
expanding the precision sufficiently to avoid loss of significance:
.. doctest:: newcontext
Special values
^^^^^^^^^^^^^^
-The number system for the :mod:`decimal` module provides special values
+The number system for the :mod:`!decimal` module provides special values
including ``NaN``, ``sNaN``, ``-Infinity``, ``Infinity``,
and two zeros, ``+0`` and ``-0``.
--------------
-The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
+The :mod:`!dis` module supports the analysis of CPython :term:`bytecode` by
disassembling it. The CPython bytecode which this module takes as an input is
defined in the file :file:`Include/opcode.h` and used by the compiler and the
interpreter.
Some instructions are accompanied by one or more inline cache entries,
which take the form of :opcode:`CACHE` instructions. These instructions
are hidden by default, but can be shown by passing ``show_caches=True`` to
- any :mod:`dis` utility. Furthermore, the interpreter now adapts the
+ any :mod:`!dis` utility. Furthermore, the interpreter now adapts the
bytecode to specialize it for different runtime conditions. The
adaptive bytecode can be shown by passing ``adaptive=True``.
Command-line interface
----------------------
-The :mod:`dis` module can be invoked as a script from the command line:
+The :mod:`!dis` module can be invoked as a script from the command line:
.. code-block:: sh
Analysis functions
------------------
-The :mod:`dis` module also defines the following analysis functions that convert
+The :mod:`!dis` module also defines the following analysis functions that convert
the input directly to the desired output. They can be useful if only a single
operation is being performed, so the intermediate analysis object isn't useful:
ignore it. Before, only opcodes ``>= HAVE_ARGUMENT`` had an argument.
.. versionchanged:: 3.12
- Pseudo instructions were added to the :mod:`dis` module, and for them
+ Pseudo instructions were added to the :mod:`!dis` module, and for them
it is not true that comparison with ``HAVE_ARGUMENT`` indicates whether
they use their arg.
--------------
-The :mod:`doctest` module searches for pieces of text that look like interactive
+The :mod:`!doctest` module searches for pieces of text that look like interactive
Python sessions, and then executes those sessions to verify that they work
exactly as shown. There are several common ways to use doctest:
import doctest
doctest.testmod()
-If you run :file:`example.py` directly from the command line, :mod:`doctest`
+If you run :file:`example.py` directly from the command line, :mod:`!doctest`
works its magic:
.. code-block:: shell-session
$
There's no output! That's normal, and it means all the examples worked. Pass
-``-v`` to the script, and :mod:`doctest` prints a detailed log of what
+``-v`` to the script, and :mod:`!doctest` prints a detailed log of what
it's trying, and prints a summary at the end:
.. code-block:: shell-session
Test passed.
$
-That's all you need to know to start making productive use of :mod:`doctest`!
+That's all you need to know to start making productive use of :mod:`!doctest`!
Jump in. The following sections provide full details. Note that there are many
examples of doctests in the standard Python test suite and libraries.
Especially useful examples can be found in the standard test file
Command-line Usage
------------------
-The :mod:`doctest` module can be invoked as a script from the command line:
+The :mod:`!doctest` module can be invoked as a script from the command line:
.. code-block:: bash
What's the Execution Context?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-By default, each time :mod:`doctest` finds a docstring to test, it uses a
+By default, each time :mod:`!doctest` finds a docstring to test, it uses a
*shallow copy* of :mod:`!M`'s globals, so that running tests doesn't change the
module's real globals, and so that one test in :mod:`!M` can't leave behind
crumbs that accidentally allow another test to work. This means examples can
There is also a way to register new option flag names, though this isn't
-useful unless you intend to extend :mod:`doctest` internals via subclassing:
+useful unless you intend to extend :mod:`!doctest` internals via subclassing:
.. function:: register_optionflag(name)
Warnings
^^^^^^^^
-:mod:`doctest` is serious about requiring exact matches in expected output. If
+:mod:`!doctest` is serious about requiring exact matches in expected output. If
even a single character doesn't match, the test fails. This will probably
surprise you a few times, as you learn exactly what Python does and doesn't
guarantee about output. For example, when printing a set, Python doesn't
------------
As your collection of doctest'ed modules grows, you'll want a way to run all
-their doctests systematically. :mod:`doctest` provides two functions that can
+their doctests systematically. :mod:`!doctest` provides two functions that can
be used to create :mod:`unittest` test suites from modules and text files
containing doctests. To integrate with :mod:`unittest` test discovery, include
a :ref:`load_tests <load_tests-protocol>` function in your test module::
So both ways of creating a :class:`unittest.TestSuite` run instances of
:class:`!DocTestCase`. This is important for a subtle reason: when you run
-:mod:`doctest` functions yourself, you can control the :mod:`!doctest` options in
+:mod:`!doctest` functions yourself, you can control the :mod:`!doctest` options in
use directly, by passing option flags to :mod:`!doctest` functions. However, if
you're writing a :mod:`unittest` framework, :mod:`!unittest` ultimately controls
when and how tests get run. The framework author typically wants to control
options), but there's no way to pass options through :mod:`!unittest` to
:mod:`!doctest` test runners.
-For this reason, :mod:`doctest` also supports a notion of :mod:`!doctest`
+For this reason, :mod:`!doctest` also supports a notion of :mod:`!doctest`
reporting flags specific to :mod:`unittest` support, via this function:
.. function:: set_unittest_reportflags(flags)
- Set the :mod:`doctest` reporting flags to use.
+ Set the :mod:`!doctest` reporting flags to use.
Argument *flags* takes the :ref:`bitwise OR <bitwise>` of option flags. See
section :ref:`doctest-options`. Only "reporting flags" can be used.
Soapbox
-------
-As mentioned in the introduction, :mod:`doctest` has grown to have three primary
+As mentioned in the introduction, :mod:`!doctest` has grown to have three primary
uses:
#. Checking examples in docstrings.
add genuine value to the documentation. A good example can often be worth many
words. If done with care, the examples will be invaluable for your users, and
will pay back the time it takes to collect them many times over as the years go
-by and things change. I'm still amazed at how often one of my :mod:`doctest`
+by and things change. I'm still amazed at how often one of my :mod:`!doctest`
examples stops working after a "harmless" change.
Doctest also makes an excellent tool for regression testing, especially if you
Instances of :class:`Charset` are used in several other modules within the
:mod:`email` package.
-Import this class from the :mod:`email.charset` module.
+Import this class from the :mod:`!email.charset` module.
.. class:: Charset(input_charset=DEFAULT_CHARSET)
This method allows you to compare two :class:`Charset` instances for
inequality.
-The :mod:`email.charset` module also provides the following functions for adding
+The :mod:`!email.charset` module also provides the following functions for adding
new entries to the global character set, alias, and codec registries:
--------------
-The following exception classes are defined in the :mod:`email.errors` module:
+The following exception classes are defined in the :mod:`!email.errors` module:
.. exception:: MessageError()
:mod:`email.message`.
-The :mod:`email.generator` module also provides a derived class,
+The :mod:`!email.generator` module also provides a derived class,
:class:`DecodedGenerator`, which is like the :class:`Generator` base class,
except that non-\ :mimetype:`text` parts are not serialized, but are instead
represented in the output stream by a string derived from a template filled
written describing how to encode email containing non-ASCII characters into
:rfc:`2822`\ -compliant format. These RFCs include :rfc:`2045`, :rfc:`2046`,
:rfc:`2047`, and :rfc:`2231`. The :mod:`email` package supports these standards
-in its :mod:`email.header` and :mod:`email.charset` modules.
+in its :mod:`!email.header` and :mod:`email.charset` modules.
If you want to include non-ASCII characters in your email headers, say in the
:mailheader:`Subject` or :mailheader:`To` fields, you should use the
:class:`Header` class and assign the field in the :class:`~email.message.Message`
object to an instance of :class:`Header` instead of using a string for the header
-value. Import the :class:`Header` class from the :mod:`email.header` module.
+value. Import the :class:`Header` class from the :mod:`!email.header` module.
For example::
>>> from email.message import Message
This method allows you to compare two :class:`Header` instances for
inequality.
-The :mod:`email.header` module also provides the following convenient functions.
+The :mod:`!email.header` module also provides the following convenient functions.
.. function:: decode_header(header)
Iterating over a message object tree is fairly easy with the
:meth:`Message.walk <email.message.Message.walk>` method. The
-:mod:`email.iterators` module provides some useful higher level iterations over
+:mod:`!email.iterators` module provides some useful higher level iterations over
message object trees.
.. versionadded:: 3.6 [1]_
The central class in the :mod:`email` package is the :class:`EmailMessage`
-class, imported from the :mod:`email.message` module. It is the base class for
+class, imported from the :mod:`!email.message` module. It is the base class for
the :mod:`email` object model. :class:`EmailMessage` provides the core
functionality for setting and querying header fields, for accessing message
bodies, and for creating or modifying structured messages.
Parser API
^^^^^^^^^^
-The :class:`BytesParser` class, imported from the :mod:`email.parser` module,
+The :class:`BytesParser` class, imported from the :mod:`!email.parser` module,
provides an API that can be used to parse a message when the complete contents
of the message are available in a :term:`bytes-like object` or file. The
-:mod:`email.parser` module also provides :class:`Parser` for parsing strings,
+:mod:`!email.parser` module also provides :class:`Parser` for parsing strings,
and header-only parsers, :class:`BytesHeaderParser` and
:class:`HeaderParser`, which can be used if you're only interested in the
headers of the message. :class:`BytesHeaderParser` and :class:`HeaderParser`
--------------
-The :mod:`email` package is a library for managing email messages. It is
+The :mod:`!email` package is a library for managing email messages. It is
specifically *not* designed to do any sending of email messages to SMTP
(:rfc:`2821`), NNTP, or other servers; those are functions of modules such as
-:mod:`smtplib`. The :mod:`email` package attempts to be as
+:mod:`smtplib`. The :mod:`!email` package attempts to be as
RFC-compliant as possible, supporting :rfc:`5322` and :rfc:`6532`, as well as
such MIME-related RFCs as :rfc:`2045`, :rfc:`2046`, :rfc:`2047`, :rfc:`2183`,
and :rfc:`2231`.
are represented. Since MIME content types are used widely in modern internet
software (not just email), this will be a familiar concept to many programmers.
-The following sections describe the functionality of the :mod:`email` package.
+The following sections describe the functionality of the :mod:`!email` package.
We start with the :mod:`~email.message` object model, which is the primary
interface an application will use, and follow that with the
:mod:`~email.parser` and :mod:`~email.generator` components. Then we cover the
:class:`~email.message.EmailMessage`/:class:`~email.policy.EmailPolicy`
API.
-Contents of the :mod:`email` package documentation:
+Contents of the :mod:`!email` package documentation:
.. toctree::
--------------
-There are a couple of useful utilities provided in the :mod:`email.utils`
+There are a couple of useful utilities provided in the :mod:`!email.utils`
module:
.. function:: localtime(dt=None)
--------------
-The :mod:`ensurepip` package provides support for bootstrapping the ``pip``
+The :mod:`!ensurepip` package provides support for bootstrapping the ``pip``
installer into an existing Python installation or virtual environment. This
bootstrapping approach reflects the fact that ``pip`` is an independent
project with its own release cycle, and the latest available stable version
Module API
----------
-:mod:`ensurepip` exposes two functions for programmatic use:
+:mod:`!ensurepip` exposes two functions for programmatic use:
.. function:: version()
the latter setting ``FD_CLOEXEC`` flag in addition.
.. versionchanged:: 3.12
- On Linux >= 4.5, the :mod:`fcntl` module exposes the ``FICLONE`` and
+ On Linux >= 4.5, the :mod:`!fcntl` module exposes the ``FICLONE`` and
``FICLONERANGE`` constants, which allow to share some data of one file with
another file by reflinking on some filesystems (e.g., btrfs, OCFS2, and
XFS). This behavior is commonly referred to as "copy-on-write".
Perform the operation *cmd* on file descriptor *fd* (file objects providing
a :meth:`~io.IOBase.fileno` method are accepted as well). The values used
for *cmd* are operating system dependent, and are available as constants
- in the :mod:`fcntl` module, using the same names as used in the relevant C
+ in the :mod:`!fcntl` module, using the same names as used in the relevant C
header files. The argument *arg* can either be an integer value, a
:term:`bytes-like object`, or a string.
The type and size of *arg* must match the type and size of
--------------
-The :mod:`filecmp` module defines functions to compare files and directories,
+The :mod:`!filecmp` module defines functions to compare files and directories,
with various optional time/correctness trade-offs. For comparing files,
see also the :mod:`difflib` module.
-The :mod:`filecmp` module defines the following functions:
+The :mod:`!filecmp` module defines the following functions:
.. function:: cmp(f1, f2, shallow=True)
--------------
-The :mod:`fractions` module provides support for rational number arithmetic.
+The :mod:`!fractions` module provides support for rational number arithmetic.
A Fraction instance can be constructed from a pair of rational numbers, from
.. include:: ../includes/wasm-notavail.rst
-Here's a sample session using the :mod:`ftplib` module::
+Here's a sample session using the :mod:`!ftplib` module::
>>> from ftplib import FTP
>>> ftp = FTP('ftp.us.debian.org') # connect to host, default port
--------------
-The :mod:`functools` module is for higher-order functions: functions that act on
+The :mod:`!functools` module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.
-The :mod:`functools` module defines the following functions:
+The :mod:`!functools` module defines the following functions:
.. decorator:: cache(user_function)
``gc.DEBUG_SAVEALL``, causing garbage-collected objects to be saved in
gc.garbage for inspection.
-The :mod:`gc` module provides the following functions:
+The :mod:`!gc` module provides the following functions:
.. function:: enable()
.. include:: ../includes/wasm-notavail.rst
-The :mod:`getpass` module provides two functions:
+The :mod:`!getpass` module provides two functions:
.. function:: getpass(prompt='Password: ', stream=None, *, echo_char=None)
--------------
-The :mod:`gettext` module provides internationalization (I18N) and localization
+The :mod:`!gettext` module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the
GNU :program:`gettext` message catalog API and a higher level, class-based API that may
be more appropriate for Python files. The interface described below allows you
GNU :program:`gettext` API
--------------------------
-The :mod:`gettext` module defines the following API, which is very similar to
+The :mod:`!gettext` module defines the following API, which is very similar to
the GNU :program:`gettext` API. If you use this API you will affect the
translation of your entire application globally. Often this is what you want if
your application is monolingual, with the choice of language dependent on the
.. function:: bindtextdomain(domain, localedir=None)
Bind the *domain* to the locale directory *localedir*. More concretely,
- :mod:`gettext` will look for binary :file:`.mo` files for the given domain using
+ :mod:`!gettext` will look for binary :file:`.mo` files for the given domain using
the path (on Unix): :file:`{localedir}/{language}/LC_MESSAGES/{domain}.mo`, where
*language* is searched for in the environment variables :envvar:`LANGUAGE`,
:envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and :envvar:`LANG` respectively.
Class-based API
---------------
-The class-based API of the :mod:`gettext` module gives you more flexibility and
+The class-based API of the :mod:`!gettext` module gives you more flexibility and
greater convenience than the GNU :program:`gettext` API. It is the recommended
way of localizing your Python applications and modules. :mod:`!gettext` defines
a :class:`GNUTranslations` class which implements the parsing of GNU :file:`.mo` format
.. index:: single: GNOME
-GNOME uses a version of the :mod:`gettext` module by James Henstridge, but this
+GNOME uses a version of the :mod:`!gettext` module by James Henstridge, but this
version has a slightly different API. Its documented usage was::
import gettext
#. create language-specific translations of the message catalogs
-#. use the :mod:`gettext` module so that message strings are properly translated
+#. use the :mod:`!gettext` module so that message strings are properly translated
In order to prepare your code for I18N, you need to look at all the strings in
your files. Any string that needs to be translated should be marked by wrapping
language-specific versions as a :file:`<language-name>.po` file that's
compiled into a machine-readable :file:`.mo` binary catalog file using
the :program:`msgfmt` program. The :file:`.mo` files are used by the
-:mod:`gettext` module for the actual translation processing at
+:mod:`!gettext` module for the actual translation processing at
run-time.
-How you use the :mod:`gettext` module in your code depends on whether you are
+How you use the :mod:`!gettext` module in your code depends on whether you are
internationalizing a single module or your entire application. The next two
sections will discuss each case.
Exceptions
----------
-The :mod:`graphlib` module defines the following exception classes:
+The :mod:`!graphlib` module defines the following exception classes:
.. exception:: CycleError
The data compression is provided by the :mod:`zlib` module.
-The :mod:`gzip` module provides the :class:`GzipFile` class, as well as the
+The :mod:`!gzip` module provides the :class:`GzipFile` class, as well as the
:func:`.open`, :func:`compress` and :func:`decompress` convenience functions.
The :class:`GzipFile` class reads and writes :program:`gzip`\ -format files,
automatically compressing or decompressing the data so that it looks like an
Command-line interface
----------------------
-The :mod:`gzip` module provides a simple command line interface to compress or
+The :mod:`!gzip` module provides a simple command line interface to compress or
decompress files.
-Once executed the :mod:`gzip` module keeps the input file(s).
+Once executed the :mod:`!gzip` module keeps the input file(s).
.. versionchanged:: 3.8
These correspond to :data:`algorithms_guaranteed`.
Additional algorithms may also be available if your Python distribution's
-:mod:`hashlib` was linked against a build of OpenSSL that provides others.
+:mod:`!hashlib` was linked against a build of OpenSSL that provides others.
Others *are not guaranteed available* on all installations and will only be
accessible by name via :func:`new`. See :data:`algorithms_available`.
**salted hashing**, **personalization**, and **tree hashing**.
Hash objects from this module follow the API of standard library's
-:mod:`hashlib` objects.
+:mod:`!hashlib` objects.
Creating hash objects
--------------
-The :mod:`http.cookiejar` module defines classes for automatic handling of HTTP
+The :mod:`!http.cookiejar` module defines classes for automatic handling of HTTP
cookies. It is useful for accessing websites that require small pieces of data
-- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a
web server, and then returned to the server in later HTTP requests.
:rfc:`2109` cookies are parsed as Netscape cookies and subsequently treated
either as Netscape or RFC 2965 cookies according to the 'policy' in effect.
Note that the great majority of cookies on the internet are Netscape cookies.
-:mod:`http.cookiejar` attempts to follow the de-facto Netscape cookie protocol (which
+:mod:`!http.cookiejar` attempts to follow the de-facto Netscape cookie protocol (which
differs substantially from that set out in the original Netscape specification),
including taking note of the ``max-age`` and ``port`` cookie-attributes
introduced with RFC 2965.
.. class:: Cookie()
This class represents Netscape, :rfc:`2109` and :rfc:`2965` cookies. It is not
- expected that users of :mod:`http.cookiejar` construct their own :class:`Cookie`
+ expected that users of :mod:`!http.cookiejar` construct their own :class:`Cookie`
instances. Instead, if necessary, call :meth:`make_cookies` on a
:class:`CookieJar` instance.
Module :mod:`http.cookies`
HTTP cookie classes, principally useful for server-side code. The
- :mod:`http.cookiejar` and :mod:`http.cookies` modules do not depend on each
+ :mod:`!http.cookiejar` and :mod:`http.cookies` modules do not depend on each
other.
https://curl.se/rfc/cookie_spec.html
The specification of the original Netscape cookie protocol. Though this is
still the dominant protocol, the 'Netscape cookie protocol' implemented by all
- the major browsers (and :mod:`http.cookiejar`) only bears a passing resemblance to
+ the major browsers (and :mod:`!http.cookiejar`) only bears a passing resemblance to
the one sketched out in ``cookie_spec.html``.
:rfc:`2109` - HTTP State Management Mechanism
correspondence is not one-to-one, because there are complicated rules for
assigning default values, because the ``max-age`` and ``expires``
cookie-attributes contain equivalent information, and because :rfc:`2109` cookies
-may be 'downgraded' by :mod:`http.cookiejar` from version 1 to version 0 (Netscape)
+may be 'downgraded' by :mod:`!http.cookiejar` from version 1 to version 0 (Netscape)
cookies.
Assignment to these attributes should not be necessary other than in rare
Integer or :const:`None`. Netscape cookies have :attr:`version` 0. :rfc:`2965` and
:rfc:`2109` cookies have a ``version`` cookie-attribute of 1. However, note that
- :mod:`http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
+ :mod:`!http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
case :attr:`version` is 0.
``True`` if this cookie was received as an :rfc:`2109` cookie (ie. the cookie
arrived in a :mailheader:`Set-Cookie` header, and the value of the Version
cookie-attribute in that header was 1). This attribute is provided because
- :mod:`http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in
+ :mod:`!http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in
which case :attr:`version` is 0.
Examples
--------
-The first example shows the most common usage of :mod:`http.cookiejar`::
+The first example shows the most common usage of :mod:`!http.cookiejar`::
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
--------------
-The :mod:`http.cookies` module defines classes for abstracting the concept of
+The :mod:`!http.cookies` module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only
cookies, and provides an abstraction for having any serializable data-type as
cookie value.
Module :mod:`http.cookiejar`
HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
- :mod:`http.cookies` modules do not depend on each other.
+ :mod:`!http.cookies` modules do not depend on each other.
:rfc:`2109` - HTTP State Management Mechanism
This is the state management specification implemented by this module.
Example
-------
-The following example demonstrates how to use the :mod:`http.cookies` module.
+The following example demonstrates how to use the :mod:`!http.cookies` module.
.. doctest::
:options: +NORMALIZE_WHITESPACE
--------------
-:mod:`http` is a package that collects several modules for working with the
+:mod:`!http` is a package that collects several modules for working with the
HyperText Transfer Protocol:
* :mod:`http.client` is a low-level HTTP protocol client; for high-level URL
* :mod:`http.cookiejar` provides persistence of cookies
-The :mod:`http` module also defines the following enums that help you work with http related code:
+The :mod:`!http` module also defines the following enums that help you work with http related code:
.. class:: HTTPStatus
.. warning::
- :mod:`http.server` is not recommended for production. It only implements
+ :mod:`!http.server` is not recommended for production. It only implements
:ref:`basic security checks <http.server-security>`.
.. include:: ../includes/wasm-notavail.rst
Command-line interface
----------------------
-:mod:`http.server` can also be invoked directly using the :option:`-m`
+:mod:`!http.server` can also be invoked directly using the :option:`-m`
switch of the interpreter. The following example illustrates how to serve
files relative to the current directory::
.. include:: ../includes/wasm-notavail.rst
-Three classes are provided by the :mod:`imaplib` module, :class:`IMAP4` is the
+Three classes are provided by the :mod:`!imaplib` module, :class:`IMAP4` is the
base class:
Introduction
------------
-The purpose of the :mod:`importlib` package is three-fold.
+The purpose of the :mod:`!importlib` package is three-fold.
One is to provide the
implementation of the :keyword:`import` statement (and thus, by extension, the
--------------
-The :mod:`inspect` module provides several useful functions to help get
+The :mod:`!inspect` module provides several useful functions to help get
information about live objects such as modules, classes, methods, functions,
tracebacks, frame objects, and code objects. For example, it can help you
examine the contents of a class, retrieve the source code of a method, extract
The flags are specific to CPython, and may not be defined in other
Python implementations. Furthermore, the flags are an implementation
detail, and can be removed or deprecated in future Python releases.
- It's recommended to use public APIs from the :mod:`inspect` module
+ It's recommended to use public APIs from the :mod:`!inspect` module
for any introspection needs.
Command-line interface
----------------------
-The :mod:`inspect` module also provides a basic introspection capability
+The :mod:`!inspect` module also provides a basic introspection capability
from the command line.
.. program:: inspect
.. index::
single: file object; io module
-The :mod:`io` module provides Python's main facilities for dealing with various
+The :mod:`!io` module provides Python's main facilities for dealing with various
types of I/O. There are three main types of I/O: *text I/O*, *binary I/O*
and *raw I/O*. These are generic categories, and various backing stores can
be used for each of them. A concrete object belonging to any of these
Argument names are not part of the specification, and only the arguments of
:func:`open` are intended to be used as keyword arguments.
-The following table summarizes the ABCs provided by the :mod:`io` module:
+The following table summarizes the ABCs provided by the :mod:`!io` module:
.. tabularcolumns:: |l|l|L|L|
When the underlying raw stream is non-blocking, implementations may
either raise :exc:`BlockingIOError` or return ``None`` if no data is
- available. :mod:`io` implementations return ``None``.
+ available. :mod:`!io` implementations return ``None``.
.. method:: read1(size=-1, /)
When the underlying raw stream is non-blocking, implementations may
either raise :exc:`BlockingIOError` or return ``None`` if no data is
- available. :mod:`io` implementations return ``None``.
+ available. :mod:`!io` implementations return ``None``.
.. method:: readinto(b, /)
--------------
-:mod:`ipaddress` provides the capabilities to create, manipulate and
+:mod:`!ipaddress` provides the capabilities to create, manipulate and
operate on IPv4 and IPv6 addresses and networks.
The functions and classes in this module make it straightforward to handle
Convenience factory functions
-----------------------------
-The :mod:`ipaddress` module provides factory functions to conveniently create
+The :mod:`!ipaddress` module provides factory functions to conveniently create
IP addresses, networks and interfaces:
.. function:: ip_address(address)
IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
doesn't make sense. There are some times however, where you may wish to
- have :mod:`ipaddress` sort these anyway. If you need to do this, you can use
+ have :mod:`!ipaddress` sort these anyway. If you need to do this, you can use
this function as the *key* argument to :func:`sorted`.
*obj* is either a network or address object.
['[2.0', ', 1.0', ']']
-Using :mod:`json` from the shell to validate and pretty-print:
+Using :mod:`!json` from the shell to validate and pretty-print:
.. code-block:: shell-session
--------------
-The :mod:`json` module can be invoked as a script via ``python -m json``
+The :mod:`!json` module can be invoked as a script via ``python -m json``
to validate and pretty-print JSON objects. The :mod:`json.tool` submodule
implements this interface.
alphabetically by key.
.. versionchanged:: 3.14
- The :mod:`json` module may now be directly executed as
+ The :mod:`!json` module may now be directly executed as
``python -m json``. For backwards compatibility, invoking
the CLI as ``python -m json.tool`` remains supported.
--------------
-The :mod:`linecache` module allows one to get any line from a Python source file, while
+The :mod:`!linecache` module allows one to get any line from a Python source file, while
attempting to optimize internally, using a cache, the common case where many
lines are read from a single file. This is used by the :mod:`traceback` module
to retrieve source lines for inclusion in the formatted traceback.
function uses :func:`tokenize.detect_encoding` to get the encoding of the
file; in the absence of an encoding token, the file encoding defaults to UTF-8.
-The :mod:`linecache` module defines the following functions:
+The :mod:`!linecache` module defines the following functions:
.. function:: getline(filename, lineno, module_globals=None)
--------------
-The :mod:`locale` module opens access to the POSIX locale database and
+The :mod:`!locale` module opens access to the POSIX locale database and
functionality. The POSIX locale mechanism allows programmers to deal with
certain cultural issues in an application, without requiring the programmer to
know all the specifics of each country where the software is executed.
.. index:: pair: module; _locale
-The :mod:`locale` module is implemented on top of the :mod:`!_locale` module,
+The :mod:`!locale` module is implemented on top of the :mod:`!_locale` module,
which in turn uses an ANSI C locale implementation if available.
-The :mod:`locale` module defines the following exception and functions:
+The :mod:`!locale` module defines the following exception and functions:
.. exception:: Error
.. data:: LC_COLLATE
Locale category for sorting strings. The functions :func:`strcoll` and
- :func:`strxfrm` of the :mod:`locale` module are affected.
+ :func:`strxfrm` of the :mod:`!locale` module are affected.
.. data:: LC_TIME
.. data:: LC_NUMERIC
Locale category for formatting numbers. The functions :func:`format_string`,
- :func:`atoi`, :func:`atof` and :func:`.str` of the :mod:`locale` module are
+ :func:`atoi`, :func:`atof` and :func:`.str` of the :mod:`!locale` module are
affected by that category. All other numeric formatting operations are not
affected.
restore it, that is not very useful (except perhaps to find out whether or not
the locale is ``C``).
-When Python code uses the :mod:`locale` module to change the locale, this also
+When Python code uses the :mod:`!locale` module to change the locale, this also
affects the embedding application. If the embedding application doesn't want
this to happen, it should remove the :mod:`!_locale` extension module (which does
all the work) from the table of built-in modules in the :file:`config.c` file,
^^^^^^^^^^^^^^^^^^^^^^^
The following functions configure the logging module. They are located in the
-:mod:`logging.config` module. Their use is optional --- you can configure the
+:mod:`!logging.config` module. Their use is optional --- you can configure the
logging module using these functions or by making calls to the main API (defined
in :mod:`logging` itself) and defining handlers which are declared either in
:mod:`logging` or :mod:`logging.handlers`.
Parsing is performed by the :class:`DictConfigurator` class, whose
constructor is passed the dictionary used for configuration, and
- has a :meth:`configure` method. The :mod:`logging.config` module
+ has a :meth:`configure` method. The :mod:`!logging.config` module
has a callable attribute :attr:`dictConfigClass`
which is initially set to :class:`DictConfigurator`.
You can replace the value of :attr:`dictConfigClass` with a
.. currentmodule:: logging.handlers
-The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
+The :class:`WatchedFileHandler` class, located in the :mod:`!logging.handlers`
module, is a :class:`FileHandler` which watches the file it is logging to. If
the file changes, it is closed and reopened using the file name.
BaseRotatingHandler
^^^^^^^^^^^^^^^^^^^
-The :class:`BaseRotatingHandler` class, located in the :mod:`logging.handlers`
+The :class:`BaseRotatingHandler` class, located in the :mod:`!logging.handlers`
module, is the base class for the rotating file handlers,
:class:`RotatingFileHandler` and :class:`TimedRotatingFileHandler`. You should
not need to instantiate this class, but it has attributes and methods you may
RotatingFileHandler
^^^^^^^^^^^^^^^^^^^
-The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
+The :class:`RotatingFileHandler` class, located in the :mod:`!logging.handlers`
module, supports rotation of disk log files.
^^^^^^^^^^^^^^^^^^^^^^^^
The :class:`TimedRotatingFileHandler` class, located in the
-:mod:`logging.handlers` module, supports rotation of disk log files at certain
+:mod:`!logging.handlers` module, supports rotation of disk log files at certain
timed intervals.
SocketHandler
^^^^^^^^^^^^^
-The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
+The :class:`SocketHandler` class, located in the :mod:`!logging.handlers` module,
sends logging output to a network socket. The base class uses a TCP socket.
DatagramHandler
^^^^^^^^^^^^^^^
-The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
+The :class:`DatagramHandler` class, located in the :mod:`!logging.handlers`
module, inherits from :class:`SocketHandler` to support sending logging messages
over UDP sockets.
SysLogHandler
^^^^^^^^^^^^^
-The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
+The :class:`SysLogHandler` class, located in the :mod:`!logging.handlers` module,
supports sending logging messages to a remote or local Unix syslog.
NTEventLogHandler
^^^^^^^^^^^^^^^^^
-The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
+The :class:`NTEventLogHandler` class, located in the :mod:`!logging.handlers`
module, supports sending logging messages to a local Windows NT, Windows 2000 or
Windows XP event log. Before you can use it, you need Mark Hammond's Win32
extensions for Python installed.
SMTPHandler
^^^^^^^^^^^
-The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
+The :class:`SMTPHandler` class, located in the :mod:`!logging.handlers` module,
supports sending logging messages to an email address via SMTP.
MemoryHandler
^^^^^^^^^^^^^
-The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
+The :class:`MemoryHandler` class, located in the :mod:`!logging.handlers` module,
supports buffering of logging records in memory, periodically flushing them to a
:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
event of a certain severity or greater is seen.
HTTPHandler
^^^^^^^^^^^
-The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
+The :class:`HTTPHandler` class, located in the :mod:`!logging.handlers` module,
supports sending logging messages to a web server, using either ``GET`` or
``POST`` semantics.
.. versionadded:: 3.2
-The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
+The :class:`QueueHandler` class, located in the :mod:`!logging.handlers` module,
supports sending logging messages to a queue, such as those implemented in the
:mod:`queue` or :mod:`multiprocessing` modules.
.. versionadded:: 3.2
-The :class:`QueueListener` class, located in the :mod:`logging.handlers`
+The :class:`QueueListener` class, located in the :mod:`!logging.handlers`
module, supports receiving logging messages from a queue, such as those
implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
messages are received from a queue in an internal thread and passed, on
Integration with the warnings module
------------------------------------
-The :func:`captureWarnings` function can be used to integrate :mod:`logging`
+The :func:`captureWarnings` function can be used to integrate :mod:`!logging`
with the :mod:`warnings` module.
.. function:: captureWarnings(capture)
library.
`Original Python logging package <https://old.red-dove.com/python_logging.html>`_
- This is the original source for the :mod:`logging` package. The version of the
+ This is the original source for the :mod:`!logging` package. The version of the
package available from this site is suitable for use with Python 1.5.2, 2.1.x
- and 2.2.x, which do not include the :mod:`logging` package in the standard
+ and 2.2.x, which do not include the :mod:`!logging` package in the standard
library.
This is not a general "persistence" module. For general persistence and
transfer of Python objects through RPC calls, see the modules :mod:`pickle` and
-:mod:`shelve`. The :mod:`marshal` module exists mainly to support reading and
+:mod:`shelve`. The :mod:`!marshal` module exists mainly to support reading and
writing the "pseudo-compiled" code for Python modules of :file:`.pyc` files.
Therefore, the Python maintainers reserve the right to modify the marshal format
in backward incompatible ways should the need arise.
.. warning::
- The :mod:`marshal` module is not intended to be secure against erroneous or
+ The :mod:`!marshal` module is not intended to be secure against erroneous or
maliciously constructed data. Never unmarshal data received from an
untrusted or unauthenticated source.
-:mod:`math.integer` --- integer-specific mathematics functions
-==============================================================
+:mod:`!math.integer` --- integer-specific mathematics functions
+===============================================================
.. module:: math.integer
:synopsis: Integer-specific mathematics functions.
Number-theoretic functions
--------------------------
-For backward compatibility, the :mod:`math` module provides also aliases of
+For backward compatibility, the :mod:`!math` module provides also aliases of
the following functions from the :mod:`math.integer` module:
.. list-table::
.. impl-detail::
- The :mod:`math` module consists mostly of thin wrappers around the platform C
+ The :mod:`!math` module consists mostly of thin wrappers around the platform C
math library functions. Behavior in exceptional cases follows Annex F of
the C99 standard where appropriate. The current implementation will raise
:exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)``
--------------
-The :mod:`mimetypes` module converts between a filename or URL and the MIME type
+The :mod:`!mimetypes` module converts between a filename or URL and the MIME type
associated with the filename extension. Conversions are provided from filename
to MIME type and from MIME type to filename extension; encodings are not
supported for the latter conversion.
The :class:`MimeTypes` class may be useful for applications which may want more
than one MIME-type database; it provides an interface similar to the one of the
-:mod:`mimetypes` module.
+:mod:`!mimetypes` module.
.. class:: MimeTypes(filenames=(), strict=True)
Introduction
------------
-:mod:`multiprocessing` is a package that supports spawning processes using an
-API similar to the :mod:`threading` module. The :mod:`multiprocessing` package
+:mod:`!multiprocessing` is a package that supports spawning processes using an
+API similar to the :mod:`threading` module. The :mod:`!multiprocessing` package
offers both local and remote concurrency, effectively side-stepping the
:term:`Global Interpreter Lock <global interpreter lock>` by using
subprocesses instead of threads. Due
-to this, the :mod:`multiprocessing` module allows the programmer to fully
+to this, the :mod:`!multiprocessing` module allows the programmer to fully
leverage multiple processors on a given machine. It runs on both POSIX and
Windows.
-The :mod:`multiprocessing` module also introduces the
+The :mod:`!multiprocessing` module also introduces the
:class:`~multiprocessing.pool.Pool` object which offers a convenient means of
parallelizing the execution of a function across multiple input values,
distributing the input data across processes (data parallelism). The following
[1, 4, 9]
-The :mod:`multiprocessing` module also introduces APIs which do not have
+The :mod:`!multiprocessing` module also introduces APIs which do not have
analogs in the :mod:`threading` module, like the ability to :meth:`terminate
<Process.terminate>`, :meth:`interrupt <Process.interrupt>` or :meth:`kill
<Process.kill>` a running process.
The :class:`Process` class
^^^^^^^^^^^^^^^^^^^^^^^^^^
-In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
+In :mod:`!multiprocessing`, processes are spawned by creating a :class:`Process`
object and then calling its :meth:`~Process.start` method. :class:`Process`
follows the API of :class:`threading.Thread`. A trivial example of a
multiprocess program is ::
Contexts and start methods
^^^^^^^^^^^^^^^^^^^^^^^^^^
-Depending on the platform, :mod:`multiprocessing` supports three ways
+Depending on the platform, :mod:`!multiprocessing` supports three ways
to start a process. These *start methods* are
.. _multiprocessing-start-method-spawn:
the *fork* context cannot be passed to processes started using the
*spawn* or *forkserver* start methods.
-Libraries using :mod:`multiprocessing` or
+Libraries using :mod:`!multiprocessing` or
:class:`~concurrent.futures.ProcessPoolExecutor` should be designed to allow
their users to provide their own multiprocessing context. Using a specific
context of your own within a library can lead to incompatibilities with the
Exchanging objects between processes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-:mod:`multiprocessing` supports two types of communication channel between
+:mod:`!multiprocessing` supports two types of communication channel between
processes:
**Queues**
Synchronization between processes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-:mod:`multiprocessing` contains equivalents of all the synchronization
+:mod:`!multiprocessing` contains equivalents of all the synchronization
primitives from :mod:`threading`. For instance one can use a lock to ensure
that only one process prints to standard output at a time::
using multiple processes.
However, if you really do need to use some shared data then
-:mod:`multiprocessing` provides a couple of ways of doing so.
+:mod:`!multiprocessing` provides a couple of ways of doing so.
**Shared memory**
Reference
---------
-The :mod:`multiprocessing` package mostly replicates the API of the
+The :mod:`!multiprocessing` package mostly replicates the API of the
:mod:`threading` module.
.. _global-start-method:
The process's authentication key (a byte string).
- When :mod:`multiprocessing` is initialized the main process is assigned a
+ When :mod:`!multiprocessing` is initialized the main process is assigned a
random string using :func:`os.urandom`.
When a :class:`Process` object is created, it will inherit the
.. exception:: ProcessError
- The base class of all :mod:`multiprocessing` exceptions.
+ The base class of all :mod:`!multiprocessing` exceptions.
.. exception:: BufferTooShort
semaphore used to count the number of unfinished tasks may eventually overflow,
raising an exception.
-One difference from other Python queue implementations, is that :mod:`multiprocessing`
+One difference from other Python queue implementations, is that :mod:`!multiprocessing`
queues serializes all objects that are put into them using :mod:`pickle`.
The object returned by the get method is a re-created object that does not share
memory with the original object.
.. note::
- :mod:`multiprocessing` uses the usual :exc:`queue.Empty` and
+ :mod:`!multiprocessing` uses the usual :exc:`queue.Empty` and
:exc:`queue.Full` exceptions to signal a timeout. They are not available in
- the :mod:`multiprocessing` namespace so you need to import them from
+ the :mod:`!multiprocessing` namespace so you need to import them from
:mod:`queue`.
.. note::
.. function:: freeze_support()
- Add support for when a program which uses :mod:`multiprocessing` has been
+ Add support for when a program which uses :mod:`!multiprocessing` has been
frozen to produce an executable. (Has been tested with **py2exe**,
**PyInstaller** and **cx_Freeze**.)
.. function:: get_context(method=None)
Return a context object which has the same attributes as the
- :mod:`multiprocessing` module.
+ :mod:`!multiprocessing` module.
If *method* is ``None`` then the default context is returned. Note that if
the global start method has not been set, this will set it to the system default
.. note::
- :mod:`multiprocessing` contains no analogues of
+ :mod:`!multiprocessing` contains no analogues of
:func:`threading.active_count`, :func:`threading.enumerate`,
:func:`threading.settrace`, :func:`threading.setprofile`,
:class:`threading.Timer`, or :class:`threading.local`.
A condition variable: an alias for :class:`threading.Condition`.
If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
- object from :mod:`multiprocessing`.
+ object from :mod:`!multiprocessing`.
Instantiating this class may set the global start method. See
:ref:`global-start-method` for more details.
.. note::
- The proxy types in :mod:`multiprocessing` do nothing to support comparisons
+ The proxy types in :mod:`!multiprocessing` do nothing to support comparisons
by value. So, for instance, we have:
.. doctest::
.. currentmodule:: multiprocessing
.. function:: get_logger()
- Returns the logger used by :mod:`multiprocessing`. If necessary, a new one
+ Returns the logger used by :mod:`!multiprocessing`. If necessary, a new one
will be created.
When first created the logger has level :const:`logging.NOTSET` and no
.. module:: multiprocessing.dummy
:synopsis: Dumb wrapper around threading.
-:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
+:mod:`multiprocessing.dummy` replicates the API of :mod:`!multiprocessing` but is
no more than a wrapper around the :mod:`threading` module.
.. currentmodule:: multiprocessing.pool
----------------------
There are certain guidelines and idioms which should be adhered to when using
-:mod:`multiprocessing`.
+:mod:`!multiprocessing`.
All start methods
Better to inherit than pickle/unpickle
When using the *spawn* or *forkserver* start methods many types
- from :mod:`multiprocessing` need to be picklable so that child
+ from :mod:`!multiprocessing` need to be picklable so that child
processes can use them. However, one should generally avoid
sending shared objects to other processes using pipes or queues.
Instead you should arrange the program so that a process which
Beware of replacing :data:`sys.stdin` with a "file like object"
- :mod:`multiprocessing` originally unconditionally called::
+ :mod:`!multiprocessing` originally unconditionally called::
os.close(sys.stdin.fileno())
--------------
-The :mod:`operator` module exports a set of efficient functions corresponding to
+The :mod:`!operator` module exports a set of efficient functions corresponding to
the intrinsic operators of Python. For example, ``operator.add(x, y)`` is
equivalent to the expression ``x+y``. Many function names are those used for
special methods, without the double underscores. For backward compatibility,
.. versionadded:: 3.11
-The :mod:`operator` module also defines tools for generalized attribute and item
+The :mod:`!operator` module also defines tools for generalized attribute and item
lookups. These are useful for making fast field extractors as arguments for
:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
expect a function argument.
------------------------------
This table shows how abstract operations correspond to operator symbols in the
-Python syntax and the functions in the :mod:`operator` module.
+Python syntax and the functions in the :mod:`!operator` module.
+-----------------------+-------------------------+---------------------------------------+
| Operation | Syntax | Function |
* :mod:`getopt`: a module that closely mirrors the procedural C ``getopt`` API.
Included in the standard library since before the initial Python 1.0 release.
-* :mod:`optparse`: a declarative replacement for ``getopt`` that
+* :mod:`!optparse`: a declarative replacement for ``getopt`` that
provides equivalent functionality without requiring each application
to implement its own procedural option parsing logic. Included
in the standard library since the Python 2.3 release.
However, it also serves a niche use case as a tool for prototyping and testing
command line argument handling in ``getopt``-based C applications.
-:mod:`optparse` should be considered as an alternative to :mod:`argparse` in the
+:mod:`!optparse` should be considered as an alternative to :mod:`argparse` in the
following cases:
-* an application is already using :mod:`optparse` and doesn't want to risk the
+* an application is already using :mod:`!optparse` and doesn't want to risk the
subtle behavioural changes that may arise when migrating to :mod:`argparse`
* the application requires additional control over the way options and
positional parameters are interleaved on the command line (including
behavior which ``argparse`` does not support, but which can be implemented
in terms of the lower level interface offered by ``optparse``
-These considerations also mean that :mod:`optparse` is likely to provide a
+These considerations also mean that :mod:`!optparse` is likely to provide a
better foundation for library authors writing third party command line
argument processing libraries.
Introduction
------------
-:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
+:mod:`!optparse` is a more convenient, flexible, and powerful library for parsing
command-line options than the minimalist :mod:`getopt` module.
-:mod:`optparse` uses a more declarative style of command-line parsing:
+:mod:`!optparse` uses a more declarative style of command-line parsing:
you create an instance of :class:`OptionParser`,
populate it with options, and parse the command line.
-:mod:`optparse` allows users to specify options in the conventional
+:mod:`!optparse` allows users to specify options in the conventional
GNU/POSIX syntax, and additionally generates usage and help messages for you.
-Here's an example of using :mod:`optparse` in a simple script::
+Here's an example of using :mod:`!optparse` in a simple script::
from optparse import OptionParser
...
<yourscript> --file=outfile -q
-As it parses the command line, :mod:`optparse` sets attributes of the
+As it parses the command line, :mod:`!optparse` sets attributes of the
``options`` object returned by :meth:`~OptionParser.parse_args` based on user-supplied
command-line values. When :meth:`~OptionParser.parse_args` returns from parsing this command
line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
-``False``. :mod:`optparse` supports both long and short options, allows short
+``False``. :mod:`!optparse` supports both long and short options, allows short
options to be merged together, and allows options to be associated with their
arguments in a variety of ways. Thus, the following command lines are all
equivalent to the above example::
<yourscript> -h
<yourscript> --help
-and :mod:`optparse` will print out a brief summary of your script's options:
+and :mod:`!optparse` will print out a brief summary of your script's options:
.. code-block:: text
Background
----------
-:mod:`optparse` was explicitly designed to encourage the creation of programs
+:mod:`!optparse` was explicitly designed to encourage the creation of programs
with straightforward command-line interfaces that follow the conventions
established by the :c:func:`!getopt` family of functions available to C developers.
To that end, it supports only the most common command-line syntax and semantics
options to be merged into a single argument, e.g. ``-x -F`` is equivalent
to ``-xF``. The GNU project introduced ``--`` followed by a series of
hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
- only two option syntaxes provided by :mod:`optparse`.
+ only two option syntaxes provided by :mod:`!optparse`.
Some other option syntaxes that the world has seen include:
* a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
``/file``
- These option syntaxes are not supported by :mod:`optparse`, and they never
+ These option syntaxes are not supported by :mod:`!optparse`, and they never
will be. This is deliberate: the first three are non-standard on any
environment, and the last only makes sense if you're exclusively targeting
Windows or certain legacy platforms (e.g. VMS, MS-DOS).
option argument
an argument that follows an option, is closely associated with that option,
and is consumed from the argument list when that option is. With
- :mod:`optparse`, option arguments may either be in a separate argument from
+ :mod:`!optparse`, option arguments may either be in a separate argument from
their option:
.. code-block:: text
will take an argument if they see it, and won't if they don't. This is
somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
an optional argument and ``-b`` is another option entirely, how do we
- interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
+ interpret ``-ab``? Because of this ambiguity, :mod:`!optparse` does not
support this feature.
positional argument
required option
an option that must be supplied on the command-line; note that the phrase
- "required option" is self-contradictory in English. :mod:`optparse` doesn't
+ "required option" is self-contradictory in English. :mod:`!optparse` doesn't
prevent you from implementing required options, but doesn't give you much
help at it either.
Tutorial
--------
-While :mod:`optparse` is quite flexible and powerful, it's also straightforward
+While :mod:`!optparse` is quite flexible and powerful, it's also straightforward
to use in most cases. This section covers the code patterns that are common to
-any :mod:`optparse`\ -based program.
+any :mod:`!optparse`\ -based program.
First, you need to import the OptionParser class; then, early in the main
program, create an OptionParser instance::
attr=value, ...)
Each option has one or more option strings, such as ``-f`` or ``--file``,
-and several option attributes that tell :mod:`optparse` what to expect and what
+and several option attributes that tell :mod:`!optparse` what to expect and what
to do when it encounters that option on the command line.
Typically, each option will have one short option string and one long option
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`
+*encountering an option* on the command line; in reality, :mod:`!optparse`
encounters *option strings* and looks up options from them.
-Once all of your options are defined, instruct :mod:`optparse` to parse your
+Once all of your options are defined, instruct :mod:`!optparse` to parse your
program's command line::
(options, args) = parser.parse_args()
Understanding option actions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Actions tell :mod:`optparse` what to do when it encounters an option on the
-command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
+Actions tell :mod:`!optparse` what to do when it encounters an option on the
+command line. There is a fixed set of actions hard-coded into :mod:`!optparse`;
adding new actions is an advanced topic covered in section
-:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
+:ref:`optparse-extending-optparse`. Most actions tell :mod:`!optparse` to store
a value in some variable---for example, take a string from the command line and
store it in an attribute of ``options``.
-If you don't specify an option action, :mod:`optparse` defaults to ``store``.
+If you don't specify an option action, :mod:`!optparse` defaults to ``store``.
.. _optparse-store-action:
The store action
^^^^^^^^^^^^^^^^
-The most common option action is ``store``, which tells :mod:`optparse` to take
+The most common option action is ``store``, which tells :mod:`!optparse` to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.
parser.add_option("-f", "--file",
action="store", type="string", dest="filename")
-Now let's make up a fake command line and ask :mod:`optparse` to parse it::
+Now let's make up a fake command line and ask :mod:`!optparse` to parse it::
args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)
-When :mod:`optparse` sees the option string ``-f``, it consumes the next
+When :mod:`!optparse` sees the option string ``-f``, it consumes the next
argument, ``foo.txt``, and stores it in ``options.filename``. So, after this
call to :meth:`~OptionParser.parse_args`, ``options.filename`` is ``"foo.txt"``.
-Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
+Some other option types supported by :mod:`!optparse` are ``int`` and ``float``.
Here's an option that expects an integer argument::
parser.add_option("-n", type="int", dest="num")
will print ``42``.
-If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
+If you don't specify a type, :mod:`!optparse` assumes ``string``. Combined with
the fact that the default action is ``store``, that means our first example can
be a lot shorter::
parser.add_option("-f", "--file", dest="filename")
-If you don't supply a destination, :mod:`optparse` figures out a sensible
+If you don't supply a destination, :mod:`!optparse` figures out a sensible
default from the option strings: if the first long option string is
``--foo-bar``, then the default destination is ``foo_bar``. If there are no
-long option strings, :mod:`optparse` looks at the first short option string: the
+long option strings, :mod:`!optparse` looks at the first short option string: the
default destination for ``-f`` is ``f``.
-:mod:`optparse` also includes the built-in ``complex`` type. Adding
+:mod:`!optparse` also includes the built-in ``complex`` type. Adding
types is covered in section :ref:`optparse-extending-optparse`.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Flag options---set a variable to true or false when a particular option is
-seen---are quite common. :mod:`optparse` supports them with two separate actions,
+seen---are quite common. :mod:`!optparse` supports them with two separate actions,
``store_true`` and ``store_false``. For example, you might have a ``verbose``
flag that is turned on with ``-v`` and off with ``-q``::
OK. (It just means you have to be a bit careful when setting default
values---see below.)
-When :mod:`optparse` encounters ``-v`` on the command line, it sets
+When :mod:`!optparse` encounters ``-v`` on the command line, it sets
``options.verbose`` to ``True``; when it encounters ``-q``,
``options.verbose`` is set to ``False``.
Other actions
^^^^^^^^^^^^^
-Some other actions supported by :mod:`optparse` are:
+Some other actions supported by :mod:`!optparse` are:
``"store_const"``
store a constant value, pre-set via :attr:`Option.const`
All of the above examples involve setting some variable (the "destination") when
certain command-line options are seen. What happens if those options are never
seen? Since we didn't supply any defaults, they are all set to ``None``. This
-is usually fine, but sometimes you want more control. :mod:`optparse` lets you
+is usually fine, but sometimes you want more control. :mod:`!optparse` lets you
supply a default value for each destination, which is assigned before the
command line is parsed.
-First, consider the verbose/quiet example. If we want :mod:`optparse` to set
+First, consider the verbose/quiet example. If we want :mod:`!optparse` to set
``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
parser.add_option("-v", action="store_true", dest="verbose", default=True)
Generating help
^^^^^^^^^^^^^^^
-:mod:`optparse`'s ability to generate help and usage text automatically is
+:mod:`!optparse`'s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces. All you have to do
is supply a :attr:`~Option.help` value for each option, and optionally a short
usage message for your whole program. Here's an OptionParser populated with
help="interaction mode: novice, intermediate, "
"or expert [default: %default]")
-If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
+If :mod:`!optparse` encounters either ``-h`` or ``--help`` on the
command-line, or if you just call :meth:`parser.print_help`, it prints the
following to standard output:
-m MODE, --mode=MODE interaction mode: novice, intermediate, or
expert [default: intermediate]
-(If the help output is triggered by a help option, :mod:`optparse` exits after
+(If the help output is triggered by a help option, :mod:`!optparse` exits after
printing the help text.)
-There's a lot going on here to help :mod:`optparse` generate the best possible
+There's a lot going on here to help :mod:`!optparse` generate the best possible
help message:
* the script defines its own usage message::
usage = "usage: %prog [options] arg1 arg2"
- :mod:`optparse` expands ``%prog`` in the usage string to the name of the
+ :mod:`!optparse` expands ``%prog`` in the usage string to the name of the
current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
is then printed before the detailed option help.
- If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
+ If you don't supply a usage string, :mod:`!optparse` uses a bland but sensible
default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
take any positional arguments.
* every option defines a help string, and doesn't worry about
- line-wrapping---\ :mod:`optparse` takes care of wrapping lines and making
+ line-wrapping---\ :mod:`!optparse` takes care of wrapping lines and making
the help output look good.
* options that take a value indicate this fact in their automatically generated
Here, "MODE" is called the meta-variable: it stands for the argument that the
user is expected to supply to ``-m``/``--mode``. By default,
- :mod:`optparse` converts the destination variable name to uppercase and uses
+ :mod:`!optparse` converts the destination variable name to uppercase and uses
that for the meta-variable. Sometimes, that's not what you want---for
example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
resulting in this automatically generated option description::
way to make your help text a lot clearer and more useful for end users.
* options that have a default value can include ``%default`` in the help
- string---\ :mod:`optparse` will replace it with :func:`str` of the option's
+ string---\ :mod:`!optparse` will replace it with :func:`str` of the option's
default value. If an option has no default value (or the default value is
``None``), ``%default`` expands to ``none``.
Printing a version string
^^^^^^^^^^^^^^^^^^^^^^^^^
-Similar to the brief usage string, :mod:`optparse` can also print a version
+Similar to the brief usage string, :mod:`!optparse` can also print a version
string for your program. You have to supply the string as the ``version``
argument to OptionParser::
parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
``%prog`` is expanded just like it is in ``usage``. Apart from that,
-``version`` can contain anything you like. When you supply it, :mod:`optparse`
+``version`` can contain anything you like. When you supply it, :mod:`!optparse`
automatically adds a ``--version`` option to your parser. If it encounters
this option on the command line, it expands your ``version`` string (by
replacing ``%prog``), prints it to stdout, and exits.
.. _optparse-how-optparse-handles-errors:
-How :mod:`optparse` handles errors
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+How :mod:`!optparse` handles errors
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-There are two broad classes of errors that :mod:`optparse` has to worry about:
+There are two broad classes of errors that :mod:`!optparse` has to worry about:
programmer errors and user errors. Programmer errors are usually erroneous
calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
option attributes, missing option attributes, etc. These are dealt with in the
:exc:`TypeError`) and let the program crash.
Handling user errors is much more important, since they are guaranteed to happen
-no matter how stable your code is. :mod:`optparse` can automatically detect
+no matter how stable your code is. :mod:`!optparse` can automatically detect
some user errors, such as bad option arguments (passing ``-n 4x`` where
``-n`` takes an integer argument), missing arguments (``-n`` at the end
of the command line, where ``-n`` takes an argument of any type). Also,
if options.a and options.b:
parser.error("options -a and -b are mutually exclusive")
-In either case, :mod:`optparse` handles the error the same way: it prints the
+In either case, :mod:`!optparse` handles the error the same way: it prints the
program's usage message and an error message to standard error and exits with
error status 2.
foo: error: -n option requires an argument
-:mod:`optparse`\ -generated error messages take care always to mention the
+:mod:`!optparse`\ -generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
:func:`OptionParser.error` from your application code.
-If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
+If :mod:`!optparse`'s default error-handling behaviour does not suit your needs,
you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
and/or :meth:`~OptionParser.error` methods.
Putting it all together
^^^^^^^^^^^^^^^^^^^^^^^
-Here's what :mod:`optparse`\ -based scripts usually look like::
+Here's what :mod:`!optparse`\ -based scripts usually look like::
from optparse import OptionParser
...
Creating the parser
^^^^^^^^^^^^^^^^^^^
-The first step in using :mod:`optparse` is to create an OptionParser instance.
+The first step in using :mod:`!optparse` is to create an OptionParser instance.
.. class:: OptionParser(...)
``usage`` (default: ``"%prog [options]"``)
The usage summary to print when your program is run incorrectly or with a
- help option. When :mod:`optparse` prints the usage string, it expands
+ help option. When :mod:`!optparse` prints the usage string, it expands
``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
passed that keyword argument). To suppress a usage message, pass the
special value :const:`optparse.SUPPRESS_USAGE`.
``version`` (default: ``None``)
A version string to print when the user supplies a version option. If you
- supply a true value for ``version``, :mod:`optparse` automatically adds a
+ supply a true value for ``version``, :mod:`!optparse` automatically adds a
version option with the single option string ``--version``. The
substring ``%prog`` is expanded the same as for ``usage``.
``description`` (default: ``None``)
A paragraph of text giving a brief overview of your program.
- :mod:`optparse` reformats this paragraph to fit the current terminal width
+ :mod:`!optparse` reformats this paragraph to fit the current terminal width
and prints it when the user requests help (after ``usage``, but before the
list of options).
``formatter`` (default: a new :class:`IndentedHelpFormatter`)
An instance of optparse.HelpFormatter that will be used for printing help
- text. :mod:`optparse` provides two concrete classes for this purpose:
+ text. :mod:`!optparse` provides two concrete classes for this purpose:
IndentedHelpFormatter and TitledHelpFormatter.
``add_help_option`` (default: ``True``)
- If true, :mod:`optparse` will add a help option (with option strings ``-h``
+ If true, :mod:`!optparse` will add a help option (with option strings ``-h``
and ``--help``) to the parser.
``prog``
(:func:`make_option` is a factory function for creating Option instances;
currently it is an alias for the Option constructor. A future version of
-:mod:`optparse` may split Option into several classes, and :func:`make_option`
+:mod:`!optparse` may split Option into several classes, and :func:`make_option`
will pick the right class to instantiate. Do not instantiate Option directly.)
The keyword arguments define attributes of the new Option object. The most
important option attribute is :attr:`~Option.action`, and it largely
determines which other attributes are relevant or required. If you pass
- irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
+ irrelevant option attributes, or fail to pass required ones, :mod:`!optparse`
raises an :exc:`OptionError` exception explaining your mistake.
- An option's *action* determines what :mod:`optparse` does when it encounters
+ An option's *action* determines what :mod:`!optparse` does when it encounters
this option on the command-line. The standard option actions hard-coded into
- :mod:`optparse` are:
+ :mod:`!optparse` are:
``"store"``
store this option's argument (default)
attributes; see :ref:`optparse-standard-option-actions`.)
As you can see, most actions involve storing or updating a value somewhere.
-:mod:`optparse` always creates a special object for this, conventionally called
+:mod:`!optparse` always creates a special object for this, conventionally called
``options``, which is an instance of :class:`optparse.Values`.
.. class:: Values
parser.parse_args()
-one of the first things :mod:`optparse` does is create the ``options`` object::
+one of the first things :mod:`!optparse` does is create the ``options`` object::
options = Values()
--file=foo
--file foo
-then :mod:`optparse`, on seeing this option, will do the equivalent of ::
+then :mod:`!optparse`, on seeing this option, will do the equivalent of ::
options.filename = "foo"
The following option attributes may be passed as keyword arguments to
:meth:`OptionParser.add_option`. If you pass an option attribute that is not
relevant to a particular option, or fail to pass a required option attribute,
-:mod:`optparse` raises :exc:`OptionError`.
+:mod:`!optparse` raises :exc:`OptionError`.
.. attribute:: Option.action
(default: ``"store"``)
- Determines :mod:`optparse`'s behaviour when this option is seen on the
+ Determines :mod:`!optparse`'s behaviour when this option is seen on the
command line; the available options are documented :ref:`here
<optparse-standard-option-actions>`.
(default: derived from option strings)
If the option's action implies writing or modifying a value somewhere, this
- tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
- attribute of the ``options`` object that :mod:`optparse` builds as it parses
+ tells :mod:`!optparse` where to write it: :attr:`~Option.dest` names an
+ attribute of the ``options`` object that :mod:`!optparse` builds as it parses
the command line.
.. attribute:: Option.default
(default: 1)
How many arguments of type :attr:`~Option.type` should be consumed when this
- option is seen. If > 1, :mod:`optparse` will store a tuple of values to
+ option is seen. If > 1, :mod:`!optparse` will store a tuple of values to
:attr:`~Option.dest`.
.. attribute:: Option.const
The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
-guide :mod:`optparse`'s behaviour; a few have required attributes, which you
+guide :mod:`!optparse`'s behaviour; a few have required attributes, which you
must specify for any option using that action.
* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
- If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
+ If :attr:`~Option.dest` is not supplied, :mod:`!optparse` derives a destination
from the first long option string (e.g., ``--foo-bar`` implies
- ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
+ ``foo_bar``). If there are no long option strings, :mod:`!optparse` derives a
destination from the first short option string (e.g., ``-f`` implies ``f``).
Example::
-f foo.txt -p 1 -3.5 4 -fbar.txt
- :mod:`optparse` will set ::
+ :mod:`!optparse` will set ::
options.f = "foo.txt"
options.point = (1.0, -3.5, 4.0)
parser.add_option("--noisy",
action="store_const", const=2, dest="verbose")
- If ``--noisy`` is seen, :mod:`optparse` will set ::
+ If ``--noisy`` is seen, :mod:`!optparse` will set ::
options.verbose = 2
The option must be followed by an argument, which is appended to the list in
:attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
- supplied, an empty list is automatically created when :mod:`optparse` first
+ supplied, an empty list is automatically created when :mod:`!optparse` first
encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
is appended to :attr:`~Option.dest`.
parser.add_option("-t", "--tracks", action="append", type="int")
- If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
+ If ``-t3`` is seen on the command-line, :mod:`!optparse` does the equivalent
of::
options.tracks = []
parser.add_option("-v", action="count", dest="verbosity")
- The first time ``-v`` is seen on the command line, :mod:`optparse` does the
+ The first time ``-v`` is seen on the command line, :mod:`!optparse` does the
equivalent of::
options.verbosity = 0
listed in the help message. To omit an option entirely, use the special value
:const:`optparse.SUPPRESS_HELP`.
- :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
+ :mod:`!optparse` automatically adds a :attr:`~Option.help` option to all
OptionParsers, so you do not normally need to create one.
Example::
help="Input file to read data from")
parser.add_option("--secret", help=SUPPRESS_HELP)
- If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
+ If :mod:`!optparse` sees either ``-h`` or ``--help`` on the command line,
it will print something like the following help message to stdout (assuming
``sys.argv[0]`` is ``"foo.py"``):
-v Be moderately verbose
--file=FILENAME Input file to read data from
- After printing the help message, :mod:`optparse` terminates your process with
+ After printing the help message, :mod:`!optparse` terminates your process with
``sys.exit(0)``.
* ``"version"``
``print_version()`` method of OptionParser. Generally only relevant if the
``version`` argument is supplied to the OptionParser constructor. As with
:attr:`~Option.help` options, you will rarely create ``version`` options,
- since :mod:`optparse` automatically adds them when needed.
+ since :mod:`!optparse` automatically adds them when needed.
.. _optparse-standard-option-types:
Standard option types
^^^^^^^^^^^^^^^^^^^^^
-:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
+:mod:`!optparse` has five built-in option types: ``"string"``, ``"int"``,
``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
option types, see section :ref:`optparse-extending-optparse`.
The conversion is done by calling :func:`int` with the appropriate base (2, 8,
-10, or 16). If this fails, so will :mod:`optparse`, although with a more useful
+10, or 16). If this fails, so will :mod:`!optparse`, although with a more useful
error message.
``"float"`` and ``"complex"`` option arguments are converted directly with
``options``
the same object that was passed in as *values*, or the ``optparse.Values``
- instance created by :mod:`optparse`
+ instance created by :mod:`!optparse`
``args``
the leftover positional arguments after all options have been processed
.. method:: OptionParser.disable_interspersed_args()
Set parsing to stop on the first non-option. For example, if ``-a`` and
- ``-b`` are both simple options that take no arguments, :mod:`optparse`
+ ``-b`` are both simple options that take no arguments, :mod:`!optparse`
normally accepts this syntax::
prog -a arg1 -b arg2
(This is particularly true if you've defined your own OptionParser subclass with
some standard options.)
-Every time you add an option, :mod:`optparse` checks for conflicts with existing
+Every time you add an option, :mod:`!optparse` checks for conflicts with existing
options. If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor::
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")
-At this point, :mod:`optparse` detects that a previously added option is already
+At this point, :mod:`!optparse` detects that a previously added option is already
using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
it resolves the situation by removing ``-n`` from the earlier option's list of
option strings. Now ``--dry-run`` is the only way for the user to activate
It's possible to whittle away the option strings for a previously added option
until there are none left, and the user has no way of invoking that option from
-the command-line. In that case, :mod:`optparse` removes that option completely,
+the command-line. In that case, :mod:`!optparse` removes that option completely,
so it doesn't show up in help text or anywhere else. Carrying on with our
existing OptionParser::
parser.add_option("--dry-run", ..., help="new dry-run option")
At this point, the original ``-n``/``--dry-run`` option is no longer
-accessible, so :mod:`optparse` removes it, leaving this help text::
+accessible, so :mod:`!optparse` removes it, leaving this help text::
Options:
...
Option Callbacks
----------------
-When :mod:`optparse`'s built-in actions and types aren't quite enough for your
-needs, you have two choices: extend :mod:`optparse` or define a callback option.
-Extending :mod:`optparse` is more general, but overkill for a lot of simple
+When :mod:`!optparse`'s built-in actions and types aren't quite enough for your
+needs, you have two choices: extend :mod:`!optparse` or define a callback option.
+Extending :mod:`!optparse` is more general, but overkill for a lot of simple
cases. Quite often a simple callback is all you need.
There are two steps to defining a callback option:
``callback`` is a function (or other callable object), so you must have already
defined ``my_callback()`` when you create this callback option. In this simple
-case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
+case, :mod:`!optparse` doesn't even know if ``-c`` takes any arguments,
which usually means that the option takes no arguments---the mere presence of
``-c`` on the command-line is all it needs to know. In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments. This is where writing callbacks gets tricky;
it's covered later in this section.
-:mod:`optparse` always passes four particular arguments to your callback, and it
+:mod:`!optparse` always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via
:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
minimal callback function signature is::
:attr:`~Option.type`
has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
- instructs :mod:`optparse` to consume one argument and convert it to
+ instructs :mod:`!optparse` to consume one argument and convert it to
:attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
- though, :mod:`optparse` passes it to your callback function.
+ though, :mod:`!optparse` passes it to your callback function.
:attr:`~Option.nargs`
- also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
+ also has its usual meaning: if it is supplied and > 1, :mod:`!optparse` will
consume :attr:`~Option.nargs` arguments, each of which must be convertible to
:attr:`~Option.type`. It then passes a tuple of converted values to your
callback.
``"--foobar"``.)
``value``
- is the argument to this option seen on the command-line. :mod:`optparse` will
+ is the argument to this option seen on the command-line. :mod:`!optparse` will
only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
the type implied by the option's type. If :attr:`~Option.type` for this option is
``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
``parser.values``
the object where option values are by default stored (an instance of
optparse.OptionValues). This lets callbacks use the same mechanism as the
- rest of :mod:`optparse` for storing option values; you don't need to mess
+ rest of :mod:`!optparse` for storing option values; you don't need to mess
around with globals or closures. You can also access or modify the
value(s) of any options already encountered on the command-line.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The callback function should raise :exc:`OptionValueError` if there are any
-problems with the option or its argument(s). :mod:`optparse` catches this and
+problems with the option or its argument(s). :mod:`!optparse` catches this and
terminates the program, printing the error message you supply to stderr. Your
message should be clear, concise, accurate, and mention the option at fault.
Otherwise, the user will have a hard time figuring out what they did wrong.
action="callback", callback=store_value,
type="int", nargs=3, dest="foo")
-Note that :mod:`optparse` takes care of consuming 3 arguments and converting
+Note that :mod:`!optparse` takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them. (Or whatever;
obviously you don't need a callback for this example.)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Things get hairy when you want an option to take a variable number of arguments.
-For this case, you must write a callback, as :mod:`optparse` doesn't provide any
+For this case, you must write a callback, as :mod:`!optparse` doesn't provide any
built-in capabilities for it. And you have to deal with certain intricacies of
-conventional Unix command-line parsing that :mod:`optparse` normally handles for
+conventional Unix command-line parsing that :mod:`!optparse` normally handles for
you. In particular, callbacks should implement the conventional rules for bare
``--`` and ``-`` arguments:
If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about. The exact implementation you
choose will be based on which trade-offs you're willing to make for your
-application (which is why :mod:`optparse` doesn't support this sort of thing
+application (which is why :mod:`!optparse` doesn't support this sort of thing
directly).
Nevertheless, here's a stab at a callback for an option with variable
.. _optparse-extending-optparse:
-Extending :mod:`optparse`
--------------------------
+Extending :mod:`!optparse`
+--------------------------
-Since the two major controlling factors in how :mod:`optparse` interprets
+Since the two major controlling factors in how :mod:`!optparse` interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.
Adding new types
^^^^^^^^^^^^^^^^
-To add new types, you need to define your own subclass of :mod:`optparse`'s
+To add new types, you need to define your own subclass of :mod:`!optparse`'s
:class:`Option` class. This class has a couple of attributes that define
-:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
+:mod:`!optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
.. attribute:: Option.TYPES
Here's a silly example that demonstrates adding a ``"complex"`` option type to
parse Python-style complex numbers on the command line. (This is even sillier
-than it used to be, because :mod:`optparse` 1.3 added built-in support for
+than it used to be, because :mod:`!optparse` 1.3 added built-in support for
complex numbers, but never mind.)
First, the necessary imports::
TYPE_CHECKER["complex"] = check_complex
(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
-up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
+up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`!optparse`'s
Option class. This being Python, nothing stops you from doing that except good
manners and common sense.)
That's it! Now you can write a script that uses the new option type just like
-any other :mod:`optparse`\ -based script, except you have to instruct your
+any other :mod:`!optparse`\ -based script, except you have to instruct your
OptionParser to use MyOption instead of Option::
parser = OptionParser(option_class=MyOption)
^^^^^^^^^^^^^^^^^^
Adding new actions is a bit trickier, because you have to understand that
-:mod:`optparse` has a couple of classifications for actions:
+:mod:`!optparse` has a couple of classifications for actions:
"store" actions
- actions that result in :mod:`optparse` storing a value to an attribute of the
+ actions that result in :mod:`!optparse` storing a value to an attribute of the
current OptionValues instance; these options require a :attr:`~Option.dest`
attribute to be supplied to the Option constructor.
.. attribute:: Option.ALWAYS_TYPED_ACTIONS
Actions that always take a type (i.e. whose options always take a value) are
- additionally listed here. The only effect of this is that :mod:`optparse`
+ additionally listed here. The only effect of this is that :mod:`!optparse`
assigns the default type, ``"string"``, to options with no explicit type
whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
:attr:`~Option.TYPED_ACTIONS`.
-* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
+* to ensure that :mod:`!optparse` assigns the default type of ``"string"`` to
``"extend"`` actions, we put the ``"extend"`` action in
:attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
* :meth:`MyOption.take_action` implements just this one new action, and passes
- control back to :meth:`Option.take_action` for the standard :mod:`optparse`
+ control back to :meth:`Option.take_action` for the standard :mod:`!optparse`
actions.
* ``values`` is an instance of the optparse_parser.Values class, which provides
Since different operating systems have different path name conventions, there
are several versions of this module in the standard library. The
- :mod:`os.path` module is always the path module suitable for the operating
+ :mod:`!os.path` module is always the path module suitable for the operating
system Python is running on, and therefore usable for local paths. However,
you can also import and use the individual modules if you want to manipulate
a path that is *always* in one of the different formats. They all have the
with the POSIX interface).
* Extensions peculiar to a particular operating system are also available
- through the :mod:`os` module, but using them is of course a threat to
+ through the :mod:`!os` module, but using them is of course a threat to
portability.
* All functions accepting path or file names accept both bytes and string
* On VxWorks, os.popen, os.fork, os.execv and os.spawn*p* are not supported.
-* On WebAssembly platforms, Android and iOS, large parts of the :mod:`os` module are
+* On WebAssembly platforms, Android and iOS, large parts of the :mod:`!os` module are
not available or behave differently. APIs related to processes (e.g.
:func:`~os.fork`, :func:`~os.execve`) and resources (e.g. :func:`~os.nice`)
are not available. Others like :func:`~os.getuid` and :func:`~os.getpid` are
of your home directory (on some platforms), and is equivalent to
``getenv("HOME")`` in C.
- This mapping is captured the first time the :mod:`os` module is imported,
+ This mapping is captured the first time the :mod:`!os` module is imported,
typically during Python startup as part of processing :file:`site.py`. Changes
to the environment made after this time are not reflected in :data:`os.environ`,
except for changes made by modifying :data:`os.environ` directly.
For a description of the flag and mode values, see the C run-time documentation;
flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
- the :mod:`os` module. In particular, on Windows adding
+ the :mod:`!os` module. In particular, on Windows adding
:const:`O_BINARY` is needed to open files in binary mode.
This function can support :ref:`paths relative to directory descriptors
.. _path_fd:
* **specifying a file descriptor:**
- Normally the *path* argument provided to functions in the :mod:`os` module
+ Normally the *path* argument provided to functions in the :mod:`!os` module
must be a string specifying a file path. However, some functions now
alternatively accept an open file descriptor for their *path* argument.
The function will then operate on the file referred to by the descriptor.
.. data:: supports_dir_fd
- A :class:`set` object indicating which functions in the :mod:`os`
+ A :class:`set` object indicating which functions in the :mod:`!os`
module accept an open file descriptor for their *dir_fd* parameter.
Different platforms provide different features, and the underlying
functionality Python uses to implement the *dir_fd* parameter is not
.. data:: supports_fd
A :class:`set` object indicating which functions in the
- :mod:`os` module permit specifying their *path* parameter as an open file
+ :mod:`!os` module permit specifying their *path* parameter as an open file
descriptor on the local platform. Different platforms provide different
features, and the underlying functionality Python uses to accept open file
descriptors as *path* arguments is not available on all platforms Python
.. data:: supports_follow_symlinks
- A :class:`set` object indicating which functions in the :mod:`os` module
+ A :class:`set` object indicating which functions in the :mod:`!os` module
accept ``False`` for their *follow_symlinks* parameter on the local platform.
Different platforms provide different features, and the underlying
functionality Python uses to implement *follow_symlinks* is not available
:class:`PurePath`/:class:`Path` equivalent.
===================================== ==============================================
-:mod:`os` and :mod:`os.path` :mod:`pathlib`
+:mod:`os` and :mod:`os.path` :mod:`!pathlib`
===================================== ==============================================
:func:`os.path.dirname` :attr:`PurePath.parent`
:func:`os.path.basename` :attr:`PurePath.name`
--------------
-The :mod:`pickle` module implements binary protocols for serializing and
+The :mod:`!pickle` module implements binary protocols for serializing and
de-serializing a Python object structure. *"Pickling"* is the process
whereby a Python object hierarchy is converted into a byte stream, and
*"unpickling"* is the inverse operation, whereby a byte stream
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Python has a more primitive serialization module called :mod:`marshal`, but in
-general :mod:`pickle` should always be the preferred way to serialize Python
+general :mod:`!pickle` should always be the preferred way to serialize Python
objects. :mod:`marshal` exists primarily to support Python's :file:`.pyc`
files.
-The :mod:`pickle` module differs from :mod:`marshal` in several significant ways:
+The :mod:`!pickle` module differs from :mod:`marshal` in several significant ways:
* :mod:`marshal` cannot be used to serialize user-defined classes and their
- instances. :mod:`pickle` can save and restore class instances transparently,
+ instances. :mod:`!pickle` can save and restore class instances transparently,
however the class definition must be importable and live in the same module as
when the object was stored.
across Python versions. Because its primary job in life is to support
:file:`.pyc` files, the Python implementers reserve the right to change the
serialization format in non-backwards compatible ways should the need arise.
- The :mod:`pickle` serialization format is guaranteed to be backwards compatible
+ The :mod:`!pickle` serialization format is guaranteed to be backwards compatible
across Python releases provided a compatible pickle protocol is chosen and
pickling and unpickling code deals with Python 2 to Python 3 type differences
if your data is crossing that unique breaking change language boundary.
.. index::
single: External Data Representation
-The data format used by :mod:`pickle` is Python-specific. This has the
+The data format used by :mod:`!pickle` is Python-specific. This has the
advantage that there are no restrictions imposed by external standards such as
JSON (which can't represent pointer sharing); however it means that
non-Python programs may not be able to reconstruct pickled Python objects.
-By default, the :mod:`pickle` data format uses a relatively compact binary
+By default, the :mod:`!pickle` data format uses a relatively compact binary
representation. If you need optimal size characteristics, you can efficiently
:doc:`compress <archiving>` pickled data.
The module :mod:`pickletools` contains tools for analyzing data streams
-generated by :mod:`pickle`. :mod:`pickletools` source code has extensive
+generated by :mod:`!pickle`. :mod:`pickletools` source code has extensive
comments about opcodes used by pickle protocols.
There are currently 6 different protocols which can be used for pickling.
.. note::
Serialization is a more primitive notion than persistence; although
- :mod:`pickle` reads and writes file objects, it does not handle the issue of
+ :mod:`!pickle` reads and writes file objects, it does not handle the issue of
naming persistent objects, nor the (even more complicated) issue of concurrent
- access to persistent objects. The :mod:`pickle` module can transform a complex
+ access to persistent objects. The :mod:`!pickle` module can transform a complex
object into a byte stream and it can transform the byte stream into an object
with the same internal structure. Perhaps the most obvious thing to do with
these byte streams is to write them onto a file, but it is also conceivable to
However, if you want more control over serialization and de-serialization,
you can create a :class:`Pickler` or an :class:`Unpickler` object, respectively.
-The :mod:`pickle` module provides the following constants:
+The :mod:`!pickle` module provides the following constants:
.. data:: HIGHEST_PROTOCOL
The default protocol is 5.
-The :mod:`pickle` module provides the following functions to make the pickling
+The :mod:`!pickle` module provides the following functions to make the pickling
process more convenient:
.. function:: dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)
The *buffers* argument was added.
-The :mod:`pickle` module defines three exceptions:
+The :mod:`!pickle` module defines three exceptions:
.. exception:: PickleError
IndexError.
-The :mod:`pickle` module exports three classes, :class:`Pickler`,
+The :mod:`!pickle` module exports three classes, :class:`Pickler`,
:class:`Unpickler` and :class:`PickleBuffer`:
.. class:: Pickler(file, protocol=None, *, fix_imports=True, buffer_callback=None)
single: persistent_id (pickle protocol)
single: persistent_load (pickle protocol)
-For the benefit of object persistence, the :mod:`pickle` module supports the
+For the benefit of object persistence, the :mod:`!pickle` module supports the
notion of a reference to an object outside the pickled data stream. Such
objects are referenced by a persistent ID, which should be either a string of
alphanumeric characters (for protocol 0) [#]_ or just an arbitrary object (for
any newer protocol).
-The resolution of such persistent IDs is not defined by the :mod:`pickle`
+The resolution of such persistent IDs is not defined by the :mod:`!pickle`
module; it will delegate this resolution to the user-defined methods on the
pickler and unpickler, :meth:`~Pickler.persistent_id` and
:meth:`~Unpickler.persistent_load` respectively.
.. versionadded:: 3.8
-In some contexts, the :mod:`pickle` module is used to transfer massive amounts
+In some contexts, the :mod:`!pickle` module is used to transfer massive amounts
of data. Therefore, it can be important to minimize the number of memory
copies, to preserve performance and resource consumption. However, normal
-operation of the :mod:`pickle` module, as it transforms a graph-like structure
+operation of the :mod:`!pickle` module, as it transforms a graph-like structure
of objects into a sequential stream of bytes, intrinsically involves copying
data to and from the pickle stream.
A :class:`PickleBuffer` object *signals* that the underlying buffer is
eligible for out-of-band data transfer. Those objects remain compatible
-with normal usage of the :mod:`pickle` module. However, consumers can also
-opt-in to tell :mod:`pickle` that they will handle those buffers by
+with normal usage of the :mod:`!pickle` module. However, consumers can also
+opt-in to tell :mod:`!pickle` that they will handle those buffers by
themselves.
Consumer API
Recent versions of the pickle protocol (from protocol 2 and upwards) feature
efficient binary encodings for several common features and built-in types.
-Also, the :mod:`pickle` module has a transparent optimizer written in C.
+Also, the :mod:`!pickle` module has a transparent optimizer written in C.
.. _pickle-example:
Command-line interface
----------------------
-The :mod:`pickle` module can be invoked as a script from the command line,
+The :mod:`!pickle` module can be invoked as a script from the command line,
it will display contents of the pickle files. However, when the pickle file
that you want to examine comes from an untrusted source, ``-m pickletools``
is a safer option because it does not execute pickle bytecode, see
Tools for working with and analyzing pickled data.
Module :mod:`shelve`
- Indexed databases of objects; uses :mod:`pickle`.
+ Indexed databases of objects; uses :mod:`!pickle`.
Module :mod:`copy`
Shallow and deep object copying.
few useful functions for analyzing pickled data. The contents of this module
are useful for Python core developers who are working on the :mod:`pickle`;
ordinary users of the :mod:`pickle` module probably won't find the
-:mod:`pickletools` module relevant.
+:mod:`!pickletools` module relevant.
.. _pickletools-cli:
Command-line usage
------------------
-:mod:`platform` can also be invoked directly using the :option:`-m`
+:mod:`!platform` can also be invoked directly using the :option:`-m`
switch of the interpreter::
python -m platform [--terse] [--nonaliased] [{nonaliased,terse} ...]
.. include:: ../includes/wasm-notavail.rst
-The :mod:`poplib` module provides two classes:
+The :mod:`!poplib` module provides two classes:
.. class:: POP3(host, port=POP3_PORT[, timeout])
.. versionchanged:: 3.12
The deprecated *keyfile* and *certfile* parameters have been removed.
-One exception is defined as an attribute of the :mod:`poplib` module:
+One exception is defined as an attribute of the :mod:`!poplib` module:
.. exception:: error_proto
**Do not import this module directly.** Instead, import the module :mod:`os`,
which provides a *portable* version of this interface. On Unix, the :mod:`os`
-module provides a superset of the :mod:`posix` interface. On non-Unix operating
-systems the :mod:`posix` module is not available, but a subset is always
+module provides a superset of the :mod:`!posix` interface. On non-Unix operating
+systems the :mod:`!posix` module is not available, but a subset is always
available through the :mod:`os` interface. Once :mod:`os` is imported, there is
-*no* performance penalty in using it instead of :mod:`posix`. In addition,
+*no* performance penalty in using it instead of :mod:`!posix`. In addition,
:mod:`os` provides some additional functionality, such as automatically calling
:func:`~os.putenv` when an entry in ``os.environ`` is changed.
-----------------------
In addition to many functions described in the :mod:`os` module documentation,
-:mod:`posix` defines the following data item:
+:mod:`!posix` defines the following data item:
.. data:: environ
which updates the environment on modification. Note also that updating
:data:`os.environ` will render this dictionary obsolete. Use of the
:mod:`os` module version of this is recommended over direct access to the
- :mod:`posix` module.
+ :mod:`!posix` module.
--------------
-The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
+The :mod:`!pprint` module provides a capability to "pretty-print" arbitrary
Python data structures in a form which can be used as input to the interpreter.
If the formatted structures include objects which are not fundamental Python
types, the representation may not be loadable. This may be the case if objects
--------------
-The :mod:`pty` module defines operations for handling the pseudo-terminal
+The :mod:`!pty` module defines operations for handling the pseudo-terminal
concept: starting another process and being able to write to and read from its
controlling terminal programmatically.
tested on Linux, FreeBSD, and macOS (it is supposed to work on other POSIX
platforms but it's not been thoroughly tested).
-The :mod:`pty` module defines the following functions:
+The :mod:`!pty` module defines the following functions:
.. function:: fork()
--------------
-The :mod:`py_compile` module provides a function to generate a byte-code file
+The :mod:`!py_compile` module provides a function to generate a byte-code file
from a source file, and another function used when the module source file is
invoked as a script.
--------------
-The :mod:`pyclbr` module provides limited information about the
+The :mod:`!pyclbr` module provides limited information about the
functions, classes, and methods defined in a Python-coded module. The
information is sufficient to implement a module browser. The
information is extracted from the Python source code rather than by
.. index:: single: Expat
-The :mod:`xml.parsers.expat` module is a Python interface to the Expat
+The :mod:`!xml.parsers.expat` module is a Python interface to the Expat
non-validating XML parser. The module provides a single extension type,
:class:`xmlparser`, that represents the current state of an XML parser. After
an :class:`xmlparser` object has been created, various attributes of the object
The type of the return values from the :func:`ParserCreate` function.
-The :mod:`xml.parsers.expat` module contains two functions:
+The :mod:`!xml.parsers.expat` module contains two functions:
.. function:: ErrorString(errno)
An operation was requested that requires DTD support to be compiled in, but
Expat was configured without DTD support. This should never be reported by a
- standard build of the :mod:`xml.parsers.expat` module.
+ standard build of the :mod:`!xml.parsers.expat` module.
.. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
--------------
-The :mod:`queue` module implements multi-producer, multi-consumer queues.
+The :mod:`!queue` module implements multi-producer, multi-consumer queues.
It is especially useful in threaded programming when information must be
exchanged safely between multiple threads. The :class:`Queue` class in this
module implements all the required locking semantics.
specific implementation provides additional guarantees
in exchange for the smaller functionality.
-The :mod:`queue` module defines the following classes and exceptions:
+The :mod:`!queue` module defines the following classes and exceptions:
.. class:: Queue(maxsize=0)
basic generator of your own devising: see the documentation on that class for
more details.
-The :mod:`random` module also provides the :class:`SystemRandom` class which
+The :mod:`!random` module also provides the :class:`SystemRandom` class which
uses the system function :func:`os.urandom` to generate random numbers
from sources provided by the operating system.
.. class:: Random([seed])
Class that implements the default pseudo-random number generator used by the
- :mod:`random` module.
+ :mod:`!random` module.
.. versionchanged:: 3.11
Formerly the *seed* could be any hashable object. Now it is limited to:
.. seealso::
The third-party :pypi:`regex` module,
- which has an API compatible with the standard library :mod:`re` module,
+ which has an API compatible with the standard library :mod:`!re` module,
but offers additional functionality and a more thorough Unicode support.
--------------
-The :mod:`readline` module defines a number of functions to facilitate
+The :mod:`!readline` module defines a number of functions to facilitate
completion and reading/writing of history files from the Python interpreter.
This module can be used directly, or via the :mod:`rlcompleter` module, which
supports completion of Python identifiers at the interactive prompt. Settings
The underlying Readline library API may be implemented by
the ``editline`` (``libedit``) library instead of GNU readline.
- On macOS the :mod:`readline` module detects which library is being used
+ On macOS the :mod:`!readline` module detects which library is being used
at run time.
The configuration file for ``editline`` is different from that
function. This is typically operated by the Tab key, and can suggest and
automatically complete a word being typed. By default, Readline is set up
to be used by :mod:`rlcompleter` to complete Python identifiers for
-the interactive interpreter. If the :mod:`readline` module is to be used
+the interactive interpreter. If the :mod:`!readline` module is to be used
with a custom completer, a different set of word delimiters should be set.
Example
-------
-The following example demonstrates how to use the :mod:`readline` module's
+The following example demonstrates how to use the :mod:`!readline` module's
history reading and writing functions to automatically load and save a history
file named :file:`.python_history` from the user's home directory. The code
below would normally be executed automatically during interactive sessions
--------------
-The :mod:`runpy` module is used to locate and run Python modules without
+The :mod:`!runpy` module is used to locate and run Python modules without
importing them first. Its main use is to implement the :option:`-m` command
line switch that allows scripts to be located using the Python module
namespace rather than the filesystem.
modules) will remain in place after the functions have returned.
Furthermore, any functions and classes defined by the executed code are not
-guaranteed to work correctly after a :mod:`runpy` function has returned.
+guaranteed to work correctly after a :mod:`!runpy` function has returned.
If that limitation is not acceptable for a given use case, :mod:`importlib`
is likely to be a more suitable choice than this module.
-The :mod:`runpy` module provides two functions:
+The :mod:`!runpy` module provides two functions:
.. function:: run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)
--------------
-The :mod:`sched` module defines a class which implements a general purpose event
+The :mod:`!sched` module defines a class which implements a general purpose event
scheduler:
.. class:: scheduler(timefunc=time.monotonic, delayfunc=time.sleep)
-------------
-The :mod:`secrets` module is used for generating cryptographically strong
+The :mod:`!secrets` module is used for generating cryptographically strong
random numbers suitable for managing data such as passwords, account
authentication, security tokens, and related secrets.
-In particular, :mod:`secrets` should be used in preference to the
+In particular, :mod:`!secrets` should be used in preference to the
default pseudo-random number generator in the :mod:`random` module, which
is designed for modelling and simulation, not security or cryptography.
Random numbers
--------------
-The :mod:`secrets` module provides access to the most secure source of
+The :mod:`!secrets` module provides access to the most secure source of
randomness that your operating system provides.
.. class:: SystemRandom
Generating tokens
-----------------
-The :mod:`secrets` module provides functions for generating secure
+The :mod:`!secrets` module provides functions for generating secure
tokens, suitable for applications such as password resets,
hard-to-guess URLs, and similar.
considered sufficient will necessarily increase as computers get more
powerful and able to make more guesses in a shorter period. As of 2015,
it is believed that 32 bytes (256 bits) of randomness is sufficient for
-the typical use-case expected for the :mod:`secrets` module.
+the typical use-case expected for the :mod:`!secrets` module.
For those who want to manage their own token length, you can explicitly
specify how much randomness is used for tokens by giving an :class:`int`
Recipes and best practices
--------------------------
-This section shows recipes and best practices for using :mod:`secrets`
+This section shows recipes and best practices for using :mod:`!secrets`
to manage a basic level of security.
Generate an eight-character alphanumeric password:
.. note::
The :mod:`selectors` module allows high-level and efficient I/O
- multiplexing, built upon the :mod:`select` module primitives. Users are
+ multiplexing, built upon the :mod:`!select` module primitives. Users are
encouraged to use the :mod:`selectors` module instead, unless they want
precise control over the OS-level primitives used.
determine which accessed entries are mutable, nor which ones were actually
mutated).
- By default, :mod:`shelve` uses :func:`pickle.dumps` and :func:`pickle.loads`
+ By default, :mod:`!shelve` uses :func:`pickle.dumps` and :func:`pickle.loads`
for serializing and deserializing. This can be changed by supplying
*serializer* and *deserializer*, respectively.
.. warning::
- Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure
+ Because the :mod:`!shelve` module is backed by :mod:`pickle`, it is insecure
to load a shelf from an untrusted source. Like with pickle, loading a shelf
can execute arbitrary code.
database should be fairly small, and in rare cases key collisions may cause
the database to refuse updates.
-* The :mod:`shelve` module does not support *concurrent* read/write access to
+* The :mod:`!shelve` module does not support *concurrent* read/write access to
shelved objects. (Multiple simultaneous read accesses are safe.) When a
program has a shelf open for writing, no other program should have it open for
reading or writing. Unix file locking can be used to solve this, but this
Generic interface to ``dbm``-style databases.
Module :mod:`pickle`
- Object serialization used by :mod:`shelve`.
+ Object serialization used by :mod:`!shelve`.
for writing minilanguages, (for example, in run control files for Python
applications) or for parsing quoted strings.
-The :mod:`shlex` module defines the following functions:
+The :mod:`!shlex` module defines the following functions:
.. function:: split(s, comments=False, posix=True)
.. versionadded:: 3.3
-The :mod:`shlex` module defines the following class:
+The :mod:`!shlex` module defines the following class:
.. class:: shlex(instream=None, infile=None, posix=False, punctuation_chars=False)
with the name of the current source file and the ``%d`` with the current input
line number (the optional arguments can be used to override these).
- This convenience is provided to encourage :mod:`shlex` users to generate error
+ This convenience is provided to encourage :mod:`!shlex` users to generate error
messages in the standard, parseable format understood by Emacs and other Unix
tools.
--------------
-The :mod:`shutil` module offers a number of high-level operations on files and
+The :mod:`!shutil` module offers a number of high-level operations on files and
collections of files. In particular, functions are provided which support file
copying and removal. For operations on individual files, see also the
:mod:`os` module.
Return a list of supported formats for archiving.
Each element of the returned sequence is a tuple ``(name, description)``.
- By default :mod:`shutil` provides these formats:
+ By default :mod:`!shutil` provides these formats:
- *zip*: ZIP file (if the :mod:`zlib` module is available).
- *tar*: Uncompressed tar file. Uses POSIX.1-2001 pax format for new archives.
Each element of the returned sequence is a tuple
``(name, extensions, description)``.
- By default :mod:`shutil` provides these formats:
+ By default :mod:`!shutil` provides these formats:
- *zip*: ZIP file (unpacking compressed files works only if the corresponding
module is available).
.. versionadded:: 3.5
-The variables defined in the :mod:`signal` module are:
+The variables defined in the :mod:`!signal` module are:
.. data:: SIG_DFL
.. versionadded:: 3.3
-The :mod:`signal` module defines one exception:
+The :mod:`!signal` module defines one exception:
.. exception:: ItimerError
alias of :exc:`OSError`.
-The :mod:`signal` module defines the following functions:
+The :mod:`!signal` module defines the following functions:
.. function:: alarm(time)
.. versionchanged:: 3.14
- :mod:`site` is no longer responsible for updating :data:`sys.prefix` and
+ :mod:`!site` is no longer responsible for updating :data:`sys.prefix` and
:data:`sys.exec_prefix` on :ref:`sys-path-init-virtual-environments`. This is
now done during the :ref:`path initialization <sys-path-init>`. As a result,
under :ref:`sys-path-init-virtual-environments`, :data:`sys.prefix` and
- :data:`sys.exec_prefix` no longer depend on the :mod:`site` initialization,
+ :data:`sys.exec_prefix` no longer depend on the :mod:`!site` initialization,
and are therefore unaffected by :option:`-S`.
.. _site-virtual-environments-configuration:
.. program:: site
-The :mod:`site` module also provides a way to get the user directories from the
+The :mod:`!site` module also provides a way to get the user directories from the
command line:
.. code-block:: shell-session
--------------
-The :mod:`smtplib` module defines an SMTP client session object that can be used
+The :mod:`!smtplib` module defines an SMTP client session object that can be used
to send mail to any internet machine with an SMTP or ESMTP listener daemon. For
details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
Protocol) and :rfc:`1869` (SMTP Service Extensions).
:exc:`SMTPException`
No suitable authentication method was found.
- Each of the authentication methods supported by :mod:`smtplib` are tried in
+ Each of the authentication methods supported by :mod:`!smtplib` are tried in
turn if they are advertised as supported by the server. See :meth:`auth`
for a list of supported authentication methods. *initial_response_ok* is
passed through to :meth:`auth`.
call the :meth:`login` method, which will try each of the above mechanisms
in turn, in the order listed. ``auth`` is exposed to facilitate the
implementation of authentication methods not (or not yet) supported
- directly by :mod:`smtplib`.
+ directly by :mod:`!smtplib`.
.. versionadded:: 3.5
- For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
scope_id)`` is used, where *flowinfo* and *scope_id* represent the ``sin6_flowinfo``
and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C. For
- :mod:`socket` module methods, *flowinfo* and *scope_id* can be omitted just for
+ :mod:`!socket` module methods, *flowinfo* and *scope_id* can be omitted just for
backward compatibility. Note, however, omission of *scope_id* can cause problems
in manipulating scoped IPv6 addresses.
Module contents
---------------
-The module :mod:`socket` exports the following elements.
+The module :mod:`!socket` exports the following elements.
Exceptions
Other functions
'''''''''''''''
-The :mod:`socket` module also offers various network-related services:
+The :mod:`!socket` module also offers various network-related services:
.. function:: close(fd)
This is because the previous execution has left the socket in a ``TIME_WAIT``
state, and can't be immediately reused.
-There is a :mod:`socket` flag to set, in order to prevent this,
+There is a :mod:`!socket` flag to set, in order to prevent this,
:const:`socket.SO_REUSEADDR`::
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
--------------
-The :mod:`socketserver` module simplifies the task of writing network servers.
+The :mod:`!socketserver` module simplifies the task of writing network servers.
.. include:: ../includes/wasm-notavail.rst
cafile=None, capath=None, cadata=None)
Return a new :class:`SSLContext` object with default settings for
- the given *purpose*. The settings are chosen by the :mod:`ssl` module,
+ the given *purpose*. The settings are chosen by the :mod:`!ssl` module,
and usually represent a higher security level than when calling the
:class:`SSLContext` constructor directly.
TLS 1.3.
.. seealso::
- :func:`create_default_context` lets the :mod:`ssl` module choose
+ :func:`create_default_context` lets the :mod:`!ssl` module choose
security settings for a given purpose.
.. versionchanged:: 3.6
--------------
-The :mod:`stat` module defines constants and functions for interpreting the
+The :mod:`!stat` module defines constants and functions for interpreting the
results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they
exist). For complete details about the :c:func:`stat`, :c:func:`!fstat` and
:c:func:`!lstat` calls, consult the documentation for your system.
.. versionchanged:: 3.4
The stat module is backed by a C implementation.
-The :mod:`stat` module defines the following functions to test for specific file
+The :mod:`!stat` module defines the following functions to test for specific file
types:
The built-in string class provides the ability to do complex variable
substitutions and value formatting via the :meth:`~str.format` method described in
-:pep:`3101`. The :class:`Formatter` class in the :mod:`string` module allows
+:pep:`3101`. The :class:`Formatter` class in the :mod:`!string` module allows
you to create and customize your own string formatting behaviors using the same
implementation as the built-in :meth:`~str.format` method.
Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
being raised.
-The :mod:`string` module provides a :class:`Template` class that implements
+The :mod:`!string` module provides a :class:`Template` class that implements
these rules. The methods of :class:`Template` are:
procedure are part of the profile. One example of a ``stringprep`` profile is
``nameprep``, which is used for internationalized domain names.
-The module :mod:`stringprep` only exposes the tables from :rfc:`3454`. As these
+The module :mod:`!stringprep` only exposes the tables from :rfc:`3454`. As these
tables would be very large to represent as dictionaries or lists, the
module uses the Unicode character database internally. The module source code
itself was generated using the ``mkstringprep.py`` utility.
As a result, these tables are exposed as functions, not as data structures.
There are two kinds of tables in the RFC: sets and mappings. For a set,
-:mod:`stringprep` provides the "characteristic function", i.e. a function that
+:mod:`!stringprep` provides the "characteristic function", i.e. a function that
returns ``True`` if the parameter is part of the set. For mappings, it provides the
mapping function: given the key, it returns the associated value. Below is a
list of all functions available in the module.
responsible for defining byte ordering and padding between elements.
See :ref:`struct-alignment` for details.
-Several :mod:`struct` functions (and methods of :class:`Struct`) take a *buffer*
+Several :mod:`!struct` functions (and methods of :class:`Struct`) take a *buffer*
argument. This refers to objects that implement the :ref:`bufferobjects` and
provide either a readable or read-writable buffer. The most common types used
for that purpose are :class:`bytes` and :class:`bytearray`, but many other types
Applications
------------
-Two main applications for the :mod:`struct` module exist, data
+Two main applications for the :mod:`!struct` module exist, data
interchange between Python and C code within an application or another
application compiled using the same compiler (:ref:`native formats<struct-native-formats>`), and
data interchange between applications using agreed upon data layout
Classes
-------
-The :mod:`struct` module also defines the following type:
+The :mod:`!struct` module also defines the following type:
.. class:: Struct(format)
--------------
-The :mod:`subprocess` module allows you to spawn new processes, connect to their
+The :mod:`!subprocess` module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes. This module intends to
replace several older modules and functions::
os.system
os.spawn*
-Information about how the :mod:`subprocess` module can be used to replace these
+Information about how the :mod:`!subprocess` module can be used to replace these
modules and functions can be found in the following sections.
.. seealso::
.. include:: ../includes/wasm-mobile-notavail.rst
-Using the :mod:`subprocess` Module
-----------------------------------
+Using the :mod:`!subprocess` Module
+-----------------------------------
The recommended approach to invoking subprocesses is to use the :func:`run`
function for all use cases it can handle. For more advanced use cases, the
Windows Constants
^^^^^^^^^^^^^^^^^
-The :mod:`subprocess` module exposes the following constants.
+The :mod:`!subprocess` module exposes the following constants.
.. data:: STD_INPUT_HANDLE
.. _subprocess-replacements:
-Replacing Older Functions with the :mod:`subprocess` Module
------------------------------------------------------------
+Replacing Older Functions with the :mod:`!subprocess` Module
+------------------------------------------------------------
In this section, "a becomes b" means that b can be used as a replacement for a.
:attr:`~CalledProcessError.output` attribute of the raised exception.
In the following examples, we assume that the relevant functions have already
-been imported from the :mod:`subprocess` module.
+been imported from the :mod:`!subprocess` module.
Replacing :program:`/bin/sh` shell command substitution
* The :func:`os.system` function ignores SIGINT and SIGQUIT signals while
the command is running, but the caller must do this separately when
- using the :mod:`subprocess` module.
+ using the :mod:`!subprocess` module.
A more realistic example would look like this::
Disable use of ``posix_spawn()``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-On Linux, :mod:`subprocess` defaults to using the ``vfork()`` system call
+On Linux, :mod:`!subprocess` defaults to using the ``vfork()`` system call
internally when it is safe to do so rather than ``fork()``. This greatly
improves performance.
Symbol tables are generated by the compiler from AST just before bytecode is
generated. The symbol table is responsible for calculating the scope of every
-identifier in the code. :mod:`symtable` provides an interface to examine these
+identifier in the code. :mod:`!symtable` provides an interface to examine these
tables.
.. versionadded:: 3.13
-The :mod:`symtable` module can be executed as a script from the command line.
+The :mod:`!symtable` module can be executed as a script from the command line.
.. code-block:: sh
.. note::
- :mod:`sys.monitoring` is a namespace within the :mod:`sys` module,
+ :mod:`!sys.monitoring` is a namespace within the :mod:`sys` module,
not an independent module, so there is no need to
``import sys.monitoring``, simply ``import sys`` and then use
``sys.monitoring``.
activate and control event monitoring.
As programs execute, events occur that might be of interest to tools that
-monitor execution. The :mod:`sys.monitoring` namespace provides means to
+monitor execution. The :mod:`!sys.monitoring` namespace provides means to
receive callbacks when events of interest occur.
The monitoring API consists of three components:
The version number used to form registry keys on Windows platforms. This is
stored as string resource 1000 in the Python DLL. The value is normally the
- major and minor versions of the running Python interpreter. It is provided in the :mod:`sys`
+ major and minor versions of the running Python interpreter. It is provided in the :mod:`!sys`
module for informational purposes; modifying this value has no effect on the
registry keys used by Python.
--------------
-The :mod:`sysconfig` module provides access to Python's configuration
+The :mod:`!sysconfig` module provides access to Python's configuration
information like the list of installation paths and the configuration variables
relevant for the current platform.
header file that are necessary to build both the Python binary itself and
third-party C extensions compiled using ``setuptools``.
-:mod:`sysconfig` puts all variables found in these files in a dictionary that
+:mod:`!sysconfig` puts all variables found in these files in a dictionary that
can be accessed using :func:`get_config_vars` or :func:`get_config_var`.
Notice that on Windows, it's a much smaller set.
------------------
Python uses an installation scheme that differs depending on the platform and on
-the installation options. These schemes are stored in :mod:`sysconfig` under
+the installation options. These schemes are stored in :mod:`!sysconfig` under
unique identifiers based on the value returned by :const:`os.name`.
The schemes are used by package installers to determine where to copy files to.
Installation path functions
---------------------------
-:mod:`sysconfig` provides some functions to determine these installation paths.
+:mod:`!sysconfig` provides some functions to determine these installation paths.
.. function:: get_scheme_names()
Return a tuple containing all schemes currently supported in
- :mod:`sysconfig`.
+ :mod:`!sysconfig`.
.. function:: get_default_scheme()
*key* must be either ``"prefix"``, ``"home"``, or ``"user"``.
The return value is a scheme name listed in :func:`get_scheme_names`. It
- can be passed to :mod:`sysconfig` functions that take a *scheme* argument,
+ can be passed to :mod:`!sysconfig` functions that take a *scheme* argument,
such as :func:`get_paths`.
.. versionadded:: 3.10
.. function:: get_path_names()
Return a tuple containing all path names currently supported in
- :mod:`sysconfig`.
+ :mod:`!sysconfig`.
.. function:: get_path(name, [scheme, [vars, [expand]]])
*name* has to be a value from the list returned by :func:`get_path_names`.
- :mod:`sysconfig` stores installation paths corresponding to each path name,
+ :mod:`!sysconfig` stores installation paths corresponding to each path name,
for each platform, with variables to be expanded. For instance the *stdlib*
path for the *nt* scheme is: ``{base}/Lib``.
Command-line usage
------------------
-You can use :mod:`sysconfig` as a script with Python's *-m* option:
+You can use :mod:`!sysconfig` as a script with Python's *-m* option:
.. code-block:: shell-session
--------------
-The :mod:`tarfile` module makes it possible to read and write tar
+The :mod:`!tarfile` module makes it possible to read and write tar
archives, including those using gzip, bz2 and lzma compression.
Use the :mod:`zipfile` module to read or write :file:`.zip` files, or the
higher-level functions in :ref:`shutil <archiving-operations>`.
.. function:: is_tarfile(name)
- Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
+ Return :const:`True` if *name* is a tar archive file, that the :mod:`!tarfile`
module can read. *name* may be a :class:`str`, file, or file-like object.
.. versionchanged:: 3.9
Support for file and file-like objects.
-The :mod:`tarfile` module defines the following exceptions:
+The :mod:`!tarfile` module defines the following exceptions:
.. exception:: TarError
- Base class for all :mod:`tarfile` exceptions.
+ Base class for all :mod:`!tarfile` exceptions.
.. exception:: ReadError
Is raised when a tar archive is opened, that either cannot be handled by the
- :mod:`tarfile` module or is somehow invalid.
+ :mod:`!tarfile` module or is somehow invalid.
.. exception:: CompressionError
Each of the following constants defines a tar archive format that the
-:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
+:mod:`!tarfile` module is able to create. See section :ref:`tar-formats` for
details.
.. versionadded:: 3.4
-The :mod:`tarfile` module provides a simple command-line interface to interact
+The :mod:`!tarfile` module provides a simple command-line interface to interact
with tar archives.
If you want to create a new tar archive, specify its name after the :option:`-c`
Supported tar formats
---------------------
-There are three tar formats that can be created with the :mod:`tarfile` module:
+There are three tar formats that can be created with the :mod:`!tarfile` module:
* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
up to a length of at best 256 characters and linknames up to 100 characters.
* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
linknames, files bigger than 8 GiB and sparse files. It is the de facto
- standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
+ standard on GNU/Linux systems. :mod:`!tarfile` fully supports the GNU tar
extensions for long names, sparse file support is read-only.
* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
pax format was designed to solve this problem. It stores non-ASCII metadata
using the universal character encoding *UTF-8*.
-The details of character conversion in :mod:`tarfile` are controlled by the
+The details of character conversion in :mod:`!tarfile` are controlled by the
*encoding* and *errors* keyword arguments of the :class:`TarFile` class.
*encoding* defines the character encoding to use for the metadata in the
Examples
--------
-Here are some examples of typical usage of the :mod:`tempfile` module::
+Here are some examples of typical usage of the :mod:`!tempfile` module::
>>> import tempfile
items with indices :const:`VMIN` and :const:`VTIME`, which are integers when
these fields are defined). The interpretation of the flags and the speeds as
well as the indexing in the *cc* array must be done using the symbolic
- constants defined in the :mod:`termios` module.
+ constants defined in the :mod:`!termios` module.
.. function:: tcsetattr(fd, when, attributes)
.. sectionauthor:: Brett Cannon <brett@python.org>
.. note::
- The :mod:`test` package is meant for internal use by Python only. It is
+ The :mod:`!test` package is meant for internal use by Python only. It is
documented for the benefit of the core developers of Python. Any use of
this package outside of Python's standard library is discouraged as code
mentioned here can change or be removed without notice between releases of
--------------
-The :mod:`test` package contains all regression tests for Python as well as the
+The :mod:`!test` package contains all regression tests for Python as well as the
modules :mod:`test.support` and :mod:`test.regrtest`.
:mod:`test.support` is used to enhance your tests while
:mod:`test.regrtest` drives the testing suite.
-Each module in the :mod:`test` package whose name starts with ``test_`` is a
+Each module in the :mod:`!test` package whose name starts with ``test_`` is a
testing suite for a specific module or feature. All new tests should be written
using the :mod:`unittest` or :mod:`doctest` module. Some older tests are
written using a "traditional" testing style that compares output printed to
.. _writing-tests:
-Writing Unit Tests for the :mod:`test` package
-----------------------------------------------
+Writing Unit Tests for the :mod:`!test` package
+-----------------------------------------------
It is preferred that tests that use the :mod:`unittest` module follow a few
guidelines. One is to name the test module by starting it with ``test_`` and end
.. module:: test.regrtest
:synopsis: Drives the regression test suite.
-The :mod:`test` package can be run as a script to drive Python's regression
+The :mod:`!test` package can be run as a script to drive Python's regression
test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under
the hood, it uses :mod:`test.regrtest`; the call :program:`python -m
test.regrtest` used in previous Python versions still works. Running the
script by itself automatically starts running all regression tests in the
-:mod:`test` package. It does this by finding all modules in the package whose
+:mod:`!test` package. It does this by finding all modules in the package whose
name starts with ``test_``, importing them, and executing the function
:func:`test_main` if present or loading the tests via
unittest.TestLoader.loadTestsFromModule if ``test_main`` does not exist. The
regression test (:program:`python -m test test_spam`) will minimize output and
only print whether the test passed or failed.
-Running :mod:`test` directly allows what resources are available for
+Running :mod:`!test` directly allows what resources are available for
tests to use to be set. You do this by using the ``-u`` command-line
option. Specifying ``all`` as the value for the ``-u`` option enables all
possible resources: :program:`python -m test -uall`.
If all but one resource is desired (a more common case), a
comma-separated list of resources that are not desired may be listed after
``all``. The command :program:`python -m test -uall,-audio,-largefile`
-will run :mod:`test` with all resources except the ``audio`` and
+will run :mod:`!test` with all resources except the ``audio`` and
``largefile`` resources. For a list of all resources and more command-line
options, run :program:`python -m test -h`.
--------------
-The :mod:`textwrap` module provides some convenience functions,
+The :mod:`!textwrap` module provides some convenience functions,
as well as :class:`TextWrapper`, the class that does all the work.
If you're just wrapping or filling one or two text strings, the convenience
functions should be good enough; otherwise, you should use an instance of
0.08588060699912603
-To give the :mod:`timeit` module access to functions you define, you can pass a
+To give the :mod:`!timeit` module access to functions you define, you can pass a
*setup* parameter which contains an import statement::
def test():
--------------
-The :mod:`tkinter.colorchooser` module provides the :class:`Chooser` class
+The :mod:`!tkinter.colorchooser` module provides the :class:`Chooser` class
as an interface to the native color picker dialog. ``Chooser`` implements
a modal color choosing dialog window. The ``Chooser`` class inherits from
the :class:`~tkinter.commondialog.Dialog` class.
.. note:: This is experimental and due to be deprecated when it is replaced
with the Tk DND.
-The :mod:`tkinter.dnd` module provides drag-and-drop support for objects within
+The :mod:`!tkinter.dnd` module provides drag-and-drop support for objects within
a single application, within the same window or between windows. To enable an
object to be dragged, you must create an event binding for it that starts the
drag-and-drop process. Typically, you bind a ButtonPress event to a callback
--------------
-The :mod:`tkinter.font` module provides the :class:`Font` class for creating
+The :mod:`!tkinter.font` module provides the :class:`Font` class for creating
and using named fonts.
The different font weights and slants are:
--------------
-The :mod:`tkinter.messagebox` module provides a template base class as well as
+The :mod:`!tkinter.messagebox` module provides a template base class as well as
a variety of convenience methods for commonly used configurations. The message
boxes are modal and will return a subset of (``True``, ``False``, ``None``,
:data:`OK`, :data:`CANCEL`, :data:`YES`, :data:`NO`) based on
--------------
-The :mod:`tkinter` package ("Tk interface") is the standard Python interface to
-the Tcl/Tk GUI toolkit. Both Tk and :mod:`tkinter` are available on most Unix
+The :mod:`!tkinter` package ("Tk interface") is the standard Python interface to
+the Tcl/Tk GUI toolkit. Both Tk and :mod:`!tkinter` are available on most Unix
platforms, including macOS, as well as on Windows systems.
Running ``python -m tkinter`` from the command line should open a window
-demonstrating a simple Tk interface, letting you know that :mod:`tkinter` is
+demonstrating a simple Tk interface, letting you know that :mod:`!tkinter` is
properly installed on your system, and also showing what version of Tcl/Tk is
installed, so you can read the Tcl/Tk documentation specific to that version.
i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.
When your Python application uses a class in Tkinter, e.g., to create a widget,
-the :mod:`tkinter` module first assembles a Tcl/Tk command string. It passes that
+the :mod:`!tkinter` module first assembles a Tcl/Tk command string. It passes that
Tcl command string to an internal :mod:`_tkinter` binary module, which then
calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the
Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.
---------------
Support for Tkinter is spread across several modules. Most applications will need the
-main :mod:`tkinter` module, as well as the :mod:`tkinter.ttk` module, which provides
+main :mod:`!tkinter` module, as well as the :mod:`tkinter.ttk` module, which provides
the modern themed widget set and API::
The modules that provide Tk support include:
-:mod:`tkinter`
+:mod:`!tkinter`
Main Tkinter module.
:mod:`tkinter.colorchooser`
:mod:`tkinter.ttk`
Themed widget set introduced in Tk 8.5, providing modern alternatives
- for many of the classic widgets in the main :mod:`tkinter` module.
+ for many of the classic widgets in the main :mod:`!tkinter` module.
Additional modules:
:mod:`_tkinter`
A binary module that contains the low-level interface to Tcl/Tk.
- It is automatically imported by the main :mod:`tkinter` module,
+ It is automatically imported by the main :mod:`!tkinter` module,
and should never be used directly by application programmers.
It is usually a shared library (or DLL), but might in some cases be
statically linked with the Python interpreter.
:mod:`idlelib`
Python's Integrated Development and Learning Environment (IDLE). Based
- on :mod:`tkinter`.
+ on :mod:`!tkinter`.
:mod:`tkinter.constants`
Symbolic constants that can be used in place of strings when passing
various parameters to Tkinter calls. Automatically imported by the
- main :mod:`tkinter` module.
+ main :mod:`!tkinter` module.
:mod:`tkinter.dnd`
- (experimental) Drag-and-drop support for :mod:`tkinter`. This will
+ (experimental) Drag-and-drop support for :mod:`!tkinter`. This will
become deprecated when it is replaced with the Tk DND.
:mod:`turtle`
Threading model
---------------
-Python and Tcl/Tk have very different threading models, which :mod:`tkinter`
+Python and Tcl/Tk have very different threading models, which :mod:`!tkinter`
tries to bridge. If you use threads, you may need to be aware of this.
A Python interpreter may have many threads associated with it. In Tcl, multiple
associated with it. Threads can also create more than one interpreter instance,
though each interpreter instance can be used only by the one thread that created it.
-Each :class:`Tk` object created by :mod:`tkinter` contains a Tcl interpreter.
+Each :class:`Tk` object created by :mod:`!tkinter` contains a Tcl interpreter.
It also keeps track of which thread created that interpreter. Calls to
-:mod:`tkinter` can be made from any Python thread. Internally, if a call comes
+:mod:`!tkinter` can be made from any Python thread. Internally, if a call comes
from a thread other than the one that created the :class:`Tk` object, an event
is posted to the interpreter's event queue, and when executed, the result is
returned to the calling Python thread.
code including event handlers.
If the Tcl interpreter is not running the event loop and processing events, any
-:mod:`tkinter` calls made from threads other than the one running the Tcl
+:mod:`!tkinter` calls made from threads other than the one running the Tcl
interpreter will fail.
A number of special cases exist:
* Tcl/Tk libraries can be built so they are not thread-aware. In this case,
- :mod:`tkinter` calls the library from the originating Python thread, even
+ :mod:`!tkinter` calls the library from the originating Python thread, even
if this is different than the thread that created the Tcl interpreter. A global
lock ensures only one call occurs at a time.
-* While :mod:`tkinter` allows you to create more than one instance of a :class:`Tk`
+* While :mod:`!tkinter` allows you to create more than one instance of a :class:`Tk`
object (with its own interpreter), all interpreters that are part of the same
thread share a common event queue, which gets ugly fast. In practice, don't create
more than one instance of :class:`Tk` at a time. Otherwise, it's best to create
or abandon the event loop entirely. If you're doing anything tricky when it comes
to events or threads, be aware of these possibilities.
-* There are a few select :mod:`tkinter` functions that presently work only when
+* There are a few select :mod:`!tkinter` functions that presently work only when
called from the thread that created the Tcl interpreter.
``value``. This connection works both ways: if the variable changes for any
reason, the widget it's connected to will be updated to reflect the new value.
-Unfortunately, in the current implementation of :mod:`tkinter` it is not
+Unfortunately, in the current implementation of :mod:`!tkinter` it is not
possible to hand over an arbitrary Python variable to a widget through a
``variable`` or ``textvariable`` option. The only kinds of variables for which
this works are variables that are subclassed from a class called Variable,
-defined in :mod:`tkinter`.
+defined in :mod:`!tkinter`.
There are many useful subclasses of Variable already defined:
:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
In Tk, there is a utility command, ``wm``, for interacting with the window
manager. Options to the ``wm`` command allow you to control things like titles,
-placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
+placement, icon bitmaps, and the like. In :mod:`!tkinter`, these commands have
been implemented as methods on the :class:`Wm` class. Toplevel widgets are
subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
directly.
Entry widget indexes (index, view index, etc.)
Entry widgets have options that refer to character positions in the text being
- displayed. You can use these :mod:`tkinter` functions to access these special
+ displayed. You can use these :mod:`!tkinter` functions to access these special
points in text widgets:
Text widget indexes
--------------
-The :mod:`tkinter.scrolledtext` module provides a class of the same name which
+The :mod:`!tkinter.scrolledtext` module provides a class of the same name which
implements a basic text widget which has a vertical scroll bar configured to do
the "right thing." Using the :class:`ScrolledText` class is a lot easier than
setting up a text widget and scroll bar directly.
--------------
-The :mod:`tkinter.ttk` module provides access to the Tk themed widget set,
+The :mod:`!tkinter.ttk` module provides access to the Tk themed widget set,
introduced in Tk 8.5. It provides additional benefits including anti-aliased font
rendering under X11 and window transparency (requiring a composition
window manager on X11).
-The basic idea for :mod:`tkinter.ttk` is to separate, to the extent possible,
+The basic idea for :mod:`!tkinter.ttk` is to separate, to the extent possible,
the code implementing a widget's behavior from the code implementing its
appearance.
from tkinter import *
from tkinter.ttk import *
-That code causes several :mod:`tkinter.ttk` widgets (:class:`Button`,
+That code causes several :mod:`!tkinter.ttk` widgets (:class:`Button`,
:class:`Checkbutton`, :class:`Entry`, :class:`Frame`, :class:`Label`,
:class:`LabelFrame`, :class:`Menubutton`, :class:`PanedWindow`,
:class:`Radiobutton`, :class:`Scale` and :class:`Scrollbar`) to
--------------
-The :mod:`tokenize` module provides a lexical scanner for Python source code,
+The :mod:`!tokenize` module provides a lexical scanner for Python source code,
implemented in Python. The scanner in this module returns comments as tokens
as well, making it useful for implementing "pretty-printers", including
colorizers for on-screen displays.
:func:`.tokenize`. It does not yield an :data:`~token.ENCODING` token.
All constants from the :mod:`token` module are also exported from
-:mod:`tokenize`.
+:mod:`!tokenize`.
Another function is provided to reverse the tokenization process. This is
useful for creating tools that tokenize a script, modify the token stream, and
.. versionadded:: 3.3
-The :mod:`tokenize` module can be executed as a script from the command line.
+The :mod:`!tokenize` module can be executed as a script from the command line.
It is as simple as:
.. code-block:: sh
--------------
-The :mod:`trace` module allows you to trace program execution, generate
+The :mod:`!trace` module allows you to trace program execution, generate
annotated statement coverage listings, print caller/callee relationships and
list functions executed during a program run. It can be used in another program
or from the command line.
Command-Line Usage
------------------
-The :mod:`trace` module can be invoked from the command line. It can be as
+The :mod:`!trace` module can be invoked from the command line. It can be as
simple as ::
python -m trace --count -C . somefile.py ...
^^^^^^^^^^^^
At least one of the following options must be specified when invoking
-:mod:`trace`. The :option:`--listfuncs <-l>` option is mutually exclusive with
+:mod:`!trace`. The :option:`--listfuncs <-l>` option is mutually exclusive with
the :option:`--trace <-t>` and :option:`--count <-c>` options. When
:option:`--listfuncs <-l>` is provided, neither :option:`--count <-c>` nor
:option:`--trace <-t>` are accepted, and vice versa.
.. function:: get_object_traceback(obj)
Get the traceback where the Python object *obj* was allocated.
- Return a :class:`Traceback` instance, or ``None`` if the :mod:`tracemalloc`
+ Return a :class:`Traceback` instance, or ``None`` if the :mod:`!tracemalloc`
module is not tracing memory allocations or did not trace the allocation of
the object.
Get the maximum number of frames stored in the traceback of a trace.
- The :mod:`tracemalloc` module must be tracing memory allocations to
+ The :mod:`!tracemalloc` module must be tracing memory allocations to
get the limit, otherwise an exception is raised.
The limit is set by the :func:`start` function.
.. function:: get_traced_memory()
Get the current size and peak size of memory blocks traced by the
- :mod:`tracemalloc` module as a tuple: ``(current: int, peak: int)``.
+ :mod:`!tracemalloc` module as a tuple: ``(current: int, peak: int)``.
.. function:: reset_peak()
- Set the peak size of memory blocks traced by the :mod:`tracemalloc` module
+ Set the peak size of memory blocks traced by the :mod:`!tracemalloc` module
to the current size.
- Do nothing if the :mod:`tracemalloc` module is not tracing memory
+ Do nothing if the :mod:`!tracemalloc` module is not tracing memory
allocations.
This function only modifies the recorded peak size, and does not modify or
.. function:: get_tracemalloc_memory()
- Get the memory usage in bytes of the :mod:`tracemalloc` module used to store
+ Get the memory usage in bytes of the :mod:`!tracemalloc` module used to store
traces of memory blocks.
Return an :class:`int`.
.. function:: is_tracing()
- ``True`` if the :mod:`tracemalloc` module is tracing Python memory
+ ``True`` if the :mod:`!tracemalloc` module is tracing Python memory
allocations, ``False`` otherwise.
See also :func:`start` and :func:`stop` functions.
:meth:`Snapshot.compare_to` and :meth:`Snapshot.statistics` methods.
Storing more frames increases the memory and CPU overhead of the
- :mod:`tracemalloc` module. Use the :func:`get_tracemalloc_memory` function
- to measure how much memory is used by the :mod:`tracemalloc` module.
+ :mod:`!tracemalloc` module. Use the :func:`get_tracemalloc_memory` function
+ to measure how much memory is used by the :mod:`!tracemalloc` module.
The :envvar:`PYTHONTRACEMALLOC` environment variable
(``PYTHONTRACEMALLOC=NFRAME``) and the :option:`-X` ``tracemalloc=NFRAME``
:class:`Snapshot` instance.
The snapshot does not include memory blocks allocated before the
- :mod:`tracemalloc` module started to trace memory allocations.
+ :mod:`!tracemalloc` module started to trace memory allocations.
Tracebacks of traces are limited to :func:`get_traceback_limit` frames. Use
the *nframe* parameter of the :func:`start` function to store more frames.
- The :mod:`tracemalloc` module must be tracing memory allocations to take a
+ The :mod:`!tracemalloc` module must be tracing memory allocations to take a
snapshot, see the :func:`start` function.
See also the :func:`get_object_traceback` function.
* ``Filter(True, subprocess.__file__)`` only includes traces of the
:mod:`subprocess` module
* ``Filter(False, tracemalloc.__file__)`` excludes traces of the
- :mod:`tracemalloc` module
+ :mod:`!tracemalloc` module
* ``Filter(False, "<unknown>")`` excludes empty tracebacks
--------------
-The :mod:`tty` module defines functions for putting the tty into cbreak and raw
+The :mod:`!tty` module defines functions for putting the tty into cbreak and raw
modes.
.. availability:: Unix.
Because it requires the :mod:`termios` module, it will work only on Unix.
-The :mod:`tty` module defines the following functions:
+The :mod:`!tty` module defines the following functions:
.. function:: cfmakeraw(mode)
--------------
-:mod:`unittest.mock` is a library for testing in Python. It allows you to
+:mod:`!unittest.mock` is a library for testing in Python. It allows you to
replace parts of your system under test with mock objects and make assertions
about how they have been used.
-:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to
+:mod:`!unittest.mock` provides a core :class:`Mock` class removing the need to
create a host of stubs throughout your test suite. After performing an
action, you can make assertions about which methods / attributes were used
and arguments they were called with. You can also specify return values and
is based on the 'action -> assertion' pattern instead of 'record -> replay'
used by many mocking frameworks.
-There is a backport of :mod:`unittest.mock` for earlier versions of Python,
+There is a backport of :mod:`!unittest.mock` for earlier versions of Python,
available as :pypi:`mock` on PyPI.
don't test how your units are "wired together" there is still lots of room
for bugs that tests might have caught.
-:mod:`unittest.mock` already provides a feature to help with this, called speccing. If you
+:mod:`!unittest.mock` already provides a feature to help with this, called speccing. If you
use a class or instance as the :attr:`!spec` for a mock then you can only access
attributes on the mock that exist on the real class:
(If you are already familiar with the basic concepts of testing, you might want
to skip to :ref:`the list of assert methods <assert-methods>`.)
-The :mod:`unittest` unit testing framework was originally inspired by JUnit
+The :mod:`!unittest` unit testing framework was originally inspired by JUnit
and has a similar flavor as major unit testing frameworks in other
languages. It supports test automation, sharing of setup and shutdown code
for tests, aggregation of tests into collections, and independence of the
tests from the reporting framework.
-To achieve this, :mod:`unittest` supports some important concepts in an
+To achieve this, :mod:`!unittest` supports some important concepts in an
object-oriented way:
test fixture
test case
A :dfn:`test case` is the individual unit of testing. It checks for a specific
- response to a particular set of inputs. :mod:`unittest` provides a base class,
+ response to a particular set of inputs. :mod:`!unittest` provides a base class,
:class:`TestCase`, which may be used to create new test cases.
test suite
`Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_
Kent Beck's original paper on testing frameworks using the pattern shared
- by :mod:`unittest`.
+ by :mod:`!unittest`.
`pytest <https://docs.pytest.org/>`_
Third-party unittest framework with a lighter-weight syntax for writing
Basic example
-------------
-The :mod:`unittest` module provides a rich set of tools for constructing and
+The :mod:`!unittest` module provides a rich set of tools for constructing and
running tests. This section demonstrates that a small subset of the tools
suffice to meet the needs of most users.
OK
-The above examples show the most commonly used :mod:`unittest` features which
+The above examples show the most commonly used :mod:`!unittest` features which
are sufficient to meet many everyday testing needs. The remainder of the
documentation explores the full feature set from first principles.
--------------------
The basic building blocks of unit testing are :dfn:`test cases` --- single
-scenarios that must be set up and checked for correctness. In :mod:`unittest`,
+scenarios that must be set up and checked for correctness. In :mod:`!unittest`,
test cases are represented by :class:`unittest.TestCase` instances.
To make your own test cases you must write subclasses of
:class:`TestCase` or use :class:`FunctionTestCase`.
Note that in order to test something, we use one of the :ref:`assert\* methods <assert-methods>`
provided by the :class:`TestCase` base class. If the test fails, an
-exception will be raised with an explanatory message, and :mod:`unittest`
+exception will be raised with an explanatory message, and :mod:`!unittest`
will identify the test case as a :dfn:`failure`. Any other exceptions will be
treated as :dfn:`errors`.
will be called once per test.
It is recommended that you use TestCase implementations to group tests together
-according to the features they test. :mod:`unittest` provides a mechanism for
-this: the :dfn:`test suite`, represented by :mod:`unittest`'s
+according to the features they test. :mod:`!unittest` provides a mechanism for
+this: the :dfn:`test suite`, represented by :mod:`!unittest`'s
:class:`TestSuite` class. In most cases, calling :func:`unittest.main` will do
the right thing and collect all the module's test cases for you and execute
them.
----------------------
Some users will find that they have existing test code that they would like to
-run from :mod:`unittest`, without converting every old test function to a
+run from :mod:`!unittest`, without converting every old test function to a
:class:`TestCase` subclass.
-For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
+For this reason, :mod:`!unittest` provides a :class:`FunctionTestCase` class.
This subclass of :class:`TestCase` can be used to wrap an existing test
function. Set-up and tear-down functions can also be provided.
.. note::
Even though :class:`FunctionTestCase` can be used to quickly convert an
- existing test base over to a :mod:`unittest`\ -based system, this approach is
+ existing test base over to a :mod:`!unittest`\ -based system, this approach is
not recommended. Taking the time to set up proper :class:`TestCase`
subclasses will make future test refactorings infinitely easier.
Classes and functions
---------------------
-This section describes in depth the API of :mod:`unittest`.
+This section describes in depth the API of :mod:`!unittest`.
.. _testcase-objects:
.. class:: TestCase(methodName='runTest')
Instances of the :class:`TestCase` class represent the logical test units
- in the :mod:`unittest` universe. This class is intended to be used as a base
+ in the :mod:`!unittest` universe. This class is intended to be used as a base
class, with specific tests being implemented by concrete subclasses. This class
implements the interface needed by the test runner to allow it to drive the
tests, and methods that the test code can use to check for and report various
allows the test runner to drive the test, but does not provide the methods
which test code can use to check and report errors. This is used to create
test cases using legacy test code, allowing it to be integrated into a
- :mod:`unittest`-based test framework.
+ :mod:`!unittest`-based test framework.
.. _testsuite-objects:
The :class:`TestLoader` class is used to create test suites from classes and
modules. Normally, there is no need to create an instance of this class; the
- :mod:`unittest` module provides an instance that can be shared as
+ :mod:`!unittest` module provides an instance that can be shared as
:data:`unittest.defaultTestLoader`. Using a subclass or instance, however,
allows customization of some configurable properties.
properly recorded; test authors do not need to worry about recording the
outcome of tests.
- Testing frameworks built on top of :mod:`unittest` may want access to the
+ Testing frameworks built on top of :mod:`!unittest` may want access to the
:class:`TestResult` object generated by running a set of tests for reporting
purposes; a :class:`TestResult` instance is returned by the
:meth:`!TestRunner.run` method for this purpose.
--------------
-The :mod:`urllib.error` module defines the exception classes for exceptions
+The :mod:`!urllib.error` module defines the exception classes for exceptions
raised by :mod:`urllib.request`. The base exception class is :exc:`URLError`.
-The following exceptions are raised by :mod:`urllib.error` as appropriate:
+The following exceptions are raised by :mod:`!urllib.error` as appropriate:
.. exception:: URLError
macOS, it *may* be removed if CPython has been built with the
:option:`--with-app-store-compliance` option.
-The :mod:`urllib.parse` module defines functions that fall into two broad
+The :mod:`!urllib.parse` module defines functions that fall into two broad
categories: URL parsing and URL quoting. These are covered in detail in
the following sections.
--------------
-The :mod:`urllib.request` module defines functions and classes which help in
+The :mod:`!urllib.request` module defines functions and classes which help in
opening URLs (mostly HTTP) in a complex world --- basic and digest
authentication, redirections, cookies and more.
.. include:: ../includes/wasm-notavail.rst
-The :mod:`urllib.request` module defines the following functions:
+The :mod:`!urllib.request` module defines the following functions:
.. function:: urlopen(url, data=None[, timeout], *, context=None)
calls to :func:`urlretrieve`.
-:mod:`urllib.request` Restrictions
-----------------------------------
+:mod:`!urllib.request` Restrictions
+-----------------------------------
.. index::
pair: HTTP; protocol
The :mod:`urllib.response` module defines functions and classes which define a
minimal file-like interface, including ``read()`` and ``readline()``.
-Functions defined by this module are used internally by the :mod:`urllib.request` module.
+Functions defined by this module are used internally by the :mod:`!urllib.request` module.
The typical response object is a :class:`urllib.response.addinfourl` instance:
.. class:: addinfourl
.. versionadded:: 3.7
-The :mod:`uuid` module defines the following functions:
+The :mod:`!uuid` module defines the following functions:
.. function:: getnode()
.. versionadded:: 3.14
-The :mod:`uuid` module defines the following namespace identifiers for use with
+The :mod:`!uuid` module defines the following namespace identifiers for use with
:func:`uuid3` or :func:`uuid5`.
When this namespace is specified, the *name* string is an X.500 DN in DER or a
text output format.
-The :mod:`uuid` module defines the following constants for the possible values
+The :mod:`!uuid` module defines the following constants for the possible values
of the :attr:`~UUID.variant` attribute:
Reserved for future definition.
-The :mod:`uuid` module defines the special Nil and Max UUID values:
+The :mod:`!uuid` module defines the special Nil and Max UUID values:
.. data:: NIL
.. versionadded:: 3.12
-The :mod:`uuid` module can be executed as a script from the command line.
+The :mod:`!uuid` module can be executed as a script from the command line.
.. code-block:: sh
Example
-------
-Here are some examples of typical usage of the :mod:`uuid` module::
+Here are some examples of typical usage of the :mod:`!uuid` module::
>>> import uuid
Command-Line Example
--------------------
-Here are some examples of typical usage of the :mod:`uuid` command-line interface:
+Here are some examples of typical usage of the :mod:`!uuid` command-line interface:
.. code-block:: shell
The warnings filter is initialized by :option:`-W` options passed to the Python
interpreter command line and the :envvar:`PYTHONWARNINGS` environment variable.
The interpreter saves the arguments for all supplied entries without
-interpretation in :data:`sys.warnoptions`; the :mod:`warnings` module parses these
+interpretation in :data:`sys.warnoptions`; the :mod:`!warnings` module parses these
when it is first imported (invalid options are ignored, after printing a
message to :data:`sys.stderr`).
:func:`showwarning`.
The *module* argument takes a module that will be used instead of the
- module returned when you import :mod:`warnings` whose filter will be
- protected. This argument exists primarily for testing the :mod:`warnings`
+ module returned when you import :mod:`!warnings` whose filter will be
+ protected. This argument exists primarily for testing the :mod:`!warnings`
module itself.
If the *action* argument is not ``None``, the remaining arguments are
If the :data:`~sys.flags.context_aware_warnings` flag is false, then
:class:`catch_warnings` will modify the global attributes of the
-:mod:`warnings` module. This is not safe if used within a concurrent program
+:mod:`!warnings` module. This is not safe if used within a concurrent program
(using multiple threads or using asyncio coroutines). For example, if two
or more threads use the :class:`catch_warnings` class at the same time, the
behavior is undefined.
--------------
-The :mod:`wave` module provides a convenient interface to the Waveform Audio
+The :mod:`!wave` module provides a convenient interface to the Waveform Audio
"WAVE" (or "WAV") file format. Only uncompressed PCM encoded wave files are
supported.
Support for ``WAVE_FORMAT_EXTENSIBLE`` headers was added, provided that the
extended format is ``KSDATAFORMAT_SUBTYPE_PCM``.
-The :mod:`wave` module defines the following function and exception:
+The :mod:`!wave` module defines the following function and exception:
.. function:: open(file, mode=None)
.. method:: close()
- Close the stream if it was opened by :mod:`wave`, and make the instance
+ Close the stream if it was opened by :mod:`!wave`, and make the instance
unusable. This is called automatically on object collection.
.. method:: close()
Make sure *nframes* is correct, and close the file if it was opened by
- :mod:`wave`. This method is called upon object collection. It will raise
+ :mod:`!wave`. This method is called upon object collection. It will raise
an exception if the output stream is not seekable and *nframes* does not
match the number of frames actually written.
--------------
-The :mod:`webbrowser` module provides a high-level interface to allow displaying
+The :mod:`!webbrowser` module provides a high-level interface to allow displaying
web-based documents to users. Under most circumstances, simply calling the
:func:`.open` function from this module will do the right thing.
controlling autoraise, browser preference, and new tab/window creation will be
ignored. Web pages will *always* be opened in the user's preferred browser, in
a new tab, with the browser being brought to the foreground. The use of the
-:mod:`webbrowser` module on iOS requires the :mod:`ctypes` module. If
+:mod:`!webbrowser` module on iOS requires the :mod:`ctypes` module. If
:mod:`ctypes` isn't available, calls to :func:`.open` will fail.
.. _webbrowser-cli:
Constants
---------
-The following constants are defined for use in many :mod:`winreg` functions.
+The following constants are defined for use in many :mod:`!winreg` functions.
.. _hkey-constants:
--------------
-The :mod:`winsound` module provides access to the basic sound-playing machinery
+The :mod:`!winsound` module provides access to the basic sound-playing machinery
provided by Windows platforms. It includes functions and several constants.
.. availability:: Windows.
of WSGI just to install a WSGI application or to write a web application using
an existing framework.
-:mod:`wsgiref` is a reference implementation of the WSGI specification that can
+:mod:`!wsgiref` is a reference implementation of the WSGI specification that can
be used to add WSGI support to a web server or framework. It provides utilities
for manipulating WSGI environment variables and response headers, base classes
for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
--------------
-:mod:`xml.dom.minidom` is a minimal implementation of the Document Object
+:mod:`!xml.dom.minidom` is a minimal implementation of the Document Object
Model interface, with an API similar to that in other languages. It is intended
to be simpler than the full DOM and also significantly smaller. Users who are
not already proficient with the DOM should consider using the
DOM applications typically start by parsing some XML into a DOM. With
-:mod:`xml.dom.minidom`, this is done through the parse functions::
+:mod:`!xml.dom.minidom`, this is done through the parse functions::
from xml.dom.minidom import parse, parseString
You can also create a :class:`Document` by calling a method on a "DOM
Implementation" object. You can get this object either by calling the
:func:`getDOMImplementation` function in the :mod:`xml.dom` package or the
-:mod:`xml.dom.minidom` module. Once you have a :class:`Document`, you
+:mod:`!xml.dom.minidom` module. Once you have a :class:`Document`, you
can add child nodes to it to populate the DOM::
from xml.dom.minidom import getDOMImplementation
When you are finished with a DOM tree, you may optionally call the
:meth:`unlink` method to encourage early cleanup of the now-unneeded
-objects. :meth:`unlink` is an :mod:`xml.dom.minidom`\ -specific
+objects. :meth:`unlink` is an :mod:`!xml.dom.minidom`\ -specific
extension to the DOM API that renders the node and its descendants
essentially useless. Otherwise, Python's garbage collector will
eventually take care of the objects in the tree.
.. seealso::
`Document Object Model (DOM) Level 1 Specification <https://www.w3.org/TR/REC-DOM-Level-1/>`_
- The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.
+ The W3C recommendation for the DOM supported by :mod:`!xml.dom.minidom`.
.. _minidom-objects:
The definition of the DOM API for Python is given as part of the :mod:`xml.dom`
module documentation. This section lists the differences between the API and
-:mod:`xml.dom.minidom`.
+:mod:`!xml.dom.minidom`.
.. method:: Node.unlink()
minidom and the DOM standard
----------------------------
-The :mod:`xml.dom.minidom` module is essentially a DOM 1.0-compatible DOM with
+The :mod:`!xml.dom.minidom` module is essentially a DOM 1.0-compatible DOM with
some DOM 2 features (primarily namespace features).
Usage of the DOM interface in Python is straight-forward. The following mapping
* The types ``short int``, ``unsigned int``, ``unsigned long long``, and
``boolean`` all map to Python integer objects.
-* The type ``DOMString`` maps to Python strings. :mod:`xml.dom.minidom` supports
+* The type ``DOMString`` maps to Python strings. :mod:`!xml.dom.minidom` supports
either bytes or strings, but will normally produce strings.
Values of type ``DOMString`` may also be ``None`` where allowed to have the IDL
``null`` value by the DOM specification from the W3C.
* ``const`` declarations map to variables in their respective scope (e.g.
``xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE``); they must not be changed.
-* ``DOMException`` is currently not supported in :mod:`xml.dom.minidom`.
- Instead, :mod:`xml.dom.minidom` uses standard Python exceptions such as
+* ``DOMException`` is currently not supported in :mod:`!xml.dom.minidom`.
+ Instead, :mod:`!xml.dom.minidom` uses standard Python exceptions such as
:exc:`TypeError` and :exc:`AttributeError`.
* :class:`NodeList` objects are implemented using Python's built-in list type.
however, much more "Pythonic" than the interface defined in the W3C
recommendations.
-The following interfaces have no implementation in :mod:`xml.dom.minidom`:
+The following interfaces have no implementation in :mod:`!xml.dom.minidom`:
* :class:`DOMTimeStamp`
--------------
-The :mod:`xml.dom.pulldom` module provides a "pull parser" which can also be
+The :mod:`!xml.dom.pulldom` module provides a "pull parser" which can also be
asked to produce DOM-accessible fragments of the document where necessary. The
basic concept involves pulling "events" from a stream of incoming XML and
processing them. In contrast to SAX which also employs an event-driven
Module Contents
---------------
-The :mod:`xml.dom` contains the following functions:
+The :mod:`!xml.dom` contains the following functions:
.. function:: registerDOMImplementation(name, factory)
HyperText Markup Language <https://www.w3.org/TR/xhtml1/>`_ (section 3.1.1).
-In addition, :mod:`xml.dom` contains a base :class:`Node` class and the DOM
+In addition, :mod:`!xml.dom` contains a base :class:`Node` class and the DOM
exception classes. The :class:`Node` class provided by this module does not
implement any of the methods or attributes defined by the DOM specification;
concrete DOM implementations must provide those. The :class:`Node` class
--------------
-The :mod:`xml.etree.ElementTree` module implements a simple and efficient API
+The :mod:`!xml.etree.ElementTree` module implements a simple and efficient API
for parsing and creating XML data.
.. versionchanged:: 3.3
Tutorial
--------
-This is a short tutorial for using :mod:`xml.etree.ElementTree` (``ET`` in
+This is a short tutorial for using :mod:`!xml.etree.ElementTree` (``ET`` in
short). The goal is to demonstrate some of the building blocks and basic
concepts of the module.
By default, the **href** attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.
-To process this file, load it as usual, and pass the root element to the :mod:`xml.etree.ElementTree` module:
+To process this file, load it as usual, and pass the root element to the :mod:`!xml.etree.ElementTree` module:
.. code-block:: python
only need to implement those interfaces whose events they are interested in;
they can implement the interfaces in a single object or in multiple objects.
Handler implementations should inherit from the base classes provided in the
-module :mod:`xml.sax.handler`, so that all methods get default implementations.
+module :mod:`!xml.sax.handler`, so that all methods get default implementations.
.. class:: ContentHandler
Interface used by the parser to represent low frequency events which may not
be of interest to many applications.
-In addition to these classes, :mod:`xml.sax.handler` provides symbolic constants
+In addition to these classes, :mod:`!xml.sax.handler` provides symbolic constants
for the feature and property names.
--------------
-The :mod:`xml.sax` package provides a number of modules which implement the
+The :mod:`!xml.sax` package provides a number of modules which implement the
Simple API for XML (SAX) interface for Python. The package itself provides the
SAX exceptions and the convenience functions which will be most used by users of
the SAX API.
:mod:`xml.sax.handler`. For convenience,
:class:`~xml.sax.xmlreader.InputSource` (which is often
instantiated directly) and the handler classes are also available from
-:mod:`xml.sax`. These interfaces are described below.
+:mod:`!xml.sax`. These interfaces are described below.
-In addition to these classes, :mod:`xml.sax` provides the following exception
+In addition to these classes, :mod:`!xml.sax` provides the following exception
classes.
--------------
-The module :mod:`xml.sax.saxutils` contains a number of classes and functions
+The module :mod:`!xml.sax.saxutils` contains a number of classes and functions
that are commonly useful when creating SAX applications, either in direct use,
or as base classes.
.. warning::
- The :mod:`xmlrpc.client` module is not secure against maliciously
+ The :mod:`!xmlrpc.client` module is not secure against maliciously
constructed data. If you need to parse untrusted or unauthenticated data,
see :ref:`xml-security`.
.. versionchanged:: 3.5
- For HTTPS URIs, :mod:`xmlrpc.client` now performs all the necessary
+ For HTTPS URIs, :mod:`!xmlrpc.client` now performs all the necessary
certificate and hostname checks by default.
.. include:: ../includes/wasm-notavail.rst
--------------
-The :mod:`xmlrpc.server` module provides a basic server framework for XML-RPC
+The :mod:`!xmlrpc.server` module provides a basic server framework for XML-RPC
servers written in Python. Servers can either be free standing, using
:class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using
:class:`CGIXMLRPCRequestHandler`.
.. warning::
- The :mod:`xmlrpc.server` module is not secure against maliciously
+ The :mod:`!xmlrpc.server` module is not secure against maliciously
constructed data. If you need to parse untrusted or unauthenticated data,
see :ref:`xml-security`.
Creating Standalone Applications with zipapp
--------------------------------------------
-Using the :mod:`zipapp` module, it is possible to create self-contained Python
+Using the :mod:`!zipapp` module, it is possible to create self-contained Python
programs, which can be distributed to end users who only need to have a
suitable version of Python installed on their system. The key to doing this
is to bundle all of the application's dependencies into the archive, along
Class used to represent information about a member of an archive. Instances
of this class are returned by the :meth:`.getinfo` and :meth:`.infolist`
- methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module
+ methods of :class:`ZipFile` objects. Most users of the :mod:`!zipfile` module
will not need to create these, but only use those created by this
module. *filename* should be the full name of the archive member, and
*date_time* should be a tuple containing six fields which describe the time
If *allowZip64* is ``True`` (the default) zipfile will create ZIP files that
use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is
- ``false`` :mod:`zipfile` will raise an exception when the ZIP file would
+ ``false`` :mod:`!zipfile` will raise an exception when the ZIP file would
require ZIP64 extensions.
The *compresslevel* parameter controls the compression level to use when
Command-line interface
----------------------
-The :mod:`zipfile` module provides a simple command-line interface to interact
+The :mod:`!zipfile` module provides a simple command-line interface to interact
with ZIP archives.
If you want to create a new ZIP archive, specify its name after the :option:`-c`
This module adds the ability to import Python modules (:file:`\*.py`,
:file:`\*.pyc`) and packages from ZIP-format archives. It is usually not
-needed to use the :mod:`zipimport` module explicitly; it is automatically used
+needed to use the :mod:`!zipimport` module explicitly; it is automatically used
by the built-in :keyword:`import` mechanism for :data:`sys.path` items that are paths
to ZIP archives.
--------
Here is an example that imports a module from a ZIP archive - note that the
-:mod:`zipimport` module is not explicitly used.
+:mod:`!zipimport` module is not explicitly used.
.. code-block:: shell-session
--------------
-The :mod:`zoneinfo` module provides a concrete time zone implementation to
+The :mod:`!zoneinfo` module provides a concrete time zone implementation to
support the IANA time zone database as originally specified in :pep:`615`. By
-default, :mod:`zoneinfo` uses the system's time zone data if available; if no
+default, :mod:`!zoneinfo` uses the system's time zone data if available; if no
system time zone data is available, the library will fall back to using the
first-party :pypi:`tzdata` package available on PyPI.