Commit b044b2a7 authored by Georg Brandl's avatar Georg Brandl

Merged revisions 74821,74828-74831,74833,74835 via svnmerge from

svn+ssh://svn.python.org/python/branches/py3k

................
  r74821 | georg.brandl | 2009-09-16 11:42:19 +0200 (Mi, 16 Sep 2009) | 1 line

  #6885: run python 3 as python3.
................
  r74828 | georg.brandl | 2009-09-16 16:23:20 +0200 (Mi, 16 Sep 2009) | 1 line

  Use true booleans.
................
  r74829 | georg.brandl | 2009-09-16 16:24:29 +0200 (Mi, 16 Sep 2009) | 1 line

  Small PEP8 correction.
................
  r74830 | georg.brandl | 2009-09-16 16:36:22 +0200 (Mi, 16 Sep 2009) | 1 line

  Use true booleans.
................
  r74831 | georg.brandl | 2009-09-16 17:54:04 +0200 (Mi, 16 Sep 2009) | 1 line

  Use true booleans and PEP8 for argdefaults.
................
  r74833 | georg.brandl | 2009-09-16 17:58:14 +0200 (Mi, 16 Sep 2009) | 1 line

  Last round of adapting style of documenting argument default values.
................
  r74835 | georg.brandl | 2009-09-16 18:00:31 +0200 (Mi, 16 Sep 2009) | 33 lines

  Merged revisions 74817-74820,74822-74824 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74817 | georg.brandl | 2009-09-16 11:05:11 +0200 (Mi, 16 Sep 2009) | 1 line

    Make deprecation notices as visible as warnings are right now.
  ........
    r74818 | georg.brandl | 2009-09-16 11:23:04 +0200 (Mi, 16 Sep 2009) | 1 line

    #6880: add reference to classes section in exceptions section, which comes earlier.
  ........
    r74819 | georg.brandl | 2009-09-16 11:24:57 +0200 (Mi, 16 Sep 2009) | 1 line

    #6876: fix base class constructor invocation in example.
  ........
    r74820 | georg.brandl | 2009-09-16 11:30:48 +0200 (Mi, 16 Sep 2009) | 1 line

    #6891: comment out dead link to Unicode article.
  ........
    r74822 | georg.brandl | 2009-09-16 12:12:06 +0200 (Mi, 16 Sep 2009) | 1 line

    #5621: refactor description of how class/instance attributes interact on a.x=a.x+1 or augassign.
  ........
    r74823 | georg.brandl | 2009-09-16 15:06:22 +0200 (Mi, 16 Sep 2009) | 1 line

    Remove strange trailing commas.
  ........
    r74824 | georg.brandl | 2009-09-16 15:11:06 +0200 (Mi, 16 Sep 2009) | 1 line

    #6892: fix optparse example involving help option.
  ........
................
parent f4b4623a
...@@ -212,11 +212,12 @@ To help understand the standard, Jukka Korpela has written an introductory guide ...@@ -212,11 +212,12 @@ To help understand the standard, Jukka Korpela has written an introductory guide
to reading the Unicode character tables, available at to reading the Unicode character tables, available at
<http://www.cs.tut.fi/~jkorpela/unicode/guide.html>. <http://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
Two other good introductory articles were written by Joel Spolsky Another good introductory article was written by Joel Spolsky
<http://www.joelonsoftware.com/articles/Unicode.html> and Jason Orendorff <http://www.joelonsoftware.com/articles/Unicode.html>.
<http://www.jorendorff.com/articles/unicode/>. If this introduction didn't make If this introduction didn't make things clear to you, you should try reading this
things clear to you, you should try reading one of these alternate articles alternate article before continuing.
before continuing.
.. Jason Orendorff XXX http://www.jorendorff.com/articles/unicode/ is broken
Wikipedia entries are often helpful; see the entries for "character encoding" Wikipedia entries are often helpful; see the entries for "character encoding"
<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8 <http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
......
...@@ -467,7 +467,7 @@ user-friendly (documented) options:: ...@@ -467,7 +467,7 @@ user-friendly (documented) options::
action="store_false", dest="verbose", action="store_false", dest="verbose",
help="be vewwy quiet (I'm hunting wabbits)") help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename", parser.add_option("-f", "--filename",
metavar="FILE", help="write output to FILE"), metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode", parser.add_option("-m", "--mode",
default="intermediate", default="intermediate",
help="interaction mode: novice, intermediate, " help="interaction mode: novice, intermediate, "
...@@ -1014,12 +1014,15 @@ must specify for any option using that action. ...@@ -1014,12 +1014,15 @@ must specify for any option using that action.
from optparse import OptionParser, SUPPRESS_HELP from optparse import OptionParser, SUPPRESS_HELP
parser = OptionParser() # usually, a help option is added automatically, but that can
parser.add_option("-h", "--help", action="help"), # be suppressed using the add_help_option argument
parser = OptionParser(add_help_option=False)
parser.add_option("-h", "--help", action="help")
parser.add_option("-v", action="store_true", dest="verbose", parser.add_option("-v", action="store_true", dest="verbose",
help="Be moderately verbose") help="Be moderately verbose")
parser.add_option("--file", dest="filename", parser.add_option("--file", dest="filename",
help="Input file to read data from"), help="Input file to read data from")
parser.add_option("--secret", help=SUPPRESS_HELP) parser.add_option("--secret", help=SUPPRESS_HELP)
If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, it If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, it
......
...@@ -41,7 +41,7 @@ of the debugger is:: ...@@ -41,7 +41,7 @@ of the debugger is::
:file:`pdb.py` can also be invoked as a script to debug other scripts. For :file:`pdb.py` can also be invoked as a script to debug other scripts. For
example:: example::
python -m pdb myscript.py python3 -m pdb myscript.py
When invoked as a script, pdb will automatically enter post-mortem debugging if When invoked as a script, pdb will automatically enter post-mortem debugging if
the program being debugged exits abnormally. After post-mortem debugging (or the program being debugged exits abnormally. After post-mortem debugging (or
......
...@@ -206,7 +206,7 @@ support history save/restore. :: ...@@ -206,7 +206,7 @@ support history save/restore. ::
class HistoryConsole(code.InteractiveConsole): class HistoryConsole(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>", def __init__(self, locals=None, filename="<console>",
histfile=os.path.expanduser("~/.console-history")): histfile=os.path.expanduser("~/.console-history")):
code.InteractiveConsole.__init__(self) code.InteractiveConsole.__init__(self, locals, filename)
self.init_history(histfile) self.init_history(histfile)
def init_history(self, histfile): def init_history(self, histfile):
......
.. _someos: .. _someos:
********************************** **********************************
...@@ -8,7 +7,7 @@ Optional Operating System Services ...@@ -8,7 +7,7 @@ Optional Operating System Services
The modules described in this chapter provide interfaces to operating system The modules described in this chapter provide interfaces to operating system
features that are available on selected operating systems only. The interfaces features that are available on selected operating systems only. The interfaces
are generally modeled after the Unix or C interfaces but they are available on are generally modeled after the Unix or C interfaces but they are available on
some other systems as well (e.g. Windows or NT). Here's an overview: some other systems as well (e.g. Windows). Here's an overview:
.. toctree:: .. toctree::
......
:mod:`spwd` --- The shadow password database :mod:`spwd` --- The shadow password database
============================================ ============================================
...@@ -48,7 +47,7 @@ below, see ``<shadow.h>``): ...@@ -48,7 +47,7 @@ below, see ``<shadow.h>``):
The sp_nam and sp_pwd items are strings, all others are integers. The sp_nam and sp_pwd items are strings, all others are integers.
:exc:`KeyError` is raised if the entry asked for cannot be found. :exc:`KeyError` is raised if the entry asked for cannot be found.
It defines the following items: The following functions are defined:
.. function:: getspnam(name) .. function:: getspnam(name)
......
:mod:`ssl` --- SSL wrapper for socket objects :mod:`ssl` --- SSL wrapper for socket objects
==================================================================== =============================================
.. module:: ssl .. module:: ssl
:synopsis: SSL wrapper for socket objects :synopsis: SSL wrapper for socket objects
...@@ -13,32 +12,29 @@ ...@@ -13,32 +12,29 @@
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
This module provides access to Transport Layer Security (often known This module provides access to Transport Layer Security (often known as "Secure
as "Secure Sockets Layer") encryption and peer authentication Sockets Layer") encryption and peer authentication facilities for network
facilities for network sockets, both client-side and server-side. sockets, both client-side and server-side. This module uses the OpenSSL
This module uses the OpenSSL library. It is available on all modern library. It is available on all modern Unix systems, Windows, Mac OS X, and
Unix systems, Windows, Mac OS X, and probably additional probably additional platforms, as long as OpenSSL is installed on that platform.
platforms, as long as OpenSSL is installed on that platform.
.. note:: .. note::
Some behavior may be platform dependent, since calls are made to the operating Some behavior may be platform dependent, since calls are made to the
system socket APIs. The installed version of OpenSSL may also cause operating system socket APIs. The installed version of OpenSSL may also
variations in behavior. cause variations in behavior.
This section documents the objects and functions in the ``ssl`` module; This section documents the objects and functions in the ``ssl`` module; for more
for more general information about TLS, SSL, and certificates, the general information about TLS, SSL, and certificates, the reader is referred to
reader is referred to the documents in the "See Also" section at the documents in the "See Also" section at the bottom.
the bottom.
This module provides a class, :class:`ssl.SSLSocket`, which is This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
derived from the :class:`socket.socket` type, and provides :class:`socket.socket` type, and provides a socket-like wrapper that also
a socket-like wrapper that also encrypts and decrypts the data encrypts and decrypts the data going over the socket with SSL. It supports
going over the socket with SSL. It supports additional additional :meth:`read` and :meth:`write` methods, along with a method,
:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`, :meth:`getpeercert`, to retrieve the certificate of the other side of the
to retrieve the certificate of the other side of the connection, and connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
a method, :meth:`cipher`, to retrieve the cipher being used for the the secure connection.
secure connection.
Functions, Constants, and Exceptions Functions, Constants, and Exceptions
------------------------------------ ------------------------------------
...@@ -46,31 +42,33 @@ Functions, Constants, and Exceptions ...@@ -46,31 +42,33 @@ Functions, Constants, and Exceptions
.. exception:: SSLError .. exception:: SSLError
Raised to signal an error from the underlying SSL implementation. This Raised to signal an error from the underlying SSL implementation. This
signifies some problem in the higher-level signifies some problem in the higher-level encryption and authentication
encryption and authentication layer that's superimposed on the underlying layer that's superimposed on the underlying network connection. This error
network connection. This error is a subtype of :exc:`socket.error`, which is a subtype of :exc:`socket.error`, which in turn is a subtype of
in turn is a subtype of :exc:`IOError`. :exc:`IOError`.
.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True) .. function:: wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True)
Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
of :class:`socket.socket`, which wraps the underlying socket in an SSL context. of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
For client-side sockets, the context construction is lazy; if the underlying socket isn't the underlying socket in an SSL context. For client-side sockets, the
connected yet, the context construction will be performed after :meth:`connect` is called context construction is lazy; if the underlying socket isn't connected yet,
on the socket. For server-side sockets, if the socket has no remote peer, it is assumed the context construction will be performed after :meth:`connect` is called on
to be a listening socket, and the server-side SSL wrapping is automatically performed the socket. For server-side sockets, if the socket has no remote peer, it is
on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may assumed to be a listening socket, and the server-side SSL wrapping is
raise :exc:`SSLError`. automatically performed on client connections accepted via the :meth:`accept`
method. :func:`wrap_socket` may raise :exc:`SSLError`.
The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate
to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates` The ``keyfile`` and ``certfile`` parameters specify optional files which
for more information on how the certificate is stored in the ``certfile``. contain a certificate to be used to identify the local side of the
connection. See the discussion of :ref:`ssl-certificates` for more
Often the private key is stored information on how the certificate is stored in the ``certfile``.
in the same file as the certificate; in this case, only the ``certfile`` parameter need be
passed. If the private key is stored in a separate file, both parameters must be used. Often the private key is stored in the same file as the certificate; in this
If the private key is stored in the ``certfile``, it should come before the first certificate case, only the ``certfile`` parameter need be passed. If the private key is
in the certificate chain:: stored in a separate file, both parameters must be used. If the private key
is stored in the ``certfile``, it should come before the first certificate in
the certificate chain::
-----BEGIN RSA PRIVATE KEY----- -----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ... ... (private key in base64 encoding) ...
...@@ -79,31 +77,33 @@ Functions, Constants, and Exceptions ...@@ -79,31 +77,33 @@ Functions, Constants, and Exceptions
... (certificate in base64 PEM encoding) ... ... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE----- -----END CERTIFICATE-----
The parameter ``server_side`` is a boolean which identifies whether server-side or client-side The parameter ``server_side`` is a boolean which identifies whether
behavior is desired from this socket. server-side or client-side behavior is desired from this socket.
The parameter ``cert_reqs`` specifies whether a certificate is The parameter ``cert_reqs`` specifies whether a certificate is required from
required from the other side of the connection, and whether it will the other side of the connection, and whether it will be validated if
be validated if provided. It must be one of the three values provided. It must be one of the three values :const:`CERT_NONE`
:const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
but validated if provided), or :const:`CERT_REQUIRED` (required and if provided), or :const:`CERT_REQUIRED` (required and validated). If the
validated). If the value of this parameter is not :const:`CERT_NONE`, then value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
the ``ca_certs`` parameter must point to a file of CA certificates. parameter must point to a file of CA certificates.
The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, The ``ca_certs`` file contains a set of concatenated "certification
which are used to validate certificates passed from the other end of the connection. authority" certificates, which are used to validate certificates passed from
See the discussion of :ref:`ssl-certificates` for more information about how to arrange the other end of the connection. See the discussion of
the certificates in this file. :ref:`ssl-certificates` for more information about how to arrange the
certificates in this file.
The parameter ``ssl_version`` specifies which version of the SSL protocol to use.
Typically, the server chooses a particular protocol version, and the client The parameter ``ssl_version`` specifies which version of the SSL protocol to
must adapt to the server's choice. Most of the versions are not interoperable use. Typically, the server chooses a particular protocol version, and the
with the other versions. If not specified, for client-side operation, the client must adapt to the server's choice. Most of the versions are not
default SSL version is SSLv3; for server-side operation, SSLv23. These interoperable with the other versions. If not specified, for client-side
version selections provide the most compatibility with other versions. operation, the default SSL version is SSLv3; for server-side operation,
SSLv23. These version selections provide the most compatibility with other
Here's a table showing which versions in a client (down the side) versions.
can connect to which versions in a server (along the top):
Here's a table showing which versions in a client (down the side) can connect
to which versions in a server (along the top):
.. table:: .. table::
...@@ -116,51 +116,52 @@ Functions, Constants, and Exceptions ...@@ -116,51 +116,52 @@ Functions, Constants, and Exceptions
*TLSv1* no no yes yes *TLSv1* no no yes yes
======================== ========= ========= ========== ========= ======================== ========= ========= ========== =========
In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), an
an SSLv2 client could not connect to an SSLv23 server. SSLv2 client could not connect to an SSLv23 server.
The parameter ``do_handshake_on_connect`` specifies whether to do the SSL The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
handshake automatically after doing a :meth:`socket.connect`, or whether the handshake automatically after doing a :meth:`socket.connect`, or whether the
application program will call it explicitly, by invoking the :meth:`SSLSocket.do_handshake` application program will call it explicitly, by invoking the
method. Calling :meth:`SSLSocket.do_handshake` explicitly gives the program control over :meth:`SSLSocket.do_handshake` method. Calling
the blocking behavior of the socket I/O involved in the handshake. :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
blocking behavior of the socket I/O involved in the handshake.
The parameter ``suppress_ragged_eofs`` specifies how the :meth:`SSLSocket.read` The parameter ``suppress_ragged_eofs`` specifies how the
method should signal unexpected EOF from the other end of the connection. If specified :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
as :const:`True` (the default), it returns a normal EOF in response to unexpected of the connection. If specified as :const:`True` (the default), it returns a
EOF errors raised from the underlying socket; if :const:`False`, it will raise normal EOF in response to unexpected EOF errors raised from the underlying
the exceptions back to the caller. socket; if :const:`False`, it will raise the exceptions back to the caller.
.. function:: RAND_status() .. function:: RAND_status()
Returns True if the SSL pseudo-random number generator has been Returns True if the SSL pseudo-random number generator has been seeded with
seeded with 'enough' randomness, and False otherwise. You can use 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
:func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
of the pseudo-random number generator. number generator.
.. function:: RAND_egd(path) .. function:: RAND_egd(path)
If you are running an entropy-gathering daemon (EGD) somewhere, and ``path`` If you are running an entropy-gathering daemon (EGD) somewhere, and ``path``
is the pathname of a socket connection open to it, this will read is the pathname of a socket connection open to it, this will read 256 bytes
256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator of randomness from the socket, and add it to the SSL pseudo-random number
to increase the security of generated secret keys. This is typically only generator to increase the security of generated secret keys. This is
necessary on systems without better sources of randomness. typically only necessary on systems without better sources of randomness.
See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
sources of entropy-gathering daemons. of entropy-gathering daemons.
.. function:: RAND_add(bytes, entropy) .. function:: RAND_add(bytes, entropy)
Mixes the given ``bytes`` into the SSL pseudo-random number generator. Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
The parameter ``entropy`` (a float) is a lower bound on the entropy parameter ``entropy`` (a float) is a lower bound on the entropy contained in
contained in string (so you can always use :const:`0.0`). string (so you can always use :const:`0.0`). See :rfc:`1750` for more
See :rfc:`1750` for more information on sources of entropy. information on sources of entropy.
.. function:: cert_time_to_seconds(timestring) .. function:: cert_time_to_seconds(timestring)
Returns a floating-point value containing a normal seconds-after-the-epoch time Returns a floating-point value containing a normal seconds-after-the-epoch
value, given the time-string representing the "notBefore" or "notAfter" date time value, given the time-string representing the "notBefore" or "notAfter"
from a certificate. date from a certificate.
Here's an example:: Here's an example::
...@@ -172,50 +173,47 @@ Functions, Constants, and Exceptions ...@@ -172,50 +173,47 @@ Functions, Constants, and Exceptions
'Wed May 9 00:00:00 2007' 'Wed May 9 00:00:00 2007'
>>> >>>
.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) .. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None)
Given the address ``addr`` of an SSL-protected server, as a Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
(*hostname*, *port-number*) pair, fetches the server's certificate, *port-number*) pair, fetches the server's certificate, and returns it as a
and returns it as a PEM-encoded string. If ``ssl_version`` is PEM-encoded string. If ``ssl_version`` is specified, uses that version of
specified, uses that version of the SSL protocol to attempt to the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
connect to the server. If ``ca_certs`` is specified, it should be specified, it should be a file containing a list of root certificates, the
a file containing a list of root certificates, the same format as same format as used for the same parameter in :func:`wrap_socket`. The call
used for the same parameter in :func:`wrap_socket`. The call will will attempt to validate the server certificate against that set of root
attempt to validate the server certificate against that set of root
certificates, and will fail if the validation attempt fails. certificates, and will fail if the validation attempt fails.
.. function:: DER_cert_to_PEM_cert (DER_cert_bytes) .. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
string version of the same certificate. string version of the same certificate.
.. function:: PEM_cert_to_DER_cert (PEM_cert_string) .. function:: PEM_cert_to_DER_cert(PEM_cert_string)
Given a certificate as an ASCII PEM string, returns a DER-encoded Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
sequence of bytes for that same certificate. bytes for that same certificate.
.. data:: CERT_NONE .. data:: CERT_NONE
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
when no certificates will be required or validated from the other certificates will be required or validated from the other side of the socket
side of the socket connection. connection.
.. data:: CERT_OPTIONAL .. data:: CERT_OPTIONAL
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
when no certificates will be required from the other side of the certificates will be required from the other side of the socket connection,
socket connection, but if they are provided, will be validated. but if they are provided, will be validated. Note that use of this setting
Note that use of this setting requires a valid certificate requires a valid certificate validation file also be passed as a value of the
validation file also be passed as a value of the ``ca_certs`` ``ca_certs`` parameter.
parameter.
.. data:: CERT_REQUIRED .. data:: CERT_REQUIRED
Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
when certificates will be required from the other side of the certificates will be required from the other side of the socket connection.
socket connection. Note that use of this setting requires a valid certificate Note that use of this setting requires a valid certificate validation file
validation file also be passed as a value of the ``ca_certs`` also be passed as a value of the ``ca_certs`` parameter.
parameter.
.. data:: PROTOCOL_SSLv2 .. data:: PROTOCOL_SSLv2
...@@ -223,22 +221,21 @@ Functions, Constants, and Exceptions ...@@ -223,22 +221,21 @@ Functions, Constants, and Exceptions
.. data:: PROTOCOL_SSLv23 .. data:: PROTOCOL_SSLv23
Selects SSL version 2 or 3 as the channel encryption protocol. Selects SSL version 2 or 3 as the channel encryption protocol. This is a
This is a setting to use with servers for maximum compatibility setting to use with servers for maximum compatibility with the other end of
with the other end of an SSL connection, but it may cause the an SSL connection, but it may cause the specific ciphers chosen for the
specific ciphers chosen for the encryption to be of fairly low encryption to be of fairly low quality.
quality.
.. data:: PROTOCOL_SSLv3 .. data:: PROTOCOL_SSLv3
Selects SSL version 3 as the channel encryption protocol. Selects SSL version 3 as the channel encryption protocol. For clients, this
For clients, this is the maximally compatible SSL variant. is the maximally compatible SSL variant.
.. data:: PROTOCOL_TLSv1 .. data:: PROTOCOL_TLSv1
Selects TLS version 1 as the channel encryption protocol. This is Selects TLS version 1 as the channel encryption protocol. This is the most
the most modern version, and probably the best choice for maximum modern version, and probably the best choice for maximum protection, if both
protection, if both sides can speak it. sides can speak it.
SSLSocket Objects SSLSocket Objects
...@@ -247,25 +244,23 @@ SSLSocket Objects ...@@ -247,25 +244,23 @@ SSLSocket Objects
.. method:: SSLSocket.read(nbytes=1024, buffer=None) .. method:: SSLSocket.read(nbytes=1024, buffer=None)
Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them. Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them.
If the ``buffer`` is specified, it will attempt to read into the buffer If the ``buffer`` is specified, it will attempt to read into the buffer the
the minimum of the size of the buffer and ``nbytes``, if that is specified. minimum of the size of the buffer and ``nbytes``, if that is specified. If
If no buffer is specified, an immutable buffer is allocated and returned no buffer is specified, an immutable buffer is allocated and returned with
with the data read from the socket. the data read from the socket.
.. method:: SSLSocket.write(data) .. method:: SSLSocket.write(data)
Writes the ``data`` to the other side of the connection, using the Writes the ``data`` to the other side of the connection, using the SSL
SSL channel to encrypt. Returns the number of bytes written. channel to encrypt. Returns the number of bytes written.
.. method:: SSLSocket.do_handshake() .. method:: SSLSocket.do_handshake()
Performs the SSL setup handshake. If the socket is non-blocking, Performs the SSL setup handshake. If the socket is non-blocking, this method
this method may raise :exc:`SSLError` with the value of the exception may raise :exc:`SSLError` with the value of the exception instance's
instance's ``args[0]`` ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
being either :const:`SSL_ERROR_WANT_READ` or :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
:const:`SSL_ERROR_WANT_WRITE`, and should be called again until raising those exceptions. Here's an example of how to do that::
it stops raising those exceptions. Here's an example of how to do
that::
while True: while True:
try: try:
...@@ -281,34 +276,31 @@ SSLSocket Objects ...@@ -281,34 +276,31 @@ SSLSocket Objects
.. method:: SSLSocket.unwrap() .. method:: SSLSocket.unwrap()
Performs the SSL shutdown handshake, which removes the TLS layer Performs the SSL shutdown handshake, which removes the TLS layer from the
from the underlying socket, and returns the underlying socket underlying socket, and returns the underlying socket object. This can be
object. This can be used to go from encrypted operation over a used to go from encrypted operation over a connection to unencrypted. The
connection to unencrypted. The returned socket should always be returned socket should always be used for further communication with the
used for further communication with the other side of the other side of the connection, rather than the original socket
connection, rather than the original socket
.. method:: SSLSocket.getpeercert(binary_form=False) .. method:: SSLSocket.getpeercert(binary_form=False)
If there is no certificate for the peer on the other end of the If there is no certificate for the peer on the other end of the connection,
connection, returns ``None``. returns ``None``.
If the parameter ``binary_form`` is :const:`False`, and a If the parameter ``binary_form`` is :const:`False`, and a certificate was
certificate was received from the peer, this method returns a received from the peer, this method returns a :class:`dict` instance. If the
:class:`dict` instance. If the certificate was not validated, the certificate was not validated, the dict is empty. If the certificate was
dict is empty. If the certificate was validated, it returns a dict validated, it returns a dict with the keys ``subject`` (the principal for
with the keys ``subject`` (the principal for which the certificate which the certificate was issued), and ``notAfter`` (the time after which the
was issued), and ``notAfter`` (the time after which the certificate certificate should not be trusted). The certificate was already validated,
should not be trusted). The certificate was already validated, so so the ``notBefore`` and ``issuer`` fields are not returned. If a
the ``notBefore`` and ``issuer`` fields are not returned. If a certificate contains an instance of the *Subject Alternative Name* extension
certificate contains an instance of the *Subject Alternative Name* (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
extension (see :rfc:`3280`), there will also be a dictionary.
``subjectAltName`` key in the dictionary.
The "subject" field is a tuple containing the sequence of relative The "subject" field is a tuple containing the sequence of relative
distinguished names (RDNs) given in the certificate's data distinguished names (RDNs) given in the certificate's data structure for the
structure for the principal, and each RDN is a sequence of principal, and each RDN is a sequence of name-value pairs::
name-value pairs::
{'notAfter': 'Feb 16 16:54:50 2013 GMT', {'notAfter': 'Feb 16 16:54:50 2013 GMT',
'subject': ((('countryName', 'US'),), 'subject': ((('countryName', 'US'),),
...@@ -318,31 +310,28 @@ SSLSocket Objects ...@@ -318,31 +310,28 @@ SSLSocket Objects
(('organizationalUnitName', 'SSL'),), (('organizationalUnitName', 'SSL'),),
(('commonName', 'somemachine.python.org'),))} (('commonName', 'somemachine.python.org'),))}
If the ``binary_form`` parameter is :const:`True`, and a If the ``binary_form`` parameter is :const:`True`, and a certificate was
certificate was provided, this method returns the DER-encoded form provided, this method returns the DER-encoded form of the entire certificate
of the entire certificate as a sequence of bytes, or :const:`None` if the as a sequence of bytes, or :const:`None` if the peer did not provide a
peer did not provide a certificate. This return certificate. This return value is independent of validation; if validation
value is independent of validation; if validation was required was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
(:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
been validated, but if :const:`CERT_NONE` was used to establish the been validated, but if :const:`CERT_NONE` was used to establish the
connection, the certificate, if present, will not have been validated. connection, the certificate, if present, will not have been validated.
.. method:: SSLSocket.cipher() .. method:: SSLSocket.cipher()
Returns a three-value tuple containing the name of the cipher being Returns a three-value tuple containing the name of the cipher being used, the
used, the version of the SSL protocol that defines its use, and the version of the SSL protocol that defines its use, and the number of secret
number of secret bits being used. If no connection has been bits being used. If no connection has been established, returns ``None``.
established, returns ``None``.
.. method:: SSLSocket.unwrap() .. method:: SSLSocket.unwrap()
Performs the SSL shutdown handshake, which removes the TLS layer Performs the SSL shutdown handshake, which removes the TLS layer from the
from the underlying socket, and returns the underlying socket underlying socket, and returns the underlying socket object. This can be
object. This can be used to go from encrypted operation over a used to go from encrypted operation over a connection to unencrypted. The
connection to unencrypted. The returned socket should always be returned socket should always be used for further communication with the
used for further communication with the other side of the other side of the connection, rather than the original socket.
connection, rather than the original socket
.. index:: single: certificates .. index:: single: certificates
...@@ -353,57 +342,54 @@ SSLSocket Objects ...@@ -353,57 +342,54 @@ SSLSocket Objects
Certificates Certificates
------------ ------------
Certificates in general are part of a public-key / private-key system. In this system, each *principal*, Certificates in general are part of a public-key / private-key system. In this
(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key. system, each *principal*, (which may be a machine, or a person, or an
One part of the key is public, and is called the *public key*; the other part is kept secret, and is called organization) is assigned a unique two-part encryption key. One part of the key
the *private key*. The two parts are related, in that if you encrypt a message with one of the parts, you can is public, and is called the *public key*; the other part is kept secret, and is
decrypt it with the other part, and **only** with the other part. called the *private key*. The two parts are related, in that if you encrypt a
message with one of the parts, you can decrypt it with the other part, and
A certificate contains information about two principals. It contains **only** with the other part.
the name of a *subject*, and the subject's public key. It also
contains a statement by a second principal, the *issuer*, that the A certificate contains information about two principals. It contains the name
subject is who he claims to be, and that this is indeed the subject's of a *subject*, and the subject's public key. It also contains a statement by a
public key. The issuer's statement is signed with the issuer's second principal, the *issuer*, that the subject is who he claims to be, and
private key, which only the issuer knows. However, anyone can verify that this is indeed the subject's public key. The issuer's statement is signed
the issuer's statement by finding the issuer's public key, decrypting with the issuer's private key, which only the issuer knows. However, anyone can
the statement with it, and comparing it to the other information in verify the issuer's statement by finding the issuer's public key, decrypting the
the certificate. The certificate also contains information about the statement with it, and comparing it to the other information in the certificate.
time period over which it is valid. This is expressed as two fields, The certificate also contains information about the time period over which it is
called "notBefore" and "notAfter". valid. This is expressed as two fields, called "notBefore" and "notAfter".
In the Python use of certificates, a client or server In the Python use of certificates, a client or server can use a certificate to
can use a certificate to prove who they are. The other prove who they are. The other side of a network connection can also be required
side of a network connection can also be required to produce a certificate, to produce a certificate, and that certificate can be validated to the
and that certificate can be validated to the satisfaction satisfaction of the client or server that requires such validation. The
of the client or server that requires such validation. connection attempt can be set to raise an exception if the validation fails.
The connection attempt can be set to raise an exception if Validation is done automatically, by the underlying OpenSSL framework; the
the validation fails. Validation is done application need not concern itself with its mechanics. But the application
automatically, by the underlying OpenSSL framework; the does usually need to provide sets of certificates to allow this process to take
application need not concern itself with its mechanics. place.
But the application does usually need to provide
sets of certificates to allow this process to take place. Python uses files to contain certificates. They should be formatted as "PEM"
(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
Python uses files to contain certificates. They should be formatted and a footer line::
as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped
with a header line and a footer line::
-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ... ... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE----- -----END CERTIFICATE-----
The Python files which contain certificates can contain a sequence The Python files which contain certificates can contain a sequence of
of certificates, sometimes called a *certificate chain*. This chain certificates, sometimes called a *certificate chain*. This chain should start
should start with the specific certificate for the principal who "is" with the specific certificate for the principal who "is" the client or server,
the client or server, and then the certificate for the issuer of that and then the certificate for the issuer of that certificate, and then the
certificate, and then the certificate for the issuer of *that* certificate, certificate for the issuer of *that* certificate, and so on up the chain till
and so on up the chain till you get to a certificate which is *self-signed*, you get to a certificate which is *self-signed*, that is, a certificate which
that is, a certificate which has the same subject and issuer, has the same subject and issuer, sometimes called a *root certificate*. The
sometimes called a *root certificate*. The certificates should just certificates should just be concatenated together in the certificate file. For
be concatenated together in the certificate file. For example, suppose example, suppose we had a three certificate chain, from our server certificate
we had a three certificate chain, from our server certificate to the to the certificate of the certification authority that signed our server
certificate of the certification authority that signed our server certificate, certificate, to the root certificate of the agency which issued the
to the root certificate of the agency which issued the certification authority's certification authority's certificate::
certificate::
-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE-----
... (certificate for your server)... ... (certificate for your server)...
...@@ -417,32 +403,29 @@ certificate:: ...@@ -417,32 +403,29 @@ certificate::
If you are going to require validation of the other side of the connection's If you are going to require validation of the other side of the connection's
certificate, you need to provide a "CA certs" file, filled with the certificate certificate, you need to provide a "CA certs" file, filled with the certificate
chains for each issuer you are willing to trust. Again, this file just chains for each issuer you are willing to trust. Again, this file just contains
contains these chains concatenated together. For validation, Python will these chains concatenated together. For validation, Python will use the first
use the first chain it finds in the file which matches. chain it finds in the file which matches. Some "standard" root certificates are
Some "standard" root certificates are available from various certification available from various certification authorities: `CACert.org
authorities: <http://www.cacert.org/index.php?id=3>`_, `Thawte
`CACert.org <http://www.cacert.org/index.php?id=3>`_, <http://www.thawte.com/roots/>`_, `Verisign
`Thawte <http://www.thawte.com/roots/>`_, <http://www.verisign.com/support/roots.html>`_, `Positive SSL
`Verisign <http://www.verisign.com/support/roots.html>`_, <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
`Positive SSL <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ (used by python.org), (used by python.org), `Equifax and GeoTrust
`Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_. <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
In general, if you are using In general, if you are using SSL3 or TLS1, you don't need to put the full chain
SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file; in your "CA certs" file; you only need the root certificates, and the remote
you only need the root certificates, and the remote peer is supposed to peer is supposed to furnish the other certificates necessary to chain from its
furnish the other certificates necessary to chain from its certificate to certificate to a root certificate. See :rfc:`4158` for more discussion of the
a root certificate. way in which certification chains can be built.
See :rfc:`4158` for more discussion of the way in which
certification chains can be built. If you are going to create a server that provides SSL-encrypted connection
services, you will need to acquire a certificate for that service. There are
If you are going to create a server that provides SSL-encrypted many ways of acquiring appropriate certificates, such as buying one from a
connection services, you will need to acquire a certificate for that certification authority. Another common practice is to generate a self-signed
service. There are many ways of acquiring appropriate certificates, certificate. The simplest way to do this is with the OpenSSL package, using
such as buying one from a certification authority. Another common something like the following::
practice is to generate a self-signed certificate. The simplest
way to do this is with the OpenSSL package, using something like
the following::
% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key Generating a 1024 bit RSA private key
...@@ -466,9 +449,9 @@ the following:: ...@@ -466,9 +449,9 @@ the following::
Email Address []:ops@myserver.mygroup.myorganization.com Email Address []:ops@myserver.mygroup.myorganization.com
% %
The disadvantage of a self-signed certificate is that it is its The disadvantage of a self-signed certificate is that it is its own root
own root certificate, and no one else will have it in their cache certificate, and no one else will have it in their cache of known (and trusted)
of known (and trusted) root certificates. root certificates.
Examples Examples
...@@ -477,7 +460,8 @@ Examples ...@@ -477,7 +460,8 @@ Examples
Testing for SSL support Testing for SSL support
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
To test for the presence of SSL support in a Python installation, user code should use the following idiom:: To test for the presence of SSL support in a Python installation, user code
should use the following idiom::
try: try:
import ssl import ssl
...@@ -489,8 +473,8 @@ To test for the presence of SSL support in a Python installation, user code shou ...@@ -489,8 +473,8 @@ To test for the presence of SSL support in a Python installation, user code shou
Client-side operation Client-side operation
^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
This example connects to an SSL server, prints the server's address and certificate, This example connects to an SSL server, prints the server's address and
sends some bytes, and reads part of the response:: certificate, sends some bytes, and reads part of the response::
import socket, ssl, pprint import socket, ssl, pprint
...@@ -518,8 +502,8 @@ sends some bytes, and reads part of the response:: ...@@ -518,8 +502,8 @@ sends some bytes, and reads part of the response::
# note that closing the SSLSocket will also close the underlying socket # note that closing the SSLSocket will also close the underlying socket
ssl_sock.close() ssl_sock.close()
As of September 6, 2007, the certificate printed by this program As of September 6, 2007, the certificate printed by this program looked like
looked like this:: this::
{'notAfter': 'May 8 23:59:59 2009 GMT', {'notAfter': 'May 8 23:59:59 2009 GMT',
'subject': ((('serialNumber', '2497886'),), 'subject': ((('serialNumber', '2497886'),),
...@@ -542,9 +526,9 @@ which is a fairly poorly-formed ``subject`` field. ...@@ -542,9 +526,9 @@ which is a fairly poorly-formed ``subject`` field.
Server-side operation Server-side operation
^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
For server operation, typically you'd need to have a server certificate, and private key, each in a file. For server operation, typically you'd need to have a server certificate, and
You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients private key, each in a file. You'd open a socket, bind it to a port, call
to connect:: :meth:`listen` on it, then start waiting for clients to connect::
import socket, ssl import socket, ssl
...@@ -552,8 +536,9 @@ to connect:: ...@@ -552,8 +536,9 @@ to connect::
bindsocket.bind(('myaddr.mydomain.com', 10023)) bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.listen(5) bindsocket.listen(5)
When one did, you'd call :meth:`accept` on the socket to get the new socket from the other When one did, you'd call :meth:`accept` on the socket to get the new socket from
end, and use :func:`wrap_socket` to create a server-side SSL context for it:: the other end, and use :func:`wrap_socket` to create a server-side SSL context
for it::
while True: while True:
newsocket, fromaddr = bindsocket.accept() newsocket, fromaddr = bindsocket.accept()
...@@ -564,7 +549,8 @@ end, and use :func:`wrap_socket` to create a server-side SSL context for it:: ...@@ -564,7 +549,8 @@ end, and use :func:`wrap_socket` to create a server-side SSL context for it::
ssl_version=ssl.PROTOCOL_TLSv1) ssl_version=ssl.PROTOCOL_TLSv1)
deal_with_client(connstream) deal_with_client(connstream)
Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: Then you'd read data from the ``connstream`` and do something with it till you
are finished with the client (or the client is finished with you)::
def deal_with_client(connstream): def deal_with_client(connstream):
......
:mod:`stat` --- Interpreting :func:`stat` results :mod:`stat` --- Interpreting :func:`stat` results
================================================= =================================================
.. module:: stat .. module:: stat
:synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat(). :synopsis: Utilities for interpreting the results of os.stat(),
os.lstat() and os.fstat().
.. sectionauthor:: Skip Montanaro <skip@automatrix.com> .. sectionauthor:: Skip Montanaro <skip@automatrix.com>
......
...@@ -479,19 +479,19 @@ these rules. The methods of :class:`Template` are: ...@@ -479,19 +479,19 @@ these rules. The methods of :class:`Template` are:
The constructor takes a single argument which is the template string. The constructor takes a single argument which is the template string.
.. method:: substitute(mapping[, **kws]) .. method:: substitute(mapping, **kwds)
Performs the template substitution, returning a new string. *mapping* is Performs the template substitution, returning a new string. *mapping* is
any dictionary-like object with keys that match the placeholders in the any dictionary-like object with keys that match the placeholders in the
template. Alternatively, you can provide keyword arguments, where the template. Alternatively, you can provide keyword arguments, where the
keywords are the placeholders. When both *mapping* and *kws* are given keywords are the placeholders. When both *mapping* and *kwds* are given
and there are duplicates, the placeholders from *kws* take precedence. and there are duplicates, the placeholders from *kwds* take precedence.
.. method:: safe_substitute(mapping[, **kws]) .. method:: safe_substitute(mapping, **kwds)
Like :meth:`substitute`, except that if placeholders are missing from Like :meth:`substitute`, except that if placeholders are missing from
*mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the
original placeholder will appear in the resulting string intact. Also, original placeholder will appear in the resulting string intact. Also,
unlike with :meth:`substitute`, any other appearances of the ``$`` will unlike with :meth:`substitute`, any other appearances of the ``$`` will
simply return ``$`` instead of raising :exc:`ValueError`. simply return ``$`` instead of raising :exc:`ValueError`.
......
:mod:`stringprep` --- Internet String Preparation :mod:`stringprep` --- Internet String Preparation
================================================= =================================================
......
.. _stringservices: .. _stringservices:
*************** ***************
......
:mod:`struct` --- Interpret bytes as packed binary data :mod:`struct` --- Interpret bytes as packed binary data
========================================================= =======================================================
.. module:: struct .. module:: struct
:synopsis: Interpret bytes as packed binary data. :synopsis: Interpret bytes as packed binary data.
...@@ -46,7 +45,7 @@ The module defines the following exception and functions: ...@@ -46,7 +45,7 @@ The module defines the following exception and functions:
(``len(bytes)`` must equal ``calcsize(fmt)``). (``len(bytes)`` must equal ``calcsize(fmt)``).
.. function:: unpack_from(fmt, buffer[,offset=0]) .. function:: unpack_from(fmt, buffer, offset=0)
Unpack the *buffer* according to the given format. The result is a tuple even Unpack the *buffer* according to the given format. The result is a tuple even
if it contains exactly one item. The *buffer* must contain at least the amount if it contains exactly one item. The *buffer* must contain at least the amount
...@@ -286,7 +285,7 @@ The :mod:`struct` module also defines the following type: ...@@ -286,7 +285,7 @@ The :mod:`struct` module also defines the following type:
(``len(bytes)`` must equal :attr:`self.size`). (``len(bytes)`` must equal :attr:`self.size`).
.. method:: unpack_from(buffer[, offset=0]) .. method:: unpack_from(buffer, offset=0)
Identical to the :func:`unpack_from` function, using the compiled format. Identical to the :func:`unpack_from` function, using the compiled format.
(``len(buffer[offset:])`` must be at least :attr:`self.size`). (``len(buffer[offset:])`` must be at least :attr:`self.size`).
......
:mod:`subprocess` --- Subprocess management :mod:`subprocess` --- Subprocess management
=========================================== ===========================================
...@@ -121,9 +120,10 @@ This module defines one class called :class:`Popen`: ...@@ -121,9 +120,10 @@ This module defines one class called :class:`Popen`:
.. note:: .. note::
This feature is only available if Python is built with universal newline support This feature is only available if Python is built with universal newline
(the default). Also, the newlines attribute of the file objects :attr:`stdout`, support (the default). Also, the newlines attribute of the file objects
:attr:`stdin` and :attr:`stderr` are not updated by the :meth:`communicate` method. :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
:meth:`communicate` method.
The *startupinfo* and *creationflags*, if given, will be passed to the The *startupinfo* and *creationflags*, if given, will be passed to the
underlying CreateProcess() function. They can specify things such as appearance underlying CreateProcess() function. They can specify things such as appearance
......
:mod:`sunau` --- Read and write Sun AU files :mod:`sunau` --- Read and write Sun AU files
============================================ ============================================
......
:mod:`symbol` --- Constants used with Python parse trees :mod:`symbol` --- Constants used with Python parse trees
======================================================== ========================================================
......
:mod:`sys` --- System-specific parameters and functions :mod:`sys` --- System-specific parameters and functions
======================================================= =======================================================
......
:mod:`syslog` --- Unix syslog library routines :mod:`syslog` --- Unix syslog library routines
============================================== ==============================================
......
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
====================================================== ======================================================
.. module:: tabnanny .. module:: tabnanny
:synopsis: Tool for detecting white space related problems in Python source files in a :synopsis: Tool for detecting white space related problems in Python
directory tree. source files in a directory tree.
.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net> .. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. sectionauthor:: Peter Funk <pf@artcom-gmbh.de> .. sectionauthor:: Peter Funk <pf@artcom-gmbh.de>
......
.. _tarfile-mod:
:mod:`tarfile` --- Read and write tar archive files :mod:`tarfile` --- Read and write tar archive files
=================================================== ===================================================
......
:mod:`telnetlib` --- Telnet client :mod:`telnetlib` --- Telnet client
================================== ==================================
...@@ -23,7 +22,7 @@ SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP ...@@ -23,7 +22,7 @@ SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP
Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin). Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).
.. class:: Telnet([host[, port[, timeout]]]) .. class:: Telnet(host=None, port=0[, timeout])
:class:`Telnet` represents a connection to a Telnet server. The instance is :class:`Telnet` represents a connection to a Telnet server. The instance is
initially not connected by default; the :meth:`open` method must be used to initially not connected by default; the :meth:`open` method must be used to
...@@ -60,7 +59,7 @@ Telnet Objects ...@@ -60,7 +59,7 @@ Telnet Objects
:class:`Telnet` instances have the following methods: :class:`Telnet` instances have the following methods:
.. method:: Telnet.read_until(expected[, timeout]) .. method:: Telnet.read_until(expected, timeout=None)
Read until a given byte string, *expected*, is encountered or until *timeout* Read until a given byte string, *expected*, is encountered or until *timeout*
seconds have passed. seconds have passed.
...@@ -123,7 +122,7 @@ Telnet Objects ...@@ -123,7 +122,7 @@ Telnet Objects
This method never blocks. This method never blocks.
.. method:: Telnet.open(host[, port[, timeout]]) .. method:: Telnet.open(host, port=0[, timeout])
Connect to a host. The optional second argument is the port number, which Connect to a host. The optional second argument is the port number, which
defaults to the standard Telnet port (23). The optional *timeout* parameter defaults to the standard Telnet port (23). The optional *timeout* parameter
...@@ -133,7 +132,7 @@ Telnet Objects ...@@ -133,7 +132,7 @@ Telnet Objects
Do not try to reopen an already connected instance. Do not try to reopen an already connected instance.
.. method:: Telnet.msg(msg[, *args]) .. method:: Telnet.msg(msg, *args)
Print a debug message when the debug level is ``>`` 0. If extra arguments are Print a debug message when the debug level is ``>`` 0. If extra arguments are
present, they are substituted in the message using the standard string present, they are substituted in the message using the standard string
...@@ -178,7 +177,7 @@ Telnet Objects ...@@ -178,7 +177,7 @@ Telnet Objects
Multithreaded version of :meth:`interact`. Multithreaded version of :meth:`interact`.
.. method:: Telnet.expect(list[, timeout]) .. method:: Telnet.expect(list, timeout=None)
Read until one from a list of a regular expressions matches. Read until one from a list of a regular expressions matches.
......
:mod:`tempfile` --- Generate temporary files and directories :mod:`tempfile` --- Generate temporary files and directories
============================================================ ============================================================
...@@ -29,7 +28,7 @@ is recommended to use keyword arguments for clarity. ...@@ -29,7 +28,7 @@ is recommended to use keyword arguments for clarity.
The module defines the following user-callable functions: The module defines the following user-callable functions:
.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]) .. function:: TemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None)
Return a file-like object that can be used as a temporary storage area. Return a file-like object that can be used as a temporary storage area.
The file is created using :func:`mkstemp`. It will be destroyed as soon The file is created using :func:`mkstemp`. It will be destroyed as soon
...@@ -53,7 +52,7 @@ The module defines the following user-callable functions: ...@@ -53,7 +52,7 @@ The module defines the following user-callable functions:
:keyword:`with` statement, just like a normal file. :keyword:`with` statement, just like a normal file.
.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]]) .. function:: NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True)
This function operates exactly as :func:`TemporaryFile` does, except that This function operates exactly as :func:`TemporaryFile` does, except that
the file is guaranteed to have a visible name in the file system (on the file is guaranteed to have a visible name in the file system (on
...@@ -68,7 +67,7 @@ The module defines the following user-callable functions: ...@@ -68,7 +67,7 @@ The module defines the following user-callable functions:
be used in a :keyword:`with` statement, just like a normal file. be used in a :keyword:`with` statement, just like a normal file.
.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]]) .. function:: SpooledTemporaryFile(max_size=0, mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None)
This function operates exactly as :func:`TemporaryFile` does, except that This function operates exactly as :func:`TemporaryFile` does, except that
data is spooled in memory until the file size exceeds *max_size*, or data is spooled in memory until the file size exceeds *max_size*, or
...@@ -85,7 +84,7 @@ The module defines the following user-callable functions: ...@@ -85,7 +84,7 @@ The module defines the following user-callable functions:
used in a :keyword:`with` statement, just like a normal file. used in a :keyword:`with` statement, just like a normal file.
.. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]]) .. function:: mkstemp(suffix='', prefix='tmp', dir=None, text=False)
Creates a temporary file in the most secure manner possible. There are Creates a temporary file in the most secure manner possible. There are
no race conditions in the file's creation, assuming that the platform no race conditions in the file's creation, assuming that the platform
...@@ -123,7 +122,7 @@ The module defines the following user-callable functions: ...@@ -123,7 +122,7 @@ The module defines the following user-callable functions:
of that file, in that order. of that file, in that order.
.. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]]) .. function:: mkdtemp(suffix='', prefix='tmp', dir=None)
Creates a temporary directory in the most secure manner possible. There Creates a temporary directory in the most secure manner possible. There
are no race conditions in the directory's creation. The directory is are no race conditions in the directory's creation. The directory is
...@@ -138,7 +137,7 @@ The module defines the following user-callable functions: ...@@ -138,7 +137,7 @@ The module defines the following user-callable functions:
:func:`mkdtemp` returns the absolute pathname of the new directory. :func:`mkdtemp` returns the absolute pathname of the new directory.
.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]]) .. function:: mktemp(suffix='', prefix='tmp', dir=None)
.. deprecated:: 2.3 .. deprecated:: 2.3
Use :func:`mkstemp` instead. Use :func:`mkstemp` instead.
......
:mod:`termios` --- POSIX style tty control :mod:`termios` --- POSIX style tty control
========================================== ==========================================
...@@ -80,11 +79,11 @@ The module defines the following functions: ...@@ -80,11 +79,11 @@ The module defines the following functions:
Convenience functions for common terminal control operations. Convenience functions for common terminal control operations.
.. _termios-example:
Example Example
------- -------
.. _termios-example:
Here's a function that prompts for a password with echoing turned off. Note the Here's a function that prompts for a password with echoing turned off. Note the
technique using a separate :func:`tcgetattr` call and a :keyword:`try` ... technique using a separate :func:`tcgetattr` call and a :keyword:`try` ...
:keyword:`finally` statement to ensure that the old tty attributes are restored :keyword:`finally` statement to ensure that the old tty attributes are restored
......
:mod:`test` --- Regression tests package for Python :mod:`test` --- Regression tests package for Python
=================================================== ===================================================
...@@ -180,7 +179,7 @@ tests. ...@@ -180,7 +179,7 @@ tests.
:mod:`test.support` --- Utility functions for tests :mod:`test.support` --- Utility functions for tests
======================================================== ===================================================
.. module:: test.support .. module:: test.support
:synopsis: Support for Python regression tests. :synopsis: Support for Python regression tests.
...@@ -247,7 +246,7 @@ The :mod:`test.support` module defines the following functions: ...@@ -247,7 +246,7 @@ The :mod:`test.support` module defines the following functions:
tests. tests.
.. function:: requires(resource[, msg]) .. function:: requires(resource, msg=None)
Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
argument to :exc:`ResourceDenied` if it is raised. Always returns true if called argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
...@@ -372,7 +371,7 @@ The :mod:`test.support` module defines the following functions: ...@@ -372,7 +371,7 @@ The :mod:`test.support` module defines the following functions:
The :mod:`test.support` module defines the following classes: The :mod:`test.support` module defines the following classes:
.. class:: TransientResource(exc[, **kwargs]) .. class:: TransientResource(exc, **kwargs)
Instances are a context manager that raises :exc:`ResourceDenied` if the Instances are a context manager that raises :exc:`ResourceDenied` if the
specified exception type is raised. Any keyword arguments are treated as specified exception type is raised. Any keyword arguments are treated as
......
:mod:`textwrap` --- Text wrapping and filling :mod:`textwrap` --- Text wrapping and filling
============================================= =============================================
...@@ -15,16 +14,17 @@ or two text strings, the convenience functions should be good enough; ...@@ -15,16 +14,17 @@ or two text strings, the convenience functions should be good enough;
otherwise, you should use an instance of :class:`TextWrapper` for efficiency. otherwise, you should use an instance of :class:`TextWrapper` for efficiency.
.. function:: wrap(text[, width[, ...]]) .. function:: wrap(text, width=70, **kwargs)
Wraps the single paragraph in *text* (a string) so every line is at most *width* Wraps the single paragraph in *text* (a string) so every line is at most
characters long. Returns a list of output lines, without final newlines. *width* characters long. Returns a list of output lines, without final
newlines.
Optional keyword arguments correspond to the instance attributes of Optional keyword arguments correspond to the instance attributes of
:class:`TextWrapper`, documented below. *width* defaults to ``70``. :class:`TextWrapper`, documented below. *width* defaults to ``70``.
.. function:: fill(text[, width[, ...]]) .. function:: fill(text, width=70, **kwargs)
Wraps the single paragraph in *text*, and returns a single string containing the Wraps the single paragraph in *text*, and returns a single string containing the
wrapped paragraph. :func:`fill` is shorthand for :: wrapped paragraph. :func:`fill` is shorthand for ::
...@@ -70,11 +70,11 @@ indentation from strings that have unwanted whitespace to the left of the text. ...@@ -70,11 +70,11 @@ indentation from strings that have unwanted whitespace to the left of the text.
print(repr(dedent(s))) # prints 'hello\n world\n' print(repr(dedent(s))) # prints 'hello\n world\n'
.. class:: TextWrapper(...) .. class:: TextWrapper(**kwargs)
The :class:`TextWrapper` constructor accepts a number of optional keyword The :class:`TextWrapper` constructor accepts a number of optional keyword
arguments. Each argument corresponds to one instance attribute, so for example arguments. Each keyword argument corresponds to an instance attribute, so
:: for example ::
wrapper = TextWrapper(initial_indent="* ") wrapper = TextWrapper(initial_indent="* ")
......
...@@ -89,7 +89,7 @@ This module defines the following functions and objects: ...@@ -89,7 +89,7 @@ This module defines the following functions and objects:
thread must release it once for each time it has acquired it. thread must release it once for each time it has acquired it.
.. function:: Semaphore([value]) .. function:: Semaphore(value=1)
:noindex: :noindex:
A factory function that returns a new semaphore object. A semaphore manages a A factory function that returns a new semaphore object. A semaphore manages a
...@@ -99,7 +99,7 @@ This module defines the following functions and objects: ...@@ -99,7 +99,7 @@ This module defines the following functions and objects:
given, *value* defaults to 1. given, *value* defaults to 1.
.. function:: BoundedSemaphore([value]) .. function:: BoundedSemaphore(value=1)
A factory function that returns a new bounded semaphore object. A bounded A factory function that returns a new bounded semaphore object. A bounded
semaphore checks to make sure its current value doesn't exceed its initial semaphore checks to make sure its current value doesn't exceed its initial
...@@ -253,7 +253,7 @@ impossible to detect the termination of alien threads. ...@@ -253,7 +253,7 @@ impossible to detect the termination of alien threads.
the *target* argument, if any, with sequential and keyword arguments taken the *target* argument, if any, with sequential and keyword arguments taken
from the *args* and *kwargs* arguments, respectively. from the *args* and *kwargs* arguments, respectively.
.. method:: join([timeout]) .. method:: join(timeout=None)
Wait until the thread terminates. This blocks the calling thread until the Wait until the thread terminates. This blocks the calling thread until the
thread whose :meth:`join` method is called terminates -- either normally thread whose :meth:`join` method is called terminates -- either normally
...@@ -349,7 +349,7 @@ and may vary across implementations. ...@@ -349,7 +349,7 @@ and may vary across implementations.
All methods are executed atomically. All methods are executed atomically.
.. method:: Lock.acquire([blocking=1]) .. method:: Lock.acquire(blocking=True)
Acquire a lock, blocking or non-blocking. Acquire a lock, blocking or non-blocking.
...@@ -396,7 +396,7 @@ pair) resets the lock to unlocked and allows another thread blocked in ...@@ -396,7 +396,7 @@ pair) resets the lock to unlocked and allows another thread blocked in
:meth:`acquire` to proceed. :meth:`acquire` to proceed.
.. method:: RLock.acquire([blocking=1]) .. method:: RLock.acquire(blocking=True)
Acquire a lock, blocking or non-blocking. Acquire a lock, blocking or non-blocking.
...@@ -487,7 +487,7 @@ in a typical producer-consumer situation, adding one item to the buffer only ...@@ -487,7 +487,7 @@ in a typical producer-consumer situation, adding one item to the buffer only
needs to wake up one consumer thread. needs to wake up one consumer thread.
.. class:: Condition([lock]) .. class:: Condition(lock=None)
If the *lock* argument is given and not ``None``, it must be a :class:`Lock` If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
or :class:`RLock` object, and it is used as the underlying lock. Otherwise, or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
...@@ -503,7 +503,7 @@ needs to wake up one consumer thread. ...@@ -503,7 +503,7 @@ needs to wake up one consumer thread.
Release the underlying lock. This method calls the corresponding method on Release the underlying lock. This method calls the corresponding method on
the underlying lock; there is no return value. the underlying lock; there is no return value.
.. method:: wait([timeout]) .. method:: wait(timeout=None)
Wait until notified or until a timeout occurs. If the calling thread has Wait until notified or until a timeout occurs. If the calling thread has
not acquired the lock when this method is called, a :exc:`RuntimeError` is not acquired the lock when this method is called, a :exc:`RuntimeError` is
...@@ -566,13 +566,13 @@ can never go below zero; when :meth:`acquire` finds that it is zero, it blocks, ...@@ -566,13 +566,13 @@ can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
waiting until some other thread calls :meth:`release`. waiting until some other thread calls :meth:`release`.
.. class:: Semaphore([value]) .. class:: Semaphore(value=1)
The optional argument gives the initial *value* for the internal counter; it The optional argument gives the initial *value* for the internal counter; it
defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
raised. raised.
.. method:: acquire([blocking]) .. method:: acquire(blocking=True)
Acquire a semaphore. Acquire a semaphore.
...@@ -659,7 +659,7 @@ An event object manages an internal flag that can be set to true with the ...@@ -659,7 +659,7 @@ An event object manages an internal flag that can be set to true with the
:meth:`wait` will block until :meth:`.set` is called to set the internal :meth:`wait` will block until :meth:`.set` is called to set the internal
flag to true again. flag to true again.
.. method:: wait([timeout]) .. method:: wait(timeout=None)
Block until the internal flag is true. If the internal flag is true on Block until the internal flag is true. If the internal flag is true on
entry, return immediately. Otherwise, block until another thread calls entry, return immediately. Otherwise, block until another thread calls
......
:mod:`time` --- Time access and conversions :mod:`time` --- Time access and conversions
=========================================== ===========================================
......
:mod:`timeit` --- Measure execution time of small code snippets :mod:`timeit` --- Measure execution time of small code snippets
=============================================================== ===============================================================
...@@ -18,7 +17,7 @@ for measuring execution times. See also Tim Peters' introduction to the ...@@ -18,7 +17,7 @@ for measuring execution times. See also Tim Peters' introduction to the
The module defines the following public class: The module defines the following public class:
.. class:: Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]]) .. class:: Timer(stmt='pass', setup='pass', timer=<timer function>)
Class for timing execution speed of small code snippets. Class for timing execution speed of small code snippets.
...@@ -38,7 +37,7 @@ The module defines the following public class: ...@@ -38,7 +37,7 @@ The module defines the following public class:
little larger in this case because of the extra function calls. little larger in this case because of the extra function calls.
.. method:: Timer.print_exc([file=None]) .. method:: Timer.print_exc(file=None)
Helper to print a traceback from the timed code. Helper to print a traceback from the timed code.
...@@ -55,7 +54,7 @@ The module defines the following public class: ...@@ -55,7 +54,7 @@ The module defines the following public class:
traceback is sent; it defaults to ``sys.stderr``. traceback is sent; it defaults to ``sys.stderr``.
.. method:: Timer.repeat([repeat=3 [, number=1000000]]) .. method:: Timer.repeat(repeat=3, number=1000000)
Call :meth:`timeit` a few times. Call :meth:`timeit` a few times.
...@@ -76,7 +75,7 @@ The module defines the following public class: ...@@ -76,7 +75,7 @@ The module defines the following public class:
and apply common sense rather than statistics. and apply common sense rather than statistics.
.. method:: Timer.timeit([number=1000000]) .. method:: Timer.timeit(number=1000000)
Time *number* executions of the main statement. This executes the setup Time *number* executions of the main statement. This executes the setup
statement once, and then returns the time it takes to execute the main statement statement once, and then returns the time it takes to execute the main statement
...@@ -98,14 +97,14 @@ The module defines the following public class: ...@@ -98,14 +97,14 @@ The module defines the following public class:
The module also defines two convenience functions: The module also defines two convenience functions:
.. function:: repeat(stmt[, setup[, timer[, repeat=3 [, number=1000000]]]]) .. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)
Create a :class:`Timer` instance with the given statement, setup code and timer Create a :class:`Timer` instance with the given statement, setup code and timer
function and run its :meth:`repeat` method with the given repeat count and function and run its :meth:`repeat` method with the given repeat count and
*number* executions. *number* executions.
.. function:: timeit(stmt[, setup[, timer[, number=1000000]]]) .. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
Create a :class:`Timer` instance with the given statement, setup code and timer Create a :class:`Timer` instance with the given statement, setup code and timer
function and run its :meth:`timeit` method with *number* executions. function and run its :meth:`timeit` method with *number* executions.
......
...@@ -45,7 +45,7 @@ Using Tix ...@@ -45,7 +45,7 @@ Using Tix
--------- ---------
.. class:: Tix(screenName[, baseName[, className]]) .. class:: Tk(screenName=None, baseName=None, className='Tix')
Toplevel widget of Tix which represents mostly the main window of an Toplevel widget of Tix which represents mostly the main window of an
application. It has an associated Tcl interpreter. application. It has an associated Tcl interpreter.
......
...@@ -262,7 +262,7 @@ methods :meth:`tkinter.Widget.cget` and :meth:`tkinter.Widget.configure`. ...@@ -262,7 +262,7 @@ methods :meth:`tkinter.Widget.cget` and :meth:`tkinter.Widget.configure`.
*x* and *y* are pixel coordinates relative to the widget. *x* and *y* are pixel coordinates relative to the widget.
.. method:: instate(statespec[, callback=None[, *args[, **kw]]]) .. method:: instate(statespec, callback=None, *args, **kw)
Test the widget's state. If a callback is not specified, returns True Test the widget's state. If a callback is not specified, returns True
if the widget state matches *statespec* and False otherwise. If callback if the widget state matches *statespec* and False otherwise. If callback
...@@ -270,7 +270,7 @@ methods :meth:`tkinter.Widget.cget` and :meth:`tkinter.Widget.configure`. ...@@ -270,7 +270,7 @@ methods :meth:`tkinter.Widget.cget` and :meth:`tkinter.Widget.configure`.
*statespec*. *statespec*.
.. method:: state([statespec=None]) .. method:: state(statespec=None)
Modify or inquire widget state. If *statespec* is specified, sets the Modify or inquire widget state. If *statespec* is specified, sets the
widget state according to it and return a new *statespec* indicating widget state according to it and return a new *statespec* indicating
...@@ -349,7 +349,7 @@ ttk.Combobox ...@@ -349,7 +349,7 @@ ttk.Combobox
.. class:: Combobox .. class:: Combobox
.. method:: current([newindex=None]) .. method:: current(newindex=None)
If *newindex* is specified, sets the combobox value to the element If *newindex* is specified, sets the combobox value to the element
position *newindex*. Otherwise, returns the index of the current value or position *newindex*. Otherwise, returns the index of the current value or
...@@ -510,7 +510,7 @@ ttk.Notebook ...@@ -510,7 +510,7 @@ ttk.Notebook
See `Tab Options`_ for the list of available options. See `Tab Options`_ for the list of available options.
.. method:: select([tab_id]) .. method:: select(tab_id=None)
Selects the specified *tab_id*. Selects the specified *tab_id*.
...@@ -519,7 +519,7 @@ ttk.Notebook ...@@ -519,7 +519,7 @@ ttk.Notebook
omitted, returns the widget name of the currently selected pane. omitted, returns the widget name of the currently selected pane.
.. method:: tab(tab_id[, option=None[, **kw]]) .. method:: tab(tab_id, option=None, **kw)
Query or modify the options of the specific *tab_id*. Query or modify the options of the specific *tab_id*.
...@@ -600,14 +600,14 @@ ttk.Progressbar ...@@ -600,14 +600,14 @@ ttk.Progressbar
.. class:: Progressbar .. class:: Progressbar
.. method:: start([interval]) .. method:: start(interval=None)
Begin autoincrement mode: schedules a recurring timer event that calls Begin autoincrement mode: schedules a recurring timer event that calls
:meth:`Progressbar.step` every *interval* milliseconds. If omitted, :meth:`Progressbar.step` every *interval* milliseconds. If omitted,
*interval* defaults to 50 milliseconds. *interval* defaults to 50 milliseconds.
.. method:: step([amount]) .. method:: step(amount=None)
Increments the progress bar's value by *amount*. Increments the progress bar's value by *amount*.
...@@ -842,7 +842,7 @@ ttk.Treeview ...@@ -842,7 +842,7 @@ ttk.Treeview
.. class:: Treeview .. class:: Treeview
.. method:: bbox(item[, column=None]) .. method:: bbox(item, column=None)
Returns the bounding box (relative to the treeview widget's window) of Returns the bounding box (relative to the treeview widget's window) of
the specified *item* in the form (x, y, width, height). the specified *item* in the form (x, y, width, height).
...@@ -852,7 +852,7 @@ ttk.Treeview ...@@ -852,7 +852,7 @@ ttk.Treeview
scrolled offscreen), returns an empty string. scrolled offscreen), returns an empty string.
.. method:: get_children([item]) .. method:: get_children(item=None)
Returns the list of children belonging to *item*. Returns the list of children belonging to *item*.
...@@ -869,7 +869,7 @@ ttk.Treeview ...@@ -869,7 +869,7 @@ ttk.Treeview
*item*'s children. *item*'s children.
.. method:: column(column[, option=None[, **kw]]) .. method:: column(column, option=None, **kw)
Query or modify the options for the specified *column*. Query or modify the options for the specified *column*.
...@@ -918,13 +918,13 @@ ttk.Treeview ...@@ -918,13 +918,13 @@ ttk.Treeview
Returns True if the specified *item* is present in the tree. Returns True if the specified *item* is present in the tree.
.. method:: focus([item=None]) .. method:: focus(item=None)
If *item* is specified, sets the focus item to *item*. Otherwise, returns If *item* is specified, sets the focus item to *item*. Otherwise, returns
the current focus item, or '' if there is none. the current focus item, or '' if there is none.
.. method:: heading(column[, option=None[, **kw]]) .. method:: heading(column, option=None, **kw)
Query or modify the heading options for the specified *column*. Query or modify the heading options for the specified *column*.
...@@ -997,7 +997,7 @@ ttk.Treeview ...@@ -997,7 +997,7 @@ ttk.Treeview
Returns the integer index of *item* within its parent's list of children. Returns the integer index of *item* within its parent's list of children.
.. method:: insert(parent, index[, iid=None[, **kw]]) .. method:: insert(parent, index, iid=None, **kw)
Creates a new item and returns the item identifier of the newly created Creates a new item and returns the item identifier of the newly created
item. item.
...@@ -1014,7 +1014,7 @@ ttk.Treeview ...@@ -1014,7 +1014,7 @@ ttk.Treeview
See `Item Options`_ for the list of available points. See `Item Options`_ for the list of available points.
.. method:: item(item[, option[, **kw]]) .. method:: item(item, option=None, **kw)
Query or modify the options for the specified *item*. Query or modify the options for the specified *item*.
...@@ -1066,7 +1066,7 @@ ttk.Treeview ...@@ -1066,7 +1066,7 @@ ttk.Treeview
the tree. the tree.
.. method:: selection([selop=None[, items=None]]) .. method:: selection(selop=None, items=None)
If *selop* is not specified, returns selected items. Otherwise, it will If *selop* is not specified, returns selected items. Otherwise, it will
act according to the following selection methods. act according to the following selection methods.
...@@ -1092,7 +1092,7 @@ ttk.Treeview ...@@ -1092,7 +1092,7 @@ ttk.Treeview
Toggle the selection state of each item in *items*. Toggle the selection state of each item in *items*.
.. method:: set(item[, column=None[, value=None]]) .. method:: set(item, column=None, value=None)
With one argument, returns a dictionary of column/value pairs for the With one argument, returns a dictionary of column/value pairs for the
specified *item*. With two arguments, returns the current value of the specified *item*. With two arguments, returns the current value of the
...@@ -1100,14 +1100,14 @@ ttk.Treeview ...@@ -1100,14 +1100,14 @@ ttk.Treeview
*column* in given *item* to the specified *value*. *column* in given *item* to the specified *value*.
.. method:: tag_bind(tagname[, sequence=None[, callback=None]]) .. method:: tag_bind(tagname, sequence=None, callback=None)
Bind a callback for the given event *sequence* to the tag *tagname*. Bind a callback for the given event *sequence* to the tag *tagname*.
When an event is delivered to an item, the callbacks for each of the When an event is delivered to an item, the callbacks for each of the
item's tags option are called. item's tags option are called.
.. method:: tag_configure(tagname[, option=None[, **kw]]) .. method:: tag_configure(tagname, option=None, **kw)
Query or modify the options for the specified *tagname*. Query or modify the options for the specified *tagname*.
...@@ -1117,7 +1117,7 @@ ttk.Treeview ...@@ -1117,7 +1117,7 @@ ttk.Treeview
corresponding values for the given *tagname*. corresponding values for the given *tagname*.
.. method:: tag_has(tagname[, item]) .. method:: tag_has(tagname, item=None)
If *item* is specified, returns 1 or 0 depending on whether the specified If *item* is specified, returns 1 or 0 depending on whether the specified
*item* has the given *tagname*. Otherwise, returns a list of all items *item* has the given *tagname*. Otherwise, returns a list of all items
...@@ -1216,7 +1216,7 @@ option. If you don't know the class name of a widget, use the method ...@@ -1216,7 +1216,7 @@ option. If you don't know the class name of a widget, use the method
blue foreground when the widget were in active or pressed states. blue foreground when the widget were in active or pressed states.
.. method:: lookup(style, option[, state=None[, default=None]]) .. method:: lookup(style, option, state=None, default=None)
Returns the value specified for *option* in *style*. Returns the value specified for *option* in *style*.
...@@ -1231,7 +1231,7 @@ option. If you don't know the class name of a widget, use the method ...@@ -1231,7 +1231,7 @@ option. If you don't know the class name of a widget, use the method
print(ttk.Style().lookup("TButton", "font")) print(ttk.Style().lookup("TButton", "font"))
.. method:: layout(style[, layoutspec=None]) .. method:: layout(style, layoutspec=None)
Define the widget layout for given *style*. If *layoutspec* is omitted, Define the widget layout for given *style*. If *layoutspec* is omitted,
return the layout specification for given style. return the layout specification for given style.
...@@ -1314,7 +1314,7 @@ option. If you don't know the class name of a widget, use the method ...@@ -1314,7 +1314,7 @@ option. If you don't know the class name of a widget, use the method
Returns the list of *elementname*'s options. Returns the list of *elementname*'s options.
.. method:: theme_create(themename[, parent=None[, settings=None]]) .. method:: theme_create(themename, parent=None, settings=None)
Create a new theme. Create a new theme.
...@@ -1366,7 +1366,7 @@ option. If you don't know the class name of a widget, use the method ...@@ -1366,7 +1366,7 @@ option. If you don't know the class name of a widget, use the method
Returns a list of all known themes. Returns a list of all known themes.
.. method:: theme_use([themename]) .. method:: theme_use(themename=None)
If *themename* is not given, returns the theme in use. Otherwise, sets If *themename* is not given, returns the theme in use. Otherwise, sets
the current theme to *themename*, refreshes all widgets and emits a the current theme to *themename*, refreshes all widgets and emits a
......
:mod:`token` --- Constants used with Python parse trees :mod:`token` --- Constants used with Python parse trees
======================================================= =======================================================
......
:mod:`trace` --- Trace or track Python statement execution :mod:`trace` --- Trace or track Python statement execution
========================================================== ==========================================================
...@@ -80,7 +79,7 @@ Programming Interface ...@@ -80,7 +79,7 @@ Programming Interface
--------------------- ---------------------
.. class:: Trace([count=1[, trace=1[, countfuncs=0[, countcallers=0[, ignoremods=()[, ignoredirs=()[, infile=None[, outfile=None[, timing=False]]]]]]]]]) .. class:: Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False)
Create an object to trace execution of a single statement or expression. All Create an object to trace execution of a single statement or expression. All
parameters are optional. *count* enables counting of line numbers. *trace* parameters are optional. *count* enables counting of line numbers. *trace*
...@@ -98,7 +97,7 @@ Programming Interface ...@@ -98,7 +97,7 @@ Programming Interface
Run *cmd* under control of the Trace object with the current tracing parameters. Run *cmd* under control of the Trace object with the current tracing parameters.
.. method:: Trace.runctx(cmd[, globals=None[, locals=None]]) .. method:: Trace.runctx(cmd, globals=None, locals=None)
Run *cmd* under control of the Trace object with the current tracing parameters Run *cmd* under control of the Trace object with the current tracing parameters
in the defined global and local environments. If not defined, *globals* and in the defined global and local environments. If not defined, *globals* and
......
...@@ -20,7 +20,7 @@ the :data:`sys.last_traceback` variable and returned as the third item from ...@@ -20,7 +20,7 @@ the :data:`sys.last_traceback` variable and returned as the third item from
The module defines the following functions: The module defines the following functions:
.. function:: print_tb(traceback[, limit[, file]]) .. function:: print_tb(traceback, limit=None, file=None)
Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted
or ``None``, all entries are printed. If *file* is omitted or ``None``, the or ``None``, all entries are printed. If *file* is omitted or ``None``, the
...@@ -28,7 +28,7 @@ The module defines the following functions: ...@@ -28,7 +28,7 @@ The module defines the following functions:
object to receive the output. object to receive the output.
.. function:: print_exception(type, value, traceback[, limit[, file[, chain]]]) .. function:: print_exception(type, value, traceback, limit=None, file=None, chain=True)
Print exception information and up to *limit* stack trace entries from Print exception information and up to *limit* stack trace entries from
*traceback* to *file*. This differs from :func:`print_tb` in the following *traceback* to *file*. This differs from :func:`print_tb` in the following
...@@ -47,19 +47,19 @@ The module defines the following functions: ...@@ -47,19 +47,19 @@ The module defines the following functions:
exception. exception.
.. function:: print_exc([limit[, file[, chain]]]) .. function:: print_exc(limit=None, file=None, chain=True)
This is a shorthand for ``print_exception(*sys.exc_info())``. This is a shorthand for ``print_exception(*sys.exc_info())``.
.. function:: print_last([limit[, file[, chain]]]) .. function:: print_last(limit=None, file=None, chain=True)
This is a shorthand for ``print_exception(sys.last_type, sys.last_value, This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file)``. In general it will work only after sys.last_traceback, limit, file)``. In general it will work only after
an exception has reached an interactive prompt (see :data:`sys.last_type`). an exception has reached an interactive prompt (see :data:`sys.last_type`).
.. function:: print_stack([f[, limit[, file]]]) .. function:: print_stack(f=None, limit=None, file=None)
This function prints a stack trace from its invocation point. The optional *f* This function prints a stack trace from its invocation point. The optional *f*
argument can be used to specify an alternate stack frame to start. The optional argument can be used to specify an alternate stack frame to start. The optional
...@@ -67,7 +67,7 @@ The module defines the following functions: ...@@ -67,7 +67,7 @@ The module defines the following functions:
:func:`print_exception`. :func:`print_exception`.
.. function:: extract_tb(traceback[, limit]) .. function:: extract_tb(traceback, limit=None)
Return a list of up to *limit* "pre-processed" stack trace entries extracted Return a list of up to *limit* "pre-processed" stack trace entries extracted
from the traceback object *traceback*. It is useful for alternate formatting of from the traceback object *traceback*. It is useful for alternate formatting of
...@@ -78,7 +78,7 @@ The module defines the following functions: ...@@ -78,7 +78,7 @@ The module defines the following functions:
stripped; if the source is not available it is ``None``. stripped; if the source is not available it is ``None``.
.. function:: extract_stack([f[, limit]]) .. function:: extract_stack(f=None, limit=None)
Extract the raw traceback from the current stack frame. The return value has Extract the raw traceback from the current stack frame. The return value has
the same format as for :func:`extract_tb`. The optional *f* and *limit* the same format as for :func:`extract_tb`. The optional *f* and *limit*
...@@ -105,7 +105,7 @@ The module defines the following functions: ...@@ -105,7 +105,7 @@ The module defines the following functions:
occurred is the always last string in the list. occurred is the always last string in the list.
.. function:: format_exception(type, value, tb[, limit[, chain]]) .. function:: format_exception(type, value, tb, limit=None, chain=True)
Format a stack trace and the exception information. The arguments have the Format a stack trace and the exception information. The arguments have the
same meaning as the corresponding arguments to :func:`print_exception`. The same meaning as the corresponding arguments to :func:`print_exception`. The
...@@ -114,18 +114,18 @@ The module defines the following functions: ...@@ -114,18 +114,18 @@ The module defines the following functions:
same text is printed as does :func:`print_exception`. same text is printed as does :func:`print_exception`.
.. function:: format_exc([limit[, chain]]) .. function:: format_exc(limit=None, chain=True)
This is like ``print_exc(limit)`` but returns a string instead of printing to a This is like ``print_exc(limit)`` but returns a string instead of printing to a
file. file.
.. function:: format_tb(tb[, limit]) .. function:: format_tb(tb, limit=None)
A shorthand for ``format_list(extract_tb(tb, limit))``. A shorthand for ``format_list(extract_tb(tb, limit))``.
.. function:: format_stack([f[, limit]]) .. function:: format_stack(f=None, limit=None)
A shorthand for ``format_list(extract_stack(f, limit))``. A shorthand for ``format_list(extract_stack(f, limit))``.
......
:mod:`tty` --- Terminal control functions :mod:`tty` --- Terminal control functions
========================================= =========================================
...@@ -17,14 +16,14 @@ Because it requires the :mod:`termios` module, it will work only on Unix. ...@@ -17,14 +16,14 @@ 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:: setraw(fd[, when]) .. function:: setraw(fd, when=termios.TCSAFLUSH)
Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it
defaults to :const:`termios.TCSAFLUSH`, and is passed to defaults to :const:`termios.TCSAFLUSH`, and is passed to
:func:`termios.tcsetattr`. :func:`termios.tcsetattr`.
.. function:: setcbreak(fd[, when]) .. function:: setcbreak(fd, when=termios.TCSAFLUSH)
Change the mode of file descriptor *fd* to cbreak. If *when* is omitted, it Change the mode of file descriptor *fd* to cbreak. If *when* is omitted, it
defaults to :const:`termios.TCSAFLUSH`, and is passed to defaults to :const:`termios.TCSAFLUSH`, and is passed to
......
.. _undoc: .. _undoc:
******************** ********************
......
:mod:`unicodedata` --- Unicode Database :mod:`unicodedata` --- Unicode Database
======================================= =======================================
......
...@@ -525,7 +525,7 @@ This section describes in depth the API of :mod:`unittest`. ...@@ -525,7 +525,7 @@ This section describes in depth the API of :mod:`unittest`.
Test cases Test cases
~~~~~~~~~~ ~~~~~~~~~~
.. class:: TestCase([methodName]) .. class:: TestCase(methodName='runTest')
Instances of the :class:`TestCase` class represent the smallest testable units Instances of the :class:`TestCase` class represent the smallest testable 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
...@@ -576,7 +576,7 @@ Test cases ...@@ -576,7 +576,7 @@ Test cases
the outcome of the test method. The default implementation does nothing. the outcome of the test method. The default implementation does nothing.
.. method:: run([result]) .. method:: run(result=None)
Run the test, collecting the result into the test result object passed as Run the test, collecting the result into the test result object passed as
*result*. If *result* is omitted or :const:`None`, a temporary result *result*. If *result* is omitted or :const:`None`, a temporary result
...@@ -603,9 +603,9 @@ Test cases ...@@ -603,9 +603,9 @@ Test cases
failures. failures.
.. method:: assertTrue(expr[, msg]) .. method:: assertTrue(expr, msg=None)
assert_(expr[, msg]) assert_(expr, msg=None)
failUnless(expr[, msg]) failUnless(expr, msg=None)
Signal a test failure if *expr* is false; the explanation for the failure Signal a test failure if *expr* is false; the explanation for the failure
will be *msg* if given, otherwise it will be :const:`None`. will be *msg* if given, otherwise it will be :const:`None`.
...@@ -614,8 +614,8 @@ Test cases ...@@ -614,8 +614,8 @@ Test cases
:meth:`failUnless`. :meth:`failUnless`.
.. method:: assertEqual(first, second[, msg]) .. method:: assertEqual(first, second, msg=None)
failUnlessEqual(first, second[, msg]) failUnlessEqual(first, second, msg=None)
Test that *first* and *second* are equal. If the values do not compare Test that *first* and *second* are equal. If the values do not compare
equal, the test will fail with the explanation given by *msg*, or equal, the test will fail with the explanation given by *msg*, or
...@@ -636,8 +636,8 @@ Test cases ...@@ -636,8 +636,8 @@ Test cases
:meth:`failUnlessEqual`. :meth:`failUnlessEqual`.
.. method:: assertNotEqual(first, second[, msg]) .. method:: assertNotEqual(first, second, msg=None)
failIfEqual(first, second[, msg]) failIfEqual(first, second, msg=None)
Test that *first* and *second* are not equal. If the values do compare Test that *first* and *second* are not equal. If the values do compare
equal, the test will fail with the explanation given by *msg*, or equal, the test will fail with the explanation given by *msg*, or
...@@ -650,8 +650,8 @@ Test cases ...@@ -650,8 +650,8 @@ Test cases
:meth:`failIfEqual`. :meth:`failIfEqual`.
.. method:: assertAlmostEqual(first, second[, places[, msg]]) .. method:: assertAlmostEqual(first, second, *, places=7, msg=None)
failUnlessAlmostEqual(first, second[, places[, msg]]) failUnlessAlmostEqual(first, second, *, places=7, msg=None)
Test that *first* and *second* are approximately equal by computing the Test that *first* and *second* are approximately equal by computing the
difference, rounding to the given number of decimal *places* (default 7), difference, rounding to the given number of decimal *places* (default 7),
...@@ -666,8 +666,8 @@ Test cases ...@@ -666,8 +666,8 @@ Test cases
:meth:`failUnlessAlmostEqual`. :meth:`failUnlessAlmostEqual`.
.. method:: assertNotAlmostEqual(first, second[, places[, msg]]) .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None)
failIfAlmostEqual(first, second[, places[, msg]]) failIfAlmostEqual(first, second, *, places=7, msg=None)
Test that *first* and *second* are not approximately equal by computing Test that *first* and *second* are not approximately equal by computing
the difference, rounding to the given number of decimal *places* (default the difference, rounding to the given number of decimal *places* (default
...@@ -708,7 +708,7 @@ Test cases ...@@ -708,7 +708,7 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertRegexpMatches(text, regexp[, msg=None]): .. method:: assertRegexpMatches(text, regexp, msg=None):
Verifies that a *regexp* search matches *text*. Fails with an error Verifies that a *regexp* search matches *text*. Fails with an error
message including the pattern and the *text*. *regexp* may be message including the pattern and the *text*. *regexp* may be
...@@ -801,8 +801,10 @@ Test cases ...@@ -801,8 +801,10 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertRaises(exception[, callable, ...]) .. method:: assertRaises(exception, callable, *args, **kwds)
failUnlessRaises(exception[, callable, ...]) failUnlessRaises(exception, callable, *args, **kwds)
assertRaises(exception)
failUnlessRaises(exception)
Test that an exception is raised when *callable* is called with any Test that an exception is raised when *callable* is called with any
positional or keyword arguments that are also passed to positional or keyword arguments that are also passed to
...@@ -811,8 +813,8 @@ Test cases ...@@ -811,8 +813,8 @@ Test cases
To catch any of a group of exceptions, a tuple containing the exception To catch any of a group of exceptions, a tuple containing the exception
classes may be passed as *exception*. classes may be passed as *exception*.
If *callable* is omitted or None, returns a context manager so that the If only the *exception* argument is given, returns a context manager so
code under test can be written inline rather than as a function:: that the code under test can be written inline rather than as a function::
with self.failUnlessRaises(some_error_class): with self.failUnlessRaises(some_error_class):
do_something() do_something()
...@@ -842,14 +844,14 @@ Test cases ...@@ -842,14 +844,14 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertIsNone(expr[, msg]) .. method:: assertIsNone(expr, msg=None)
This signals a test failure if *expr* is not None. This signals a test failure if *expr* is not None.
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertIsNotNone(expr[, msg]) .. method:: assertIsNotNone(expr, msg=None)
The inverse of the :meth:`assertIsNone` method. The inverse of the :meth:`assertIsNone` method.
This signals a test failure if *expr* is None. This signals a test failure if *expr* is None.
...@@ -857,7 +859,7 @@ Test cases ...@@ -857,7 +859,7 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertIs(expr1, expr2[, msg]) .. method:: assertIs(expr1, expr2, msg=None)
This signals a test failure if *expr1* and *expr2* don't evaluate to the same This signals a test failure if *expr1* and *expr2* don't evaluate to the same
object. object.
...@@ -865,7 +867,7 @@ Test cases ...@@ -865,7 +867,7 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertIsNot(expr1, expr2[, msg]) .. method:: assertIsNot(expr1, expr2, msg=None)
The inverse of the :meth:`assertIs` method. The inverse of the :meth:`assertIs` method.
This signals a test failure if *expr1* and *expr2* evaluate to the same This signals a test failure if *expr1* and *expr2* evaluate to the same
...@@ -874,8 +876,8 @@ Test cases ...@@ -874,8 +876,8 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: assertFalse(expr[, msg]) .. method:: assertFalse(expr, msg=None)
failIf(expr[, msg]) failIf(expr, msg=None)
The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method. The inverse of the :meth:`assertTrue` method is the :meth:`assertFalse` method.
This signals a test failure if *expr* is true, with *msg* or :const:`None` This signals a test failure if *expr* is true, with *msg* or :const:`None`
...@@ -885,7 +887,7 @@ Test cases ...@@ -885,7 +887,7 @@ Test cases
:meth:`failIf`. :meth:`failIf`.
.. method:: fail([msg]) .. method:: fail(msg=None)
Signals a test failure unconditionally, with *msg* or :const:`None` for Signals a test failure unconditionally, with *msg* or :const:`None` for
the error message. the error message.
...@@ -976,7 +978,7 @@ Test cases ...@@ -976,7 +978,7 @@ Test cases
.. versionadded:: 3.1 .. versionadded:: 3.1
.. method:: addCleanup(function[, *args[, **kwargs]]) .. method:: addCleanup(function, *args, **kwargs)
Add a function to be called after :meth:`tearDown` to cleanup resources Add a function to be called after :meth:`tearDown` to cleanup resources
used during the test. Functions will be called in reverse order to the used during the test. Functions will be called in reverse order to the
...@@ -1006,7 +1008,7 @@ Test cases ...@@ -1006,7 +1008,7 @@ Test cases
.. versionadded:: 2.7 .. versionadded:: 2.7
.. class:: FunctionTestCase(testFunc[, setUp[, tearDown[, description]]]) .. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)
This class implements the portion of the :class:`TestCase` interface which This class implements the portion of the :class:`TestCase` interface which
allows the test runner to drive the test, but does not provide the methods which allows the test runner to drive the test, but does not provide the methods which
...@@ -1020,7 +1022,7 @@ Test cases ...@@ -1020,7 +1022,7 @@ Test cases
Grouping tests Grouping tests
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
.. class:: TestSuite([tests]) .. class:: TestSuite(tests=())
This class represents an aggregation of individual tests cases and test suites. This class represents an aggregation of individual tests cases and test suites.
The class presents the interface needed by the test runner to allow it to be run The class presents the interface needed by the test runner to allow it to be run
...@@ -1127,7 +1129,7 @@ Loading and running tests ...@@ -1127,7 +1129,7 @@ Loading and running tests
be useful when the fixtures are different and defined in subclasses. be useful when the fixtures are different and defined in subclasses.
.. method:: loadTestsFromName(name[, module]) .. method:: loadTestsFromName(name, module=None)
Return a suite of all tests cases given a string specifier. Return a suite of all tests cases given a string specifier.
...@@ -1152,7 +1154,7 @@ Loading and running tests ...@@ -1152,7 +1154,7 @@ Loading and running tests
The method optionally resolves *name* relative to the given *module*. The method optionally resolves *name* relative to the given *module*.
.. method:: loadTestsFromNames(names[, module]) .. method:: loadTestsFromNames(names, module=None)
Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
than a single name. The return value is a test suite which supports all than a single name. The return value is a test suite which supports all
...@@ -1369,7 +1371,7 @@ Loading and running tests ...@@ -1369,7 +1371,7 @@ Loading and running tests
instead of repeatedly creating new instances. instead of repeatedly creating new instances.
.. class:: TextTestRunner([stream[, descriptions[, verbosity]]]) .. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1)
A basic test runner implementation which prints results on standard error. It A basic test runner implementation which prints results on standard error. It
has a few configurable parameters, but is essentially very simple. Graphical has a few configurable parameters, but is essentially very simple. Graphical
...@@ -1382,7 +1384,7 @@ Loading and running tests ...@@ -1382,7 +1384,7 @@ Loading and running tests
subclasses to provide a custom ``TestResult``. subclasses to provide a custom ``TestResult``.
.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit]]]]]]) .. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=TextTestRunner, testLoader=unittest.defaultTestLoader, exit=True)
A command-line program that runs a set of tests; this is primarily for making A command-line program that runs a set of tests; this is primarily for making
test modules conveniently executable. The simplest use for this function is to test modules conveniently executable. The simplest use for this function is to
......
.. _unix: .. _unix:
********************** **********************
......
...@@ -39,7 +39,7 @@ The following exceptions are raised by :mod:`urllib.error` as appropriate: ...@@ -39,7 +39,7 @@ The following exceptions are raised by :mod:`urllib.error` as appropriate:
to a value found in the dictionary of codes as found in to a value found in the dictionary of codes as found in
:attr:`http.server.BaseHTTPRequestHandler.responses`. :attr:`http.server.BaseHTTPRequestHandler.responses`.
.. exception:: ContentTooShortError(msg[, content]) .. exception:: ContentTooShortError(msg, content)
This exception is raised when the :func:`urlretrieve` function detects that This exception is raised when the :func:`urlretrieve` function detects that
the amount of the downloaded data is less than the expected amount (given by the amount of the downloaded data is less than the expected amount (given by
......
...@@ -26,7 +26,7 @@ following URL schemes: ``file``, ``ftp``, ``gopher``, ``hdl``, ``http``, ...@@ -26,7 +26,7 @@ following URL schemes: ``file``, ``ftp``, ``gopher``, ``hdl``, ``http``,
The :mod:`urllib.parse` module defines the following functions: The :mod:`urllib.parse` module defines the following functions:
.. function:: urlparse(urlstring[, default_scheme[, allow_fragments]]) .. function:: urlparse(urlstring, default_scheme='', allow_fragments=True)
Parse a URL into six components, returning a 6-tuple. This corresponds to the Parse a URL into six components, returning a 6-tuple. This corresponds to the
general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``. general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``.
...@@ -89,7 +89,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -89,7 +89,7 @@ The :mod:`urllib.parse` module defines the following functions:
object. object.
.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing]]) .. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False)
Parse a query string given as a string argument (data of type Parse a query string given as a string argument (data of type
:mimetype:`application/x-www-form-urlencoded`). Data are returned as a :mimetype:`application/x-www-form-urlencoded`). Data are returned as a
...@@ -110,7 +110,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -110,7 +110,7 @@ The :mod:`urllib.parse` module defines the following functions:
dictionaries into query strings. dictionaries into query strings.
.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing]]) .. function:: parse_qsl(qs, keep_blank_values=False, strict_parsing=False)
Parse a query string given as a string argument (data of type Parse a query string given as a string argument (data of type
:mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of :mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of
...@@ -139,7 +139,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -139,7 +139,7 @@ The :mod:`urllib.parse` module defines the following functions:
states that these are equivalent). states that these are equivalent).
.. function:: urlsplit(urlstring[, default_scheme[, allow_fragments]]) .. function:: urlsplit(urlstring, default_scheme='', allow_fragments=True)
This is similar to :func:`urlparse`, but does not split the params from the URL. This is similar to :func:`urlparse`, but does not split the params from the URL.
This should generally be used instead of :func:`urlparse` if the more recent URL This should generally be used instead of :func:`urlparse` if the more recent URL
...@@ -187,7 +187,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -187,7 +187,7 @@ The :mod:`urllib.parse` module defines the following functions:
with an empty query; the RFC states that these are equivalent). with an empty query; the RFC states that these are equivalent).
.. function:: urljoin(base, url[, allow_fragments]) .. function:: urljoin(base, url, allow_fragments=True)
Construct a full ("absolute") URL by combining a "base URL" (*base*) with Construct a full ("absolute") URL by combining a "base URL" (*base*) with
another URL (*url*). Informally, this uses components of the base URL, in another URL (*url*). Informally, this uses components of the base URL, in
...@@ -223,7 +223,8 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -223,7 +223,8 @@ The :mod:`urllib.parse` module defines the following functions:
string. If there is no fragment identifier in *url*, return *url* unmodified string. If there is no fragment identifier in *url*, return *url* unmodified
and an empty string. and an empty string.
.. function:: quote(string[, safe[, encoding[, errors]]])
.. function:: quote(string, safe='/', encoding=None, errors=None)
Replace special characters in *string* using the ``%xx`` escape. Letters, Replace special characters in *string* using the ``%xx`` escape. Letters,
digits, and the characters ``'_.-'`` are never quoted. The optional *safe* digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
...@@ -246,7 +247,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -246,7 +247,7 @@ The :mod:`urllib.parse` module defines the following functions:
Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``. Example: ``quote('/El Niño/')`` yields ``'/El%20Ni%C3%B1o/'``.
.. function:: quote_plus(string[, safe[, encoding[, errors]]]) .. function:: quote_plus(string, safe='', encoding=None, errors=None)
Like :func:`quote`, but also replace spaces by plus signs, as required for Like :func:`quote`, but also replace spaces by plus signs, as required for
quoting HTML form values when building up a query string to go into a URL. quoting HTML form values when building up a query string to go into a URL.
...@@ -255,7 +256,8 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -255,7 +256,8 @@ The :mod:`urllib.parse` module defines the following functions:
Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``. Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``.
.. function:: quote_from_bytes(bytes[, safe])
.. function:: quote_from_bytes(bytes, safe='/')
Like :func:`quote`, but accepts a :class:`bytes` object rather than a Like :func:`quote`, but accepts a :class:`bytes` object rather than a
:class:`str`, and does not perform string-to-bytes encoding. :class:`str`, and does not perform string-to-bytes encoding.
...@@ -263,7 +265,8 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -263,7 +265,8 @@ The :mod:`urllib.parse` module defines the following functions:
Example: ``quote_from_bytes(b'a&\xef')`` yields Example: ``quote_from_bytes(b'a&\xef')`` yields
``'a%26%EF'``. ``'a%26%EF'``.
.. function:: unquote(string[, encoding[, errors]])
.. function:: unquote(string, encoding='utf-8', errors='replace')
Replace ``%xx`` escapes by their single-character equivalent. Replace ``%xx`` escapes by their single-character equivalent.
The optional *encoding* and *errors* parameters specify how to decode The optional *encoding* and *errors* parameters specify how to decode
...@@ -279,7 +282,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -279,7 +282,7 @@ The :mod:`urllib.parse` module defines the following functions:
Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``. Example: ``unquote('/El%20Ni%C3%B1o/')`` yields ``'/El Niño/'``.
.. function:: unquote_plus(string[, encoding[, errors]]) .. function:: unquote_plus(string, encoding='utf-8', errors='replace')
Like :func:`unquote`, but also replace plus signs by spaces, as required for Like :func:`unquote`, but also replace plus signs by spaces, as required for
unquoting HTML form values. unquoting HTML form values.
...@@ -288,6 +291,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -288,6 +291,7 @@ The :mod:`urllib.parse` module defines the following functions:
Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``. Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``.
.. function:: unquote_to_bytes(string) .. function:: unquote_to_bytes(string)
Replace ``%xx`` escapes by their single-octet equivalent, and return a Replace ``%xx`` escapes by their single-octet equivalent, and return a
...@@ -302,7 +306,7 @@ The :mod:`urllib.parse` module defines the following functions: ...@@ -302,7 +306,7 @@ The :mod:`urllib.parse` module defines the following functions:
``b'a&\xef'``. ``b'a&\xef'``.
.. function:: urlencode(query[, doseq]) .. function:: urlencode(query, doseq=False)
Convert a mapping object or a sequence of two-element tuples to a "url-encoded" Convert a mapping object or a sequence of two-element tuples to a "url-encoded"
string, suitable to pass to :func:`urlopen` above as the optional *data* string, suitable to pass to :func:`urlopen` above as the optional *data*
......
...@@ -14,7 +14,7 @@ authentication, redirections, cookies and more. ...@@ -14,7 +14,7 @@ authentication, redirections, cookies and more.
The :mod:`urllib.request` module defines the following functions: The :mod:`urllib.request` module defines the following functions:
.. function:: urlopen(url[, data][, timeout]) .. function:: urlopen(url, data=None[, timeout])
Open the URL *url*, which can be either a string or a Open the URL *url*, which can be either a string or a
:class:`Request` object. :class:`Request` object.
...@@ -75,13 +75,14 @@ The :mod:`urllib.request` module defines the following functions: ...@@ -75,13 +75,14 @@ The :mod:`urllib.request` module defines the following functions:
:class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`, :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
:class:`HTTPErrorProcessor`. :class:`HTTPErrorProcessor`.
If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported), If the Python installation has SSL support (i.e., if the :mod:`ssl` module
:class:`HTTPSHandler` will also be added. can be imported), :class:`HTTPSHandler` will also be added.
A :class:`BaseHandler` subclass may also change its :attr:`handler_order` A :class:`BaseHandler` subclass may also change its :attr:`handler_order`
member variable to modify its position in the handlers list. member variable to modify its position in the handlers list.
.. function:: urlretrieve(url[, filename[, reporthook[, data]]])
.. function:: urlretrieve(url, filename=None, reporthook=None, data=None)
Copy a network object denoted by a URL to a local file, if necessary. If the URL Copy a network object denoted by a URL to a local file, if necessary. If the URL
points to a local file, or a valid cached copy of the object exists, the object points to a local file, or a valid cached copy of the object exists, the object
...@@ -160,9 +161,10 @@ The :mod:`urllib.request` module defines the following functions: ...@@ -160,9 +161,10 @@ The :mod:`urllib.request` module defines the following functions:
path. This does not accept a complete URL. This function uses :func:`unquote` path. This does not accept a complete URL. This function uses :func:`unquote`
to decode *path*. to decode *path*.
The following classes are provided: The following classes are provided:
.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable]) .. class:: Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False)
This class is an abstraction of a URL request. This class is an abstraction of a URL request.
...@@ -205,7 +207,8 @@ The following classes are provided: ...@@ -205,7 +207,8 @@ The following classes are provided:
document, and the user had no option to approve the automatic document, and the user had no option to approve the automatic
fetching of the image, this should be true. fetching of the image, this should be true.
.. class:: URLopener([proxies[, **x509]])
.. class:: URLopener(proxies=None, **x509)
Base class for opening and reading URLs. Unless you need to support opening Base class for opening and reading URLs. Unless you need to support opening
objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`, objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
...@@ -230,7 +233,7 @@ The following classes are provided: ...@@ -230,7 +233,7 @@ The following classes are provided:
:class:`URLopener` objects will raise an :exc:`IOError` exception if the server :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
returns an error code. returns an error code.
.. method:: open(fullurl[, data]) .. method:: open(fullurl, data=None)
Open *fullurl* using the appropriate protocol. This method sets up cache and Open *fullurl* using the appropriate protocol. This method sets up cache and
proxy information, then calls the appropriate open method with its input proxy information, then calls the appropriate open method with its input
...@@ -239,12 +242,12 @@ The following classes are provided: ...@@ -239,12 +242,12 @@ The following classes are provided:
:func:`urlopen`. :func:`urlopen`.
.. method:: open_unknown(fullurl[, data]) .. method:: open_unknown(fullurl, data=None)
Overridable interface to open unknown URL types. Overridable interface to open unknown URL types.
.. method:: retrieve(url[, filename[, reporthook[, data]]]) .. method:: retrieve(url, filename=None, reporthook=None, data=None)
Retrieves the contents of *url* and places it in *filename*. The return value Retrieves the contents of *url* and places it in *filename*. The return value
is a tuple consisting of a local filename and either a is a tuple consisting of a local filename and either a
...@@ -337,12 +340,12 @@ The following classes are provided: ...@@ -337,12 +340,12 @@ The following classes are provided:
A class to handle redirections. A class to handle redirections.
.. class:: HTTPCookieProcessor([cookiejar]) .. class:: HTTPCookieProcessor(cookiejar=None)
A class to handle HTTP Cookies. A class to handle HTTP Cookies.
.. class:: ProxyHandler([proxies]) .. class:: ProxyHandler(proxies=None)
Cause requests to go through a proxy. If *proxies* is given, it must be a Cause requests to go through a proxy. If *proxies* is given, it must be a
dictionary mapping protocol names to URLs of proxies. The default is to read the dictionary mapping protocol names to URLs of proxies. The default is to read the
...@@ -362,7 +365,7 @@ The following classes are provided: ...@@ -362,7 +365,7 @@ The following classes are provided:
fits. fits.
.. class:: AbstractBasicAuthHandler([password_mgr]) .. class:: AbstractBasicAuthHandler(password_mgr=None)
This is a mixin class that helps with HTTP authentication, both to the remote This is a mixin class that helps with HTTP authentication, both to the remote
host and to a proxy. *password_mgr*, if given, should be something that is host and to a proxy. *password_mgr*, if given, should be something that is
...@@ -371,7 +374,7 @@ The following classes are provided: ...@@ -371,7 +374,7 @@ The following classes are provided:
supported. supported.
.. class:: HTTPBasicAuthHandler([password_mgr]) .. class:: HTTPBasicAuthHandler(password_mgr=None)
Handle authentication with the remote host. *password_mgr*, if given, should be Handle authentication with the remote host. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section something that is compatible with :class:`HTTPPasswordMgr`; refer to section
...@@ -379,7 +382,7 @@ The following classes are provided: ...@@ -379,7 +382,7 @@ The following classes are provided:
supported. supported.
.. class:: ProxyBasicAuthHandler([password_mgr]) .. class:: ProxyBasicAuthHandler(password_mgr=None)
Handle authentication with the proxy. *password_mgr*, if given, should be Handle authentication with the proxy. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section something that is compatible with :class:`HTTPPasswordMgr`; refer to section
...@@ -387,7 +390,7 @@ The following classes are provided: ...@@ -387,7 +390,7 @@ The following classes are provided:
supported. supported.
.. class:: AbstractDigestAuthHandler([password_mgr]) .. class:: AbstractDigestAuthHandler(password_mgr=None)
This is a mixin class that helps with HTTP authentication, both to the remote This is a mixin class that helps with HTTP authentication, both to the remote
host and to a proxy. *password_mgr*, if given, should be something that is host and to a proxy. *password_mgr*, if given, should be something that is
...@@ -396,7 +399,7 @@ The following classes are provided: ...@@ -396,7 +399,7 @@ The following classes are provided:
supported. supported.
.. class:: HTTPDigestAuthHandler([password_mgr]) .. class:: HTTPDigestAuthHandler(password_mgr=None)
Handle authentication with the remote host. *password_mgr*, if given, should be Handle authentication with the remote host. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section something that is compatible with :class:`HTTPPasswordMgr`; refer to section
...@@ -404,7 +407,7 @@ The following classes are provided: ...@@ -404,7 +407,7 @@ The following classes are provided:
supported. supported.
.. class:: ProxyDigestAuthHandler([password_mgr]) .. class:: ProxyDigestAuthHandler(password_mgr=None)
Handle authentication with the proxy. *password_mgr*, if given, should be Handle authentication with the proxy. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section something that is compatible with :class:`HTTPPasswordMgr`; refer to section
...@@ -597,7 +600,7 @@ OpenerDirector Objects ...@@ -597,7 +600,7 @@ OpenerDirector Objects
post-process *protocol* responses. post-process *protocol* responses.
.. method:: OpenerDirector.open(url[, data][, timeout]) .. method:: OpenerDirector.open(url, data=None[, timeout])
Open the given *url* (which can be a request object or a string), optionally Open the given *url* (which can be a request object or a string), optionally
passing the given *data*. Arguments, return values and exceptions raised are passing the given *data*. Arguments, return values and exceptions raised are
...@@ -609,7 +612,7 @@ OpenerDirector Objects ...@@ -609,7 +612,7 @@ OpenerDirector Objects
HTTP, HTTPS, FTP and FTPS connections). HTTP, HTTPS, FTP and FTPS connections).
.. method:: OpenerDirector.error(proto[, arg[, ...]]) .. method:: OpenerDirector.error(proto, *args)
Handle an error of the given protocol. This will call the registered error Handle an error of the given protocol. This will call the registered error
handlers for the given protocol with the given arguments (which are protocol handlers for the given protocol with the given arguments (which are protocol
......
:mod:`uu` --- Encode and decode uuencode files :mod:`uu` --- Encode and decode uuencode files
============================================== ==============================================
...@@ -25,7 +24,7 @@ This code was contributed by Lance Ellinghouse, and modified by Jack Jansen. ...@@ -25,7 +24,7 @@ This code was contributed by Lance Ellinghouse, and modified by Jack Jansen.
The :mod:`uu` module defines the following functions: The :mod:`uu` module defines the following functions:
.. function:: encode(in_file, out_file[, name[, mode]]) .. function:: encode(in_file, out_file, name=None, mode=None)
Uuencode file *in_file* into file *out_file*. The uuencoded file will have Uuencode file *in_file* into file *out_file*. The uuencoded file will have
the header specifying *name* and *mode* as the defaults for the results of the header specifying *name* and *mode* as the defaults for the results of
...@@ -33,7 +32,7 @@ The :mod:`uu` module defines the following functions: ...@@ -33,7 +32,7 @@ The :mod:`uu` module defines the following functions:
and ``0o666`` respectively. and ``0o666`` respectively.
.. function:: decode(in_file[, out_file[, mode[, quiet]]]) .. function:: decode(in_file, out_file=None, mode=None, quiet=False)
This call decodes uuencoded file *in_file* placing the result on file This call decodes uuencoded file *in_file* placing the result on file
*out_file*. If *out_file* is a pathname, *mode* is used to set the permission *out_file*. If *out_file* is a pathname, *mode* is used to set the permission
......
:mod:`uuid` --- UUID objects according to RFC 4122 :mod:`uuid` --- UUID objects according to RFC 4122
================================================== ==================================================
...@@ -18,7 +17,7 @@ a UUID containing the computer's network address. :func:`uuid4` creates a ...@@ -18,7 +17,7 @@ a UUID containing the computer's network address. :func:`uuid4` creates a
random UUID. random UUID.
.. class:: UUID([hex[, bytes[, bytes_le[, fields[, int[, version]]]]]]) .. class:: UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None)
Create a UUID from either a string of 32 hexadecimal digits, a string of 16 Create a UUID from either a string of 32 hexadecimal digits, a string of 16
bytes as the *bytes* argument, a string of 16 bytes in little-endian order as bytes as the *bytes* argument, a string of 16 bytes in little-endian order as
...@@ -43,8 +42,8 @@ random UUID. ...@@ -43,8 +42,8 @@ random UUID.
variant and version number set according to RFC 4122, overriding bits in the variant and version number set according to RFC 4122, overriding bits in the
given *hex*, *bytes*, *bytes_le*, *fields*, or *int*. given *hex*, *bytes*, *bytes_le*, *fields*, or *int*.
:class:`UUID` instances have these read-only attributes:
:class:`UUID` instances have these read-only attributes:
.. attribute:: UUID.bytes .. attribute:: UUID.bytes
...@@ -126,7 +125,7 @@ The :mod:`uuid` module defines the following functions: ...@@ -126,7 +125,7 @@ The :mod:`uuid` module defines the following functions:
.. index:: single: getnode .. index:: single: getnode
.. function:: uuid1([node[, clock_seq]]) .. function:: uuid1(node=None, clock_seq=None)
Generate a UUID from a host ID, sequence number, and the current time. If *node* Generate a UUID from a host ID, sequence number, and the current time. If *node*
is not given, :func:`getnode` is used to obtain the hardware address. If is not given, :func:`getnode` is used to obtain the hardware address. If
......
...@@ -234,7 +234,7 @@ Available Functions ...@@ -234,7 +234,7 @@ Available Functions
------------------- -------------------
.. function:: warn(message[, category[, stacklevel]]) .. function:: warn(message, category=None, stacklevel=1)
Issue a warning, or maybe ignore it or raise an exception. The *category* Issue a warning, or maybe ignore it or raise an exception. The *category*
argument, if given, must be a warning category class (see above); it defaults to argument, if given, must be a warning category class (see above); it defaults to
...@@ -253,7 +253,7 @@ Available Functions ...@@ -253,7 +253,7 @@ Available Functions
of the warning message). of the warning message).
.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]]) .. function:: warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None)
This is a low-level interface to the functionality of :func:`warn`, passing in This is a low-level interface to the functionality of :func:`warn`, passing in
explicitly the message, category, filename and line number, and optionally the explicitly the message, category, filename and line number, and optionally the
...@@ -270,7 +270,7 @@ Available Functions ...@@ -270,7 +270,7 @@ Available Functions
sources). sources).
.. function:: showwarning(message, category, filename, lineno[, file[, line]]) .. function:: showwarning(message, category, filename, lineno, file=None, line=None)
Write a warning to a file. The default implementation calls Write a warning to a file. The default implementation calls
``formatwarning(message, category, filename, lineno, line)`` and writes the ``formatwarning(message, category, filename, lineno, line)`` and writes the
...@@ -282,7 +282,7 @@ Available Functions ...@@ -282,7 +282,7 @@ Available Functions
try to read the line specified by *filename* and *lineno*. try to read the line specified by *filename* and *lineno*.
.. function:: formatwarning(message, category, filename, lineno[, line]) .. function:: formatwarning(message, category, filename, lineno, line=None)
Format a warning the standard way. This returns a string which may contain Format a warning the standard way. This returns a string which may contain
embedded newlines and ends in a newline. *line* is a line of source code to embedded newlines and ends in a newline. *line* is a line of source code to
...@@ -291,7 +291,7 @@ Available Functions ...@@ -291,7 +291,7 @@ Available Functions
*lineno*. *lineno*.
.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]]) .. function:: filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)
Insert an entry into the list of :ref:`warnings filter specifications Insert an entry into the list of :ref:`warnings filter specifications
<warning-filter>`. The entry is inserted at the front by default; if <warning-filter>`. The entry is inserted at the front by default; if
...@@ -303,7 +303,7 @@ Available Functions ...@@ -303,7 +303,7 @@ Available Functions
everything. everything.
.. function:: simplefilter(action[, category[, lineno[, append]]]) .. function:: simplefilter(action, category=Warning, lineno=0, append=False)
Insert a simple entry into the list of :ref:`warnings filter specifications Insert a simple entry into the list of :ref:`warnings filter specifications
<warning-filter>`. The meaning of the function parameters is as for <warning-filter>`. The meaning of the function parameters is as for
...@@ -322,7 +322,7 @@ Available Functions ...@@ -322,7 +322,7 @@ Available Functions
Available Context Managers Available Context Managers
-------------------------- --------------------------
.. class:: catch_warnings([\*, record=False, module=None]) .. class:: catch_warnings(\*, record=False, module=None)
A context manager that copies and, upon exit, restores the warnings filter A context manager that copies and, upon exit, restores the warnings filter
and the :func:`showwarning` function. and the :func:`showwarning` function.
......
...@@ -12,7 +12,7 @@ It does not support compression/decompression, but it does support mono/stereo. ...@@ -12,7 +12,7 @@ It does not support compression/decompression, but it does support mono/stereo.
The :mod:`wave` module defines the following function and exception: The :mod:`wave` module defines the following function and exception:
.. function:: open(file[, mode]) .. function:: open(file, mode=None)
If *file* is a string, open the file by that name, other treat it as a seekable If *file* is a string, open the file by that name, other treat it as a seekable
file-like object. *mode* can be any of file-like object. *mode* can be any of
......
:mod:`weakref` --- Weak references :mod:`weakref` --- Weak references
================================== ==================================
...@@ -92,10 +91,10 @@ Extension types can easily be made to support weak references; see ...@@ -92,10 +91,10 @@ Extension types can easily be made to support weak references; see
but cannot be propagated; they are handled in exactly the same way as exceptions but cannot be propagated; they are handled in exactly the same way as exceptions
raised from an object's :meth:`__del__` method. raised from an object's :meth:`__del__` method.
Weak references are :term:`hashable` if the *object* is hashable. They will maintain Weak references are :term:`hashable` if the *object* is hashable. They will
their hash value even after the *object* was deleted. If :func:`hash` is called maintain their hash value even after the *object* was deleted. If
the first time only after the *object* was deleted, the call will raise :func:`hash` is called the first time only after the *object* was deleted,
:exc:`TypeError`. the call will raise :exc:`TypeError`.
Weak references support tests for equality, but not ordering. If the referents Weak references support tests for equality, but not ordering. If the referents
are still alive, two references have the same equality relationship as their are still alive, two references have the same equality relationship as their
......
:mod:`webbrowser` --- Convenient Web-browser controller :mod:`webbrowser` --- Convenient Web-browser controller
======================================================= =======================================================
...@@ -46,7 +45,7 @@ The following exception is defined: ...@@ -46,7 +45,7 @@ The following exception is defined:
The following functions are defined: The following functions are defined:
.. function:: open(url[, new=0[, autoraise=True]]) .. function:: open(url, new=0, autoraise=True)
Display *url* using the default browser. If *new* is 0, the *url* is opened Display *url* using the default browser. If *new* is 0, the *url* is opened
in the same browser window if possible. If *new* is 1, a new browser window in the same browser window if possible. If *new* is 1, a new browser window
...@@ -72,14 +71,14 @@ The following functions are defined: ...@@ -72,14 +71,14 @@ The following functions are defined:
equivalent to :func:`open_new`. equivalent to :func:`open_new`.
.. function:: get([name]) .. function:: get(using=None)
Return a controller object for the browser type *name*. If *name* is empty, Return a controller object for the browser type *using*. If *using* is
return a controller for a default browser appropriate to the caller's ``None``, return a controller for a default browser appropriate to the
environment. caller's environment.
.. function:: register(name, constructor[, instance]) .. function:: register(name, constructor, instance=None)
Register the browser type *name*. Once a browser type is registered, the Register the browser type *name*. Once a browser type is registered, the
:func:`get` function can return a controller for that browser type. If :func:`get` function can return a controller for that browser type. If
...@@ -175,7 +174,7 @@ Browser controllers provide these methods which parallel three of the ...@@ -175,7 +174,7 @@ Browser controllers provide these methods which parallel three of the
module-level convenience functions: module-level convenience functions:
.. method:: controller.open(url[, new[, autoraise=True]]) .. method:: controller.open(url, new=0, autoraise=True)
Display *url* using the browser handled by this controller. If *new* is 1, a new Display *url* using the browser handled by this controller. If *new* is 1, a new
browser window is opened if possible. If *new* is 2, a new browser page ("tab") browser window is opened if possible. If *new* is 2, a new browser page ("tab")
......
...@@ -183,7 +183,7 @@ This module offers the following functions: ...@@ -183,7 +183,7 @@ This module offers the following functions:
:const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true. :const:`HKEY_LOCAL_MACHINE` tree. This may or may not be true.
.. function:: OpenKey(key, sub_key[, res=0][, sam=KEY_READ]) .. function:: OpenKey(key, sub_key, res=0, sam=KEY_READ)
Opens the specified key, returning a :dfn:`handle object` Opens the specified key, returning a :dfn:`handle object`
...@@ -195,7 +195,7 @@ This module offers the following functions: ...@@ -195,7 +195,7 @@ This module offers the following functions:
*res* is a reserved integer, and must be zero. The default is zero. *res* is a reserved integer, and must be zero. The default is zero.
*sam* is an integer that specifies an access mask that describes the desired *sam* is an integer that specifies an access mask that describes the desired
security access for the key. Default is :const:`KEY_READ` security access for the key. Default is :const:`KEY_READ`.
The result is a new handle to the specified key. The result is a new handle to the specified key.
......
:mod:`winsound` --- Sound-playing interface for Windows :mod:`winsound` --- Sound-playing interface for Windows
======================================================= =======================================================
...@@ -31,7 +30,7 @@ provided by Windows platforms. It includes functions and several constants. ...@@ -31,7 +30,7 @@ provided by Windows platforms. It includes functions and several constants.
indicates an error, :exc:`RuntimeError` is raised. indicates an error, :exc:`RuntimeError` is raised.
.. function:: MessageBeep([type=MB_OK]) .. function:: MessageBeep(type=MB_OK)
Call the underlying :cfunc:`MessageBeep` function from the Platform API. This Call the underlying :cfunc:`MessageBeep` function from the Platform API. This
plays a sound as specified in the registry. The *type* argument specifies which plays a sound as specified in the registry. The *type* argument specifies which
......
...@@ -57,7 +57,7 @@ parameter expect a WSGI-compliant dictionary to be supplied; please see ...@@ -57,7 +57,7 @@ parameter expect a WSGI-compliant dictionary to be supplied; please see
found, and "http" otherwise. found, and "http" otherwise.
.. function:: request_uri(environ [, include_query=1]) .. function:: request_uri(environ, include_query=True)
Return the full request URI, optionally including the query string, using the Return the full request URI, optionally including the query string, using the
algorithm found in the "URL Reconstruction" section of :pep:`333`. If algorithm found in the "URL Reconstruction" section of :pep:`333`. If
...@@ -146,7 +146,7 @@ also provides these miscellaneous utilities: ...@@ -146,7 +146,7 @@ also provides these miscellaneous utilities:
:rfc:`2616`. :rfc:`2616`.
.. class:: FileWrapper(filelike [, blksize=8192]) .. class:: FileWrapper(filelike, blksize=8192)
A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects A wrapper to convert a file-like object to an :term:`iterator`. The resulting objects
support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for
...@@ -269,7 +269,7 @@ request. (E.g., using the :func:`shift_path_info` function from ...@@ -269,7 +269,7 @@ request. (E.g., using the :func:`shift_path_info` function from
:mod:`wsgiref.util`.) :mod:`wsgiref.util`.)
.. function:: make_server(host, port, app [, server_class=WSGIServer [, handler_class=WSGIRequestHandler]]) .. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)
Create a new WSGI server listening on *host* and *port*, accepting connections Create a new WSGI server listening on *host* and *port*, accepting connections
for *app*. The return value is an instance of the supplied *server_class*, and for *app*. The return value is an instance of the supplied *server_class*, and
...@@ -458,7 +458,7 @@ input, output, and error streams. ...@@ -458,7 +458,7 @@ input, output, and error streams.
environment. environment.
.. class:: BaseCGIHandler(stdin, stdout, stderr, environ [, multithread=True [, multiprocess=False]]) .. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)
Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and
:mod:`os` modules, the CGI environment and I/O streams are specified explicitly. :mod:`os` modules, the CGI environment and I/O streams are specified explicitly.
...@@ -473,7 +473,7 @@ input, output, and error streams. ...@@ -473,7 +473,7 @@ input, output, and error streams.
instead of :class:`SimpleHandler`. instead of :class:`SimpleHandler`.
.. class:: SimpleHandler(stdin, stdout, stderr, environ [,multithread=True [, multiprocess=False]]) .. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)
Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin
servers. If you are writing an HTTP server implementation, you will probably servers. If you are writing an HTTP server implementation, you will probably
......
:mod:`xdrlib` --- Encode and decode XDR data :mod:`xdrlib` --- Encode and decode XDR data
============================================ ============================================
......
:mod:`xml.dom.minidom` --- Lightweight DOM implementation :mod:`xml.dom.minidom` --- Lightweight DOM implementation
========================================================= =========================================================
...@@ -28,7 +27,7 @@ DOM applications typically start by parsing some XML into a DOM. With ...@@ -28,7 +27,7 @@ DOM applications typically start by parsing some XML into a DOM. With
The :func:`parse` function can take either a filename or an open file object. The :func:`parse` function can take either a filename or an open file object.
.. function:: parse(filename_or_file[, parser[, bufsize]]) .. function:: parse(filename_or_file, parser=None, bufsize=None)
Return a :class:`Document` from the given input. *filename_or_file* may be Return a :class:`Document` from the given input. *filename_or_file* may be
either a file name, or a file-like object. *parser*, if given, must be a SAX2 either a file name, or a file-like object. *parser*, if given, must be a SAX2
...@@ -40,7 +39,7 @@ If you have XML in a string, you can use the :func:`parseString` function ...@@ -40,7 +39,7 @@ If you have XML in a string, you can use the :func:`parseString` function
instead: instead:
.. function:: parseString(string[, parser]) .. function:: parseString(string, parser=None)
Return a :class:`Document` that represents the *string*. This method creates a Return a :class:`Document` that represents the *string*. This method creates a
:class:`StringIO` object for the string and passes that on to :func:`parse`. :class:`StringIO` object for the string and passes that on to :func:`parse`.
...@@ -126,7 +125,7 @@ module documentation. This section lists the differences between the API and ...@@ -126,7 +125,7 @@ module documentation. This section lists the differences between the API and
to discard children of that node. to discard children of that node.
.. method:: Node.writexml(writer[, indent=""[, addindent=""[, newl=""[, encoding=""]]]]) .. method:: Node.writexml(writer, indent="", addindent="", newl="", encoding="")
Write XML to the writer object. The writer should have a :meth:`write` method Write XML to the writer object. The writer should have a :meth:`write` method
which matches that of the file object interface. The *indent* parameter is the which matches that of the file object interface. The *indent* parameter is the
...@@ -138,7 +137,7 @@ module documentation. This section lists the differences between the API and ...@@ -138,7 +137,7 @@ module documentation. This section lists the differences between the API and
used to specify the encoding field of the XML header. used to specify the encoding field of the XML header.
.. method:: Node.toxml([encoding]) .. method:: Node.toxml(encoding=None)
Return the XML that the DOM represents as a string. Return the XML that the DOM represents as a string.
...@@ -153,7 +152,7 @@ module documentation. This section lists the differences between the API and ...@@ -153,7 +152,7 @@ module documentation. This section lists the differences between the API and
encoding argument should be specified as "utf-8". encoding argument should be specified as "utf-8".
.. method:: Node.toprettyxml([indent=""[, newl=""[, encoding=""]]]) .. method:: Node.toprettyxml(indent="", newl="", encoding="")
Return a pretty-printed version of the document. *indent* specifies the Return a pretty-printed version of the document. *indent* specifies the
indentation string and defaults to a tabulator; *newl* specifies the string indentation string and defaults to a tabulator; *newl* specifies the string
......
:mod:`xml.dom.pulldom` --- Support for building partial DOM trees :mod:`xml.dom.pulldom` --- Support for building partial DOM trees
================================================================= =================================================================
...@@ -11,7 +10,7 @@ ...@@ -11,7 +10,7 @@
Object Model representation of a document from SAX events. Object Model representation of a document from SAX events.
.. class:: PullDOM([documentFactory]) .. class:: PullDOM(documentFactory=None)
:class:`xml.sax.handler.ContentHandler` implementation that ... :class:`xml.sax.handler.ContentHandler` implementation that ...
...@@ -21,17 +20,17 @@ Object Model representation of a document from SAX events. ...@@ -21,17 +20,17 @@ Object Model representation of a document from SAX events.
... ...
.. class:: SAX2DOM([documentFactory]) .. class:: SAX2DOM(documentFactory=None)
:class:`xml.sax.handler.ContentHandler` implementation that ... :class:`xml.sax.handler.ContentHandler` implementation that ...
.. function:: parse(stream_or_string[, parser[, bufsize]]) .. function:: parse(stream_or_string, parser=None, bufsize=None)
... ...
.. function:: parseString(string[, parser]) .. function:: parseString(string, parser=None)
... ...
......
:mod:`xml.dom` --- The Document Object Model API :mod:`xml.dom` --- The Document Object Model API
================================================ ================================================
...@@ -96,7 +95,7 @@ The :mod:`xml.dom` contains the following functions: ...@@ -96,7 +95,7 @@ The :mod:`xml.dom` contains the following functions:
implementation supports some customization). implementation supports some customization).
.. function:: getDOMImplementation([name[, features]]) .. function:: getDOMImplementation(name=None, features=())
Return a suitable DOM implementation. The *name* is either well-known, the Return a suitable DOM implementation. The *name* is either well-known, the
module name of a DOM implementation, or ``None``. If it is not ``None``, imports module name of a DOM implementation, or ``None``. If it is not ``None``, imports
......
:mod:`xml.etree.ElementTree` --- The ElementTree XML API :mod:`xml.etree.ElementTree` --- The ElementTree XML API
======================================================== ========================================================
...@@ -41,7 +40,7 @@ Functions ...@@ -41,7 +40,7 @@ Functions
--------- ---------
.. function:: Comment([text]) .. function:: Comment(text=None)
Comment element factory. This factory function creates a special element Comment element factory. This factory function creates a special element
that will be serialized as an XML comment. The comment string can be either that will be serialized as an XML comment. The comment string can be either
...@@ -61,7 +60,7 @@ Functions ...@@ -61,7 +60,7 @@ Functions
*elem* is an element tree or an individual element. *elem* is an element tree or an individual element.
.. function:: Element(tag[, attrib][, **extra]) .. function:: Element(tag, attrib={}, **extra)
Element factory. This function returns an object implementing the standard Element factory. This function returns an object implementing the standard
Element interface. The exact class or type of that object is implementation Element interface. The exact class or type of that object is implementation
...@@ -87,7 +86,7 @@ Functions ...@@ -87,7 +86,7 @@ Functions
element instance. Returns a true value if this is an element object. element instance. Returns a true value if this is an element object.
.. function:: iterparse(source[, events]) .. function:: iterparse(source, events=None)
Parses an XML section into an element tree incrementally, and reports what's Parses an XML section into an element tree incrementally, and reports what's
going on to the user. *source* is a filename or file object containing XML data. going on to the user. *source* is a filename or file object containing XML data.
...@@ -105,7 +104,7 @@ Functions ...@@ -105,7 +104,7 @@ Functions
If you need a fully populated element, look for "end" events instead. If you need a fully populated element, look for "end" events instead.
.. function:: parse(source[, parser]) .. function:: parse(source, parser=None)
Parses an XML section into an element tree. *source* is a filename or file Parses an XML section into an element tree. *source* is a filename or file
object containing XML data. *parser* is an optional parser instance. If not object containing XML data. *parser* is an optional parser instance. If not
...@@ -113,7 +112,7 @@ Functions ...@@ -113,7 +112,7 @@ Functions
instance. instance.
.. function:: ProcessingInstruction(target[, text]) .. function:: ProcessingInstruction(target, text=None)
PI element factory. This factory function creates a special element that will PI element factory. This factory function creates a special element that will
be serialized as an XML processing instruction. *target* is a string containing be serialized as an XML processing instruction. *target* is a string containing
...@@ -121,7 +120,7 @@ Functions ...@@ -121,7 +120,7 @@ Functions
an element instance, representing a processing instruction. an element instance, representing a processing instruction.
.. function:: SubElement(parent, tag[, attrib[, **extra]]) .. function:: SubElement(parent, tag, attrib={}, **extra)
Subelement factory. This function creates an element instance, and appends it Subelement factory. This function creates an element instance, and appends it
to an existing element. to an existing element.
...@@ -133,7 +132,7 @@ Functions ...@@ -133,7 +132,7 @@ Functions
as keyword arguments. Returns an element instance. as keyword arguments. Returns an element instance.
.. function:: tostring(element[, encoding]) .. function:: tostring(element, encoding=None)
Generates a string representation of an XML element, including all subelements. Generates a string representation of an XML element, including all subelements.
*element* is an Element instance. *encoding* is the output encoding (default is *element* is an Element instance. *encoding* is the output encoding (default is
...@@ -202,7 +201,7 @@ The following dictionary-like methods work on the element attributes. ...@@ -202,7 +201,7 @@ The following dictionary-like methods work on the element attributes.
attributes, and sets the text and tail attributes to None. attributes, and sets the text and tail attributes to None.
.. method:: Element.get(key[, default=None]) .. method:: Element.get(key, default=None)
Gets the element attribute named *key*. Gets the element attribute named *key*.
...@@ -246,7 +245,7 @@ The following methods work on the element's children (subelements). ...@@ -246,7 +245,7 @@ The following methods work on the element's children (subelements).
Returns an iterable yielding all matching elements in document order. Returns an iterable yielding all matching elements in document order.
.. method:: Element.findtext(condition[, default=None]) .. method:: Element.findtext(condition, default=None)
Finds text for the first subelement matching *condition*. *condition* may be a Finds text for the first subelement matching *condition*. *condition* may be a
tag name or path. Returns the text content of the first matching element, or tag name or path. Returns the text content of the first matching element, or
...@@ -259,7 +258,7 @@ The following methods work on the element's children (subelements). ...@@ -259,7 +258,7 @@ The following methods work on the element's children (subelements).
Returns all subelements. The elements are returned in document order. Returns all subelements. The elements are returned in document order.
.. method:: Element.getiterator([tag=None]) .. method:: Element.getiterator(tag=None)
Creates a tree iterator with the current element as the root. The iterator Creates a tree iterator with the current element as the root. The iterator
iterates over this element and all elements below it, in document (depth first) iterates over this element and all elements below it, in document (depth first)
...@@ -305,7 +304,7 @@ ElementTree Objects ...@@ -305,7 +304,7 @@ ElementTree Objects
------------------- -------------------
.. class:: ElementTree([element,] [file]) .. class:: ElementTree(element=None, file=None)
ElementTree wrapper class. This class represents an entire element hierarchy, ElementTree wrapper class. This class represents an entire element hierarchy,
and adds some extra support for serialization to and from standard XML. and adds some extra support for serialization to and from standard XML.
...@@ -336,7 +335,7 @@ ElementTree Objects ...@@ -336,7 +335,7 @@ ElementTree Objects
order. order.
.. method:: findtext(path[, default]) .. method:: findtext(path, default=None)
Finds the element text for the first toplevel element with given tag. Finds the element text for the first toplevel element with given tag.
Same as getroot().findtext(path). *path* is the toplevel element to look Same as getroot().findtext(path). *path* is the toplevel element to look
...@@ -346,7 +345,7 @@ ElementTree Objects ...@@ -346,7 +345,7 @@ ElementTree Objects
found, but has no text content, this method returns an empty string. found, but has no text content, this method returns an empty string.
.. method:: getiterator([tag]) .. method:: getiterator(tag=None)
Creates and returns a tree iterator for the root element. The iterator Creates and returns a tree iterator for the root element. The iterator
loops over all elements in this tree, in section order. *tag* is the tag loops over all elements in this tree, in section order. *tag* is the tag
...@@ -358,7 +357,7 @@ ElementTree Objects ...@@ -358,7 +357,7 @@ ElementTree Objects
Returns the root element for this tree. Returns the root element for this tree.
.. method:: parse(source[, parser]) .. method:: parse(source, parser=None)
Loads an external XML section into this element tree. *source* is a file Loads an external XML section into this element tree. *source* is a file
name or file object. *parser* is an optional parser instance. If not name or file object. *parser* is an optional parser instance. If not
...@@ -366,7 +365,7 @@ ElementTree Objects ...@@ -366,7 +365,7 @@ ElementTree Objects
root element. root element.
.. method:: write(file[, encoding]) .. method:: write(file, encoding=None)
Writes the element tree to a file, as XML. *file* is a file name, or a Writes the element tree to a file, as XML. *file* is a file name, or a
file object opened for writing. *encoding* [1]_ is the output encoding file object opened for writing. *encoding* [1]_ is the output encoding
...@@ -406,7 +405,7 @@ QName Objects ...@@ -406,7 +405,7 @@ QName Objects
------------- -------------
.. class:: QName(text_or_uri[, tag]) .. class:: QName(text_or_uri, tag=None)
QName wrapper. This can be used to wrap a QName attribute value, in order to QName wrapper. This can be used to wrap a QName attribute value, in order to
get proper namespace handling on output. *text_or_uri* is a string containing get proper namespace handling on output. *text_or_uri* is a string containing
...@@ -422,7 +421,7 @@ TreeBuilder Objects ...@@ -422,7 +421,7 @@ TreeBuilder Objects
------------------- -------------------
.. class:: TreeBuilder([element_factory]) .. class:: TreeBuilder(element_factory=None)
Generic element structure builder. This builder converts a sequence of start, Generic element structure builder. This builder converts a sequence of start,
data, and end method calls to a well-formed element structure. You can use this data, and end method calls to a well-formed element structure. You can use this
...@@ -461,7 +460,7 @@ XMLTreeBuilder Objects ...@@ -461,7 +460,7 @@ XMLTreeBuilder Objects
---------------------- ----------------------
.. class:: XMLTreeBuilder([html,] [target]) .. class:: XMLTreeBuilder(html=0, target=None)
Element structure builder for XML source data, based on the expat parser. *html* Element structure builder for XML source data, based on the expat parser. *html*
are predefined HTML entities. This flag is not supported by the current are predefined HTML entities. This flag is not supported by the current
......
:mod:`xml.sax.handler` --- Base classes for SAX handlers :mod:`xml.sax.handler` --- Base classes for SAX handlers
======================================================== ========================================================
......
:mod:`xml.sax.xmlreader` --- Interface for XML parsers :mod:`xml.sax.xmlreader` --- Interface for XML parsers
====================================================== ======================================================
...@@ -48,7 +47,7 @@ a new parser object. ...@@ -48,7 +47,7 @@ a new parser object.
methods may return ``None``. methods may return ``None``.
.. class:: InputSource([systemId]) .. class:: InputSource(system_id=None)
Encapsulation of the information needed by the :class:`XMLReader` to read Encapsulation of the information needed by the :class:`XMLReader` to read
entities. entities.
......
:mod:`xml.sax` --- Support for SAX2 parsers :mod:`xml.sax` --- Support for SAX2 parsers
=========================================== ===========================================
...@@ -17,7 +16,7 @@ the SAX API. ...@@ -17,7 +16,7 @@ the SAX API.
The convenience functions are: The convenience functions are:
.. function:: make_parser([parser_list]) .. function:: make_parser(parser_list=[])
Create and return a SAX :class:`XMLReader` object. The first parser found will Create and return a SAX :class:`XMLReader` object. The first parser found will
be used. If *parser_list* is provided, it must be a sequence of strings which be used. If *parser_list* is provided, it must be a sequence of strings which
...@@ -25,7 +24,7 @@ The convenience functions are: ...@@ -25,7 +24,7 @@ The convenience functions are:
in *parser_list* will be used before modules in the default list of parsers. in *parser_list* will be used before modules in the default list of parsers.
.. function:: parse(filename_or_stream, handler[, error_handler]) .. function:: parse(filename_or_stream, handler, error_handler=handler.ErrorHandler())
Create a SAX parser and use it to parse a document. The document, passed in as Create a SAX parser and use it to parse a document. The document, passed in as
*filename_or_stream*, can be a filename or a file object. The *handler* *filename_or_stream*, can be a filename or a file object. The *handler*
...@@ -35,7 +34,7 @@ The convenience functions are: ...@@ -35,7 +34,7 @@ The convenience functions are:
return value; all work must be done by the *handler* passed in. return value; all work must be done by the *handler* passed in.
.. function:: parseString(string, handler[, error_handler]) .. function:: parseString(string, handler, error_handler=handler.ErrorHandler())
Similar to :func:`parse`, but parses from a buffer *string* received as a Similar to :func:`parse`, but parses from a buffer *string* received as a
parameter. parameter.
...@@ -66,7 +65,7 @@ In addition to these classes, :mod:`xml.sax` provides the following exception ...@@ -66,7 +65,7 @@ In addition to these classes, :mod:`xml.sax` provides the following exception
classes. classes.
.. exception:: SAXException(msg[, exception]) .. exception:: SAXException(msg, exception=None)
Encapsulate an XML error or warning. This class can contain basic error or Encapsulate an XML error or warning. This class can contain basic error or
warning information from either the XML parser or the application: it can be warning information from either the XML parser or the application: it can be
...@@ -90,14 +89,14 @@ classes. ...@@ -90,14 +89,14 @@ classes.
interface as well as the :class:`SAXException` interface. interface as well as the :class:`SAXException` interface.
.. exception:: SAXNotRecognizedException(msg[, exception]) .. exception:: SAXNotRecognizedException(msg, exception=None)
Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is
confronted with an unrecognized feature or property. SAX applications and confronted with an unrecognized feature or property. SAX applications and
extensions may use this class for similar purposes. extensions may use this class for similar purposes.
.. exception:: SAXNotSupportedException(msg[, exception]) .. exception:: SAXNotSupportedException(msg, exception=None)
Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is asked to Subclass of :exc:`SAXException` raised when a SAX :class:`XMLReader` is asked to
enable a feature that is not supported, or to set a property to a value that the enable a feature that is not supported, or to set a property to a value that the
......
:mod:`xml.sax.saxutils` --- SAX Utilities :mod:`xml.sax.saxutils` --- SAX Utilities
========================================= =========================================
...@@ -13,7 +12,7 @@ that are commonly useful when creating SAX applications, either in direct use, ...@@ -13,7 +12,7 @@ that are commonly useful when creating SAX applications, either in direct use,
or as base classes. or as base classes.
.. function:: escape(data[, entities]) .. function:: escape(data, entities={})
Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data. Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data.
...@@ -23,7 +22,7 @@ or as base classes. ...@@ -23,7 +22,7 @@ or as base classes.
``'>'`` are always escaped, even if *entities* is provided. ``'>'`` are always escaped, even if *entities* is provided.
.. function:: unescape(data[, entities]) .. function:: unescape(data, entities={})
Unescape ``'&amp;'``, ``'&lt;'``, and ``'&gt;'`` in a string of data. Unescape ``'&amp;'``, ``'&lt;'``, and ``'&gt;'`` in a string of data.
...@@ -33,7 +32,7 @@ or as base classes. ...@@ -33,7 +32,7 @@ or as base classes.
are always unescaped, even if *entities* is provided. are always unescaped, even if *entities* is provided.
.. function:: quoteattr(data[, entities]) .. function:: quoteattr(data, entities={})
Similar to :func:`escape`, but also prepares *data* to be used as an Similar to :func:`escape`, but also prepares *data* to be used as an
attribute value. The return value is a quoted version of *data* with any attribute value. The return value is a quoted version of *data* with any
...@@ -51,7 +50,7 @@ or as base classes. ...@@ -51,7 +50,7 @@ or as base classes.
using the reference concrete syntax. using the reference concrete syntax.
.. class:: XMLGenerator([out[, encoding]]) .. class:: XMLGenerator(out=None, encoding='iso-8859-1')
This class implements the :class:`ContentHandler` interface by writing SAX This class implements the :class:`ContentHandler` interface by writing SAX
events back into an XML document. In other words, using an :class:`XMLGenerator` events back into an XML document. In other words, using an :class:`XMLGenerator`
...@@ -69,7 +68,7 @@ or as base classes. ...@@ -69,7 +68,7 @@ or as base classes.
requests as they pass through. requests as they pass through.
.. function:: prepare_input_source(source[, base]) .. function:: prepare_input_source(source, base='')
This function takes an input source and an optional base URL and returns a fully This function takes an input source and an optional base URL and returns a fully
resolved :class:`InputSource` object ready for reading. The input source can be resolved :class:`InputSource` object ready for reading. The input source can be
......
...@@ -17,7 +17,7 @@ supports writing XML-RPC client code; it handles all the details of translating ...@@ -17,7 +17,7 @@ supports writing XML-RPC client code; it handles all the details of translating
between conformable Python objects and XML on the wire. between conformable Python objects and XML on the wire.
.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime]]]]]) .. class:: ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False)
A :class:`ServerProxy` instance is an object that manages communication with a A :class:`ServerProxy` instance is an object that manages communication with a
remote XML-RPC server. The required first argument is a URI (Uniform Resource remote XML-RPC server. The required first argument is a URI (Uniform Resource
...@@ -458,7 +458,7 @@ The client code for the preceding server:: ...@@ -458,7 +458,7 @@ The client code for the preceding server::
Convenience Functions Convenience Functions
--------------------- ---------------------
.. function:: dumps(params[, methodname[, methodresponse[, encoding[, allow_none]]]]) .. function:: dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Convert *params* into an XML-RPC request. or into a response if *methodresponse* Convert *params* into an XML-RPC request. or into a response if *methodresponse*
is true. *params* can be either a tuple of arguments or an instance of the is true. *params* can be either a tuple of arguments or an instance of the
...@@ -469,7 +469,7 @@ Convenience Functions ...@@ -469,7 +469,7 @@ Convenience Functions
it via an extension, provide a true value for *allow_none*. it via an extension, provide a true value for *allow_none*.
.. function:: loads(data[, use_datetime]) .. function:: loads(data, use_datetime=False)
Convert an XML-RPC request or response into Python objects, a ``(params, Convert an XML-RPC request or response into Python objects, a ``(params,
methodname)``. *params* is a tuple of argument; *methodname* is a string, or methodname)``. *params* is a tuple of argument; *methodname* is a string, or
......
...@@ -13,7 +13,7 @@ servers written in Python. Servers can either be free standing, using ...@@ -13,7 +13,7 @@ servers written in Python. Servers can either be free standing, using
:class:`CGIXMLRPCRequestHandler`. :class:`CGIXMLRPCRequestHandler`.
.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]]) .. class:: SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True)
Create a new server instance. This class provides methods for registration of Create a new server instance. This class provides methods for registration of
functions that can be called by the XML-RPC protocol. The *requestHandler* functions that can be called by the XML-RPC protocol. The *requestHandler*
...@@ -29,7 +29,7 @@ servers written in Python. Servers can either be free standing, using ...@@ -29,7 +29,7 @@ servers written in Python. Servers can either be free standing, using
the *allow_reuse_address* class variable before the address is bound. the *allow_reuse_address* class variable before the address is bound.
.. class:: CGIXMLRPCRequestHandler([allow_none[, encoding]]) .. class:: CGIXMLRPCRequestHandler(allow_none=False, encoding=None)
Create a new instance to handle XML-RPC requests in a CGI environment. The Create a new instance to handle XML-RPC requests in a CGI environment. The
*allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client` *allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client`
...@@ -53,7 +53,7 @@ The :class:`SimpleXMLRPCServer` class is based on ...@@ -53,7 +53,7 @@ The :class:`SimpleXMLRPCServer` class is based on
alone XML-RPC servers. alone XML-RPC servers.
.. method:: SimpleXMLRPCServer.register_function(function[, name]) .. method:: SimpleXMLRPCServer.register_function(function, name=None)
Register a function that can respond to XML-RPC requests. If *name* is given, Register a function that can respond to XML-RPC requests. If *name* is given,
it will be the method name associated with *function*, otherwise it will be the method name associated with *function*, otherwise
...@@ -62,7 +62,7 @@ alone XML-RPC servers. ...@@ -62,7 +62,7 @@ alone XML-RPC servers.
the period character. the period character.
.. method:: SimpleXMLRPCServer.register_instance(instance[, allow_dotted_names]) .. method:: SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False)
Register an object which is used to expose method names which have not been Register an object which is used to expose method names which have not been
registered using :meth:`register_function`. If *instance* contains a registered using :meth:`register_function`. If *instance* contains a
...@@ -167,7 +167,7 @@ The :class:`CGIXMLRPCRequestHandler` class can be used to handle XML-RPC ...@@ -167,7 +167,7 @@ The :class:`CGIXMLRPCRequestHandler` class can be used to handle XML-RPC
requests sent to Python CGI scripts. requests sent to Python CGI scripts.
.. method:: CGIXMLRPCRequestHandler.register_function(function[, name]) .. method:: CGIXMLRPCRequestHandler.register_function(function, name=None)
Register a function that can respond to XML-RPC requests. If *name* is given, Register a function that can respond to XML-RPC requests. If *name* is given,
it will be the method name associated with function, otherwise it will be the method name associated with function, otherwise
...@@ -201,7 +201,7 @@ requests sent to Python CGI scripts. ...@@ -201,7 +201,7 @@ requests sent to Python CGI scripts.
Register the XML-RPC multicall function ``system.multicall``. Register the XML-RPC multicall function ``system.multicall``.
.. method:: CGIXMLRPCRequestHandler.handle_request([request_text = None]) .. method:: CGIXMLRPCRequestHandler.handle_request(request_text=None)
Handle a XML-RPC request. If *request_text* is given, it should be the POST Handle a XML-RPC request. If *request_text* is given, it should be the POST
data provided by the HTTP server, otherwise the contents of stdin will be used. data provided by the HTTP server, otherwise the contents of stdin will be used.
...@@ -229,7 +229,7 @@ to HTTP GET requests. Servers can either be free standing, using ...@@ -229,7 +229,7 @@ to HTTP GET requests. Servers can either be free standing, using
:class:`DocCGIXMLRPCRequestHandler`. :class:`DocCGIXMLRPCRequestHandler`.
.. class:: DocXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]]) .. class:: DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True)
Create a new server instance. All parameters have the same meaning as for Create a new server instance. All parameters have the same meaning as for
:class:`SimpleXMLRPCServer`; *requestHandler* defaults to :class:`SimpleXMLRPCServer`; *requestHandler* defaults to
......
:mod:`zipfile` --- Work with ZIP archives :mod:`zipfile` --- Work with ZIP archives
========================================= =========================================
...@@ -49,7 +48,7 @@ The module defines the following items: ...@@ -49,7 +48,7 @@ The module defines the following items:
Class for creating ZIP archives containing Python libraries. Class for creating ZIP archives containing Python libraries.
.. class:: ZipInfo([filename[, date_time]]) .. class:: ZipInfo(filename='NoName', date_time=(1980,1,1,0,0,0))
Class used to represent information about a member of an archive. Instances Class used to represent information about a member of an archive. Instances
of this class are returned by the :meth:`getinfo` and :meth:`infolist` of this class are returned by the :meth:`getinfo` and :meth:`infolist`
...@@ -98,7 +97,7 @@ ZipFile Objects ...@@ -98,7 +97,7 @@ ZipFile Objects
--------------- ---------------
.. class:: ZipFile(file[, mode[, compression[, allowZip64]]]) .. class:: ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=False)
Open a ZIP file, where *file* can be either a path to a file (a string) or a Open a ZIP file, where *file* can be either a path to a file (a string) or a
file-like object. The *mode* parameter should be ``'r'`` to read an existing file-like object. The *mode* parameter should be ``'r'`` to read an existing
...@@ -149,7 +148,7 @@ ZipFile Objects ...@@ -149,7 +148,7 @@ ZipFile Objects
Return a list of archive members by name. Return a list of archive members by name.
.. method:: ZipFile.open(name[, mode[, pwd]]) .. method:: ZipFile.open(name, mode='r', pwd=None)
Extract a member from the archive as a file-like object (ZipExtFile). *name* is Extract a member from the archive as a file-like object (ZipExtFile). *name* is
the name of the file in the archive, or a :class:`ZipInfo` object. The *mode* the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
...@@ -182,7 +181,7 @@ ZipFile Objects ...@@ -182,7 +181,7 @@ ZipFile Objects
ZIP file that contains members with duplicate names. ZIP file that contains members with duplicate names.
.. method:: ZipFile.extract(member[, path[, pwd]]) .. method:: ZipFile.extract(member, path=None, pwd=None)
Extract a member from the archive to the current working directory; *member* Extract a member from the archive to the current working directory; *member*
must be its full name or a :class:`ZipInfo` object). Its file information is must be its full name or a :class:`ZipInfo` object). Its file information is
...@@ -191,7 +190,7 @@ ZipFile Objects ...@@ -191,7 +190,7 @@ ZipFile Objects
*pwd* is the password used for encrypted files. *pwd* is the password used for encrypted files.
.. method:: ZipFile.extractall([path[, members[, pwd]]]) .. method:: ZipFile.extractall(path=None, members=None, pwd=None)
Extract all members from the archive to the current working directory. *path* Extract all members from the archive to the current working directory. *path*
specifies a different directory to extract to. *members* is optional and must specifies a different directory to extract to. *members* is optional and must
...@@ -209,7 +208,7 @@ ZipFile Objects ...@@ -209,7 +208,7 @@ ZipFile Objects
Set *pwd* as default password to extract encrypted files. Set *pwd* as default password to extract encrypted files.
.. method:: ZipFile.read(name[, pwd]) .. method:: ZipFile.read(name, pwd=None)
Return the bytes of the file *name* in the archive. *name* is the name of the Return the bytes of the file *name* in the archive. *name* is the name of the
file in the archive, or a :class:`ZipInfo` object. The archive must be open for file in the archive, or a :class:`ZipInfo` object. The archive must be open for
...@@ -225,7 +224,7 @@ ZipFile Objects ...@@ -225,7 +224,7 @@ ZipFile Objects
:meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`. :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.
.. method:: ZipFile.write(filename[, arcname[, compress_type]]) .. method:: ZipFile.write(filename, arcname=None, compress_type=None)
Write the file named *filename* to the archive, giving it the archive name Write the file named *filename* to the archive, giving it the archive name
*arcname* (by default, this will be the same as *filename*, but without a drive *arcname* (by default, this will be the same as *filename*, but without a drive
...@@ -297,7 +296,7 @@ The :class:`PyZipFile` constructor takes the same parameters as the ...@@ -297,7 +296,7 @@ The :class:`PyZipFile` constructor takes the same parameters as the
:class:`ZipFile` objects. :class:`ZipFile` objects.
.. method:: PyZipFile.writepy(pathname[, basename]) .. method:: PyZipFile.writepy(pathname, basename='')
Search for files :file:`\*.py` and add the corresponding file to the archive. Search for files :file:`\*.py` and add the corresponding file to the archive.
The corresponding file is a :file:`\*.pyo` file if available, else a The corresponding file is a :file:`\*.pyo` file if available, else a
......
:mod:`zipimport` --- Import modules from Zip archives :mod:`zipimport` --- Import modules from Zip archives
===================================================== =====================================================
......
:mod:`zlib` --- Compression compatible with :program:`gzip` :mod:`zlib` --- Compression compatible with :program:`gzip`
=========================================================== ===========================================================
.. module:: zlib .. module:: zlib
:synopsis: Low-level interface to compression and decompression routines compatible with :synopsis: Low-level interface to compression and decompression routines
gzip. compatible with gzip.
For applications that require data compression, the functions in this module For applications that require data compression, the functions in this module
......
...@@ -170,6 +170,25 @@ Assignment of an object to a single target is recursively defined as follows. ...@@ -170,6 +170,25 @@ Assignment of an object to a single target is recursively defined as follows.
perform the assignment, it raises an exception (usually but not necessarily perform the assignment, it raises an exception (usually but not necessarily
:exc:`AttributeError`). :exc:`AttributeError`).
.. _attr-target-note:
Note: If the object is a class instance and the attribute reference occurs on
both sides of the assignment operator, the RHS expression, ``a.x`` can access
either an instance attribute or (if no instance attribute exists) a class
attribute. The LHS target ``a.x`` is always set as an instance attribute,
creating it if necessary. Thus, the two occurrences of ``a.x`` do not
necessarily refer to the same attribute: if the RHS expression refers to a
class attribute, the LHS creates a new instance attribute as the target of the
assignment::
class Cls:
x = 3 # class variable
inst = Cls()
inst.x = inst.x + 1 # writes inst.x as 4 leaving Cls.x as 3
This description does not necessarily apply to descriptor attributes, such as
properties created with :func:`property`.
.. index:: .. index::
pair: subscription; assignment pair: subscription; assignment
object: mutable object: mutable
...@@ -276,16 +295,8 @@ same way as normal assignments. Similarly, with the exception of the possible ...@@ -276,16 +295,8 @@ same way as normal assignments. Similarly, with the exception of the possible
*in-place* behavior, the binary operation performed by augmented assignment is *in-place* behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations. the same as the normal binary operations.
For targets which are attribute references, the initial value is retrieved with For targets which are attribute references, the same :ref:`caveat about class
a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice and instance attributes <attr-target-note>` applies as for regular assignments.
that the two methods do not necessarily refer to the same variable. When
:meth:`getattr` refers to a class variable, :meth:`setattr` still writes to an
instance variable. For example::
class A:
x = 3 # class variable
a = A()
a.x += 1 # writes a.x as 4 leaving A.x as 3
.. _assert: .. _assert:
......
...@@ -20,6 +20,20 @@ Body.enum.converters['loweralpha'] = \ ...@@ -20,6 +20,20 @@ Body.enum.converters['loweralpha'] = \
Body.enum.converters['lowerroman'] = \ Body.enum.converters['lowerroman'] = \
Body.enum.converters['upperroman'] = lambda x: None Body.enum.converters['upperroman'] = lambda x: None
# monkey-patch HTML translator to give versionmodified paragraphs a class
def new_visit_versionmodified(self, node):
self.body.append(self.starttag(node, 'p', CLASS=node['type']))
text = versionlabels[node['type']] % node['version']
if len(node):
text += ': '
else:
text += '.'
self.body.append('<span class="versionmodified">%s</span>' % text)
from sphinx.writers.html import HTMLTranslator
from sphinx.locale import versionlabels
HTMLTranslator.visit_versionmodified = new_visit_versionmodified
def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
issue = utils.unescape(text) issue = utils.unescape(text)
......
...@@ -5,15 +5,6 @@ ...@@ -5,15 +5,6 @@
/* -- main layout ----------------------------------------------------------- */ /* -- main layout ----------------------------------------------------------- */
div.documentwrapper {
float: left;
width: 100%;
}
div.bodywrapper {
margin: 0 0 0 230px;
}
div.clearer { div.clearer {
clear: both; clear: both;
} }
...@@ -338,6 +329,12 @@ dl.glossary dt { ...@@ -338,6 +329,12 @@ dl.glossary dt {
font-style: italic; font-style: italic;
} }
p.deprecated {
background-color: #ffe4e4;
border: 1px solid #f66;
padding: 7px
}
.system-message { .system-message {
background-color: #fda; background-color: #fda;
padding: 5px; padding: 5px;
...@@ -394,7 +391,7 @@ img.math { ...@@ -394,7 +391,7 @@ img.math {
vertical-align: middle; vertical-align: middle;
} }
div.math p { div.body div.math p {
text-align: center; text-align: center;
} }
......
...@@ -242,9 +242,10 @@ re-raise the exception:: ...@@ -242,9 +242,10 @@ re-raise the exception::
User-defined Exceptions User-defined Exceptions
======================= =======================
Programs may name their own exceptions by creating a new exception class. Programs may name their own exceptions by creating a new exception class (see
Exceptions should typically be derived from the :exc:`Exception` class, either :ref:`tut-classes` for more about Python classes). Exceptions should typically
directly or indirectly. For example:: be derived from the :exc:`Exception` class, either directly or indirectly. For
example::
>>> class MyError(Exception): >>> class MyError(Exception):
... def __init__(self, value): ... def __init__(self, value):
......
...@@ -97,7 +97,7 @@ class _RLock(_Verbose): ...@@ -97,7 +97,7 @@ class _RLock(_Verbose):
owner and owner.name, owner and owner.name,
self._count) self._count)
def acquire(self, blocking=1): def acquire(self, blocking=True):
me = current_thread() me = current_thread()
if self._owner is me: if self._owner is me:
self._count = self._count + 1 self._count = self._count + 1
...@@ -289,7 +289,7 @@ class _Semaphore(_Verbose): ...@@ -289,7 +289,7 @@ class _Semaphore(_Verbose):
self._cond = Condition(Lock()) self._cond = Condition(Lock())
self._value = value self._value = value
def acquire(self, blocking=1): def acquire(self, blocking=True):
rc = False rc = False
self._cond.acquire() self._cond.acquire()
while self._value == 0: while self._value == 0:
......
...@@ -70,11 +70,11 @@ def print_tb(tb, limit=None, file=None): ...@@ -70,11 +70,11 @@ def print_tb(tb, limit=None, file=None):
tb = tb.tb_next tb = tb.tb_next
n = n+1 n = n+1
def format_tb(tb, limit = None): def format_tb(tb, limit=None):
"""A shorthand for 'format_list(extract_stack(f, limit)).""" """A shorthand for 'format_list(extract_stack(f, limit))."""
return format_list(extract_tb(tb, limit)) return format_list(extract_tb(tb, limit))
def extract_tb(tb, limit = None): def extract_tb(tb, limit=None):
"""Return list of up to limit pre-processed entries from traceback. """Return list of up to limit pre-processed entries from traceback.
This is useful for alternate formatting of stack traces. If This is useful for alternate formatting of stack traces. If
...@@ -304,7 +304,7 @@ def format_stack(f=None, limit=None): ...@@ -304,7 +304,7 @@ def format_stack(f=None, limit=None):
f = sys.exc_info()[2].tb_frame.f_back f = sys.exc_info()[2].tb_frame.f_back
return format_list(extract_stack(f, limit)) return format_list(extract_stack(f, limit))
def extract_stack(f=None, limit = None): def extract_stack(f=None, limit=None):
"""Extract the raw traceback from the current stack frame. """Extract the raw traceback from the current stack frame.
The return value has the same format as for extract_tb(). The The return value has the same format as for extract_tb(). The
......
...@@ -329,7 +329,7 @@ def unquote(string, encoding='utf-8', errors='replace'): ...@@ -329,7 +329,7 @@ def unquote(string, encoding='utf-8', errors='replace'):
res[-1] = b''.join(pct_sequence).decode(encoding, errors) res[-1] = b''.join(pct_sequence).decode(encoding, errors)
return ''.join(res) return ''.join(res)
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): def parse_qs(qs, keep_blank_values=False, strict_parsing=False):
"""Parse a query given as a string argument. """Parse a query given as a string argument.
Arguments: Arguments:
...@@ -355,7 +355,7 @@ def parse_qs(qs, keep_blank_values=0, strict_parsing=0): ...@@ -355,7 +355,7 @@ def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
dict[name] = [value] dict[name] = [value]
return dict return dict
def parse_qsl(qs, keep_blank_values=0, strict_parsing=0): def parse_qsl(qs, keep_blank_values=False, strict_parsing=False):
"""Parse a query given as a string argument. """Parse a query given as a string argument.
Arguments: Arguments:
...@@ -509,7 +509,7 @@ def quote_from_bytes(bs, safe='/'): ...@@ -509,7 +509,7 @@ def quote_from_bytes(bs, safe='/'):
_safe_quoters[cachekey] = quoter _safe_quoters[cachekey] = quoter
return ''.join([quoter[char] for char in bs]) return ''.join([quoter[char] for char in bs])
def urlencode(query, doseq=0): def urlencode(query, doseq=False):
"""Encode a sequence of two-element tuples or dictionary into a URL query string. """Encode a sequence of two-element tuples or dictionary into a URL query string.
If any values in the query arg are sequences and doseq is true, each If any values in the query arg are sequences and doseq is true, each
......
...@@ -80,7 +80,7 @@ def encode(in_file, out_file, name=None, mode=None): ...@@ -80,7 +80,7 @@ def encode(in_file, out_file, name=None, mode=None):
out_file.write(b' \nend\n') out_file.write(b' \nend\n')
def decode(in_file, out_file=None, mode=None, quiet=0): def decode(in_file, out_file=None, mode=None, quiet=False):
"""Decode uuencoded file""" """Decode uuencoded file"""
# #
# Open the input file, if needed. # Open the input file, if needed.
......
...@@ -29,7 +29,7 @@ def formatwarning(message, category, filename, lineno, line=None): ...@@ -29,7 +29,7 @@ def formatwarning(message, category, filename, lineno, line=None):
return s return s
def filterwarnings(action, message="", category=Warning, module="", lineno=0, def filterwarnings(action, message="", category=Warning, module="", lineno=0,
append=0): append=False):
"""Insert an entry into the list of warnings filters (at the front). """Insert an entry into the list of warnings filters (at the front).
Use assertions to check that all arguments have the right type.""" Use assertions to check that all arguments have the right type."""
...@@ -49,7 +49,7 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0, ...@@ -49,7 +49,7 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0,
else: else:
filters.insert(0, item) filters.insert(0, item)
def simplefilter(action, category=Warning, lineno=0, append=0): def simplefilter(action, category=Warning, lineno=0, append=False):
"""Insert a simple entry into the list of warnings filters (at the front). """Insert a simple entry into the list of warnings filters (at the front).
A simple filter matches all modules and messages. A simple filter matches all modules and messages.
......
...@@ -67,7 +67,7 @@ def application_uri(environ): ...@@ -67,7 +67,7 @@ def application_uri(environ):
url += quote(environ.get('SCRIPT_NAME') or '/') url += quote(environ.get('SCRIPT_NAME') or '/')
return url return url
def request_uri(environ, include_query=1): def request_uri(environ, include_query=True):
"""Return the full request URI, optionally including the query string""" """Return the full request URI, optionally including the query string"""
url = application_uri(environ) url = application_uri(environ)
from urllib.parse import quote from urllib.parse import quote
......
...@@ -36,7 +36,7 @@ def _good_enough(dom, features): ...@@ -36,7 +36,7 @@ def _good_enough(dom, features):
return 0 return 0
return 1 return 1
def getDOMImplementation(name = None, features = ()): def getDOMImplementation(name=None, features=()):
"""getDOMImplementation(name = None, features = ()) -> DOM implementation. """getDOMImplementation(name = None, features = ()) -> DOM implementation.
Return a suitable DOM implementation. The name is either Return a suitable DOM implementation. The name is either
......
...@@ -43,7 +43,7 @@ class Node(xml.dom.Node): ...@@ -43,7 +43,7 @@ class Node(xml.dom.Node):
def __bool__(self): def __bool__(self):
return True return True
def toxml(self, encoding = None): def toxml(self, encoding=None):
return self.toprettyxml("", "", encoding) return self.toprettyxml("", "", encoding)
def toprettyxml(self, indent="\t", newl="\n", encoding=None): def toprettyxml(self, indent="\t", newl="\n", encoding=None):
......
...@@ -268,7 +268,7 @@ class XMLFilterBase(xmlreader.XMLReader): ...@@ -268,7 +268,7 @@ class XMLFilterBase(xmlreader.XMLReader):
# --- Utility functions # --- Utility functions
def prepare_input_source(source, base = ""): def prepare_input_source(source, base=""):
"""This function takes an InputSource and an optional base URL and """This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading.""" returns a fully resolved InputSource object ready for reading."""
......
...@@ -480,7 +480,7 @@ class Marshaller: ...@@ -480,7 +480,7 @@ class Marshaller:
# by the way, if you don't understand what's going on in here, # by the way, if you don't understand what's going on in here,
# that's perfectly ok. # that's perfectly ok.
def __init__(self, encoding=None, allow_none=0): def __init__(self, encoding=None, allow_none=False):
self.memo = {} self.memo = {}
self.data = None self.data = None
self.encoding = encoding self.encoding = encoding
...@@ -653,7 +653,7 @@ class Unmarshaller: ...@@ -653,7 +653,7 @@ class Unmarshaller:
# and again, if you don't understand what's going on in here, # and again, if you don't understand what's going on in here,
# that's perfectly ok. # that's perfectly ok.
def __init__(self, use_datetime=0): def __init__(self, use_datetime=False):
self._type = None self._type = None
self._stack = [] self._stack = []
self._marks = [] self._marks = []
...@@ -886,7 +886,7 @@ FastMarshaller = FastParser = FastUnmarshaller = None ...@@ -886,7 +886,7 @@ FastMarshaller = FastParser = FastUnmarshaller = None
# #
# return A (parser, unmarshaller) tuple. # return A (parser, unmarshaller) tuple.
def getparser(use_datetime=0): def getparser(use_datetime=False):
"""getparser() -> parser, unmarshaller """getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it Create an instance of the fastest available parser, and attach it
...@@ -923,7 +923,7 @@ def getparser(use_datetime=0): ...@@ -923,7 +923,7 @@ def getparser(use_datetime=0):
# @return A string containing marshalled data. # @return A string containing marshalled data.
def dumps(params, methodname=None, methodresponse=None, encoding=None, def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0): allow_none=False):
"""data [,options] -> marshalled data """data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC Convert an argument tuple or a Fault instance to an XML-RPC
...@@ -999,7 +999,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None, ...@@ -999,7 +999,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None,
# (None if not present). # (None if not present).
# @see Fault # @see Fault
def loads(data, use_datetime=0): def loads(data, use_datetime=False):
"""data -> unmarshalled data, method name """data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method Convert an XML-RPC packet to unmarshalled data plus a method
...@@ -1040,7 +1040,7 @@ class Transport: ...@@ -1040,7 +1040,7 @@ class Transport:
# client identifier (may be overridden) # client identifier (may be overridden)
user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__ user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
def __init__(self, use_datetime=0): def __init__(self, use_datetime=False):
self._use_datetime = use_datetime self._use_datetime = use_datetime
## ##
...@@ -1052,7 +1052,7 @@ class Transport: ...@@ -1052,7 +1052,7 @@ class Transport:
# @param verbose Debugging flag. # @param verbose Debugging flag.
# @return Parsed response. # @return Parsed response.
def request(self, host, handler, request_body, verbose=0): def request(self, host, handler, request_body, verbose=False):
# issue XML-RPC request # issue XML-RPC request
http_conn = self.send_request(host, handler, request_body, verbose) http_conn = self.send_request(host, handler, request_body, verbose)
...@@ -1234,8 +1234,8 @@ class ServerProxy: ...@@ -1234,8 +1234,8 @@ class ServerProxy:
the given encoding. the given encoding.
""" """
def __init__(self, uri, transport=None, encoding=None, verbose=0, def __init__(self, uri, transport=None, encoding=None, verbose=False,
allow_none=0, use_datetime=0): allow_none=False, use_datetime=False):
# establish a "logical" server connection # establish a "logical" server connection
# get the url # get the url
......
...@@ -201,7 +201,7 @@ class SimpleXMLRPCDispatcher: ...@@ -201,7 +201,7 @@ class SimpleXMLRPCDispatcher:
self.instance = instance self.instance = instance
self.allow_dotted_names = allow_dotted_names self.allow_dotted_names = allow_dotted_names
def register_function(self, function, name = None): def register_function(self, function, name=None):
"""Registers a function to respond to XML-RPC requests. """Registers a function to respond to XML-RPC requests.
The optional name argument can be used to set a Unicode name The optional name argument can be used to set a Unicode name
...@@ -578,7 +578,7 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): ...@@ -578,7 +578,7 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):
sys.stdout.buffer.write(response) sys.stdout.buffer.write(response)
sys.stdout.buffer.flush() sys.stdout.buffer.flush()
def handle_request(self, request_text = None): def handle_request(self, request_text=None):
"""Handle a single XML-RPC request passed through a CGI post method. """Handle a single XML-RPC request passed through a CGI post method.
If no XML data is given then it is read from stdin. The resulting If no XML data is given then it is read from stdin. The resulting
...@@ -837,7 +837,7 @@ class DocXMLRPCServer( SimpleXMLRPCServer, ...@@ -837,7 +837,7 @@ class DocXMLRPCServer( SimpleXMLRPCServer,
""" """
def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler, def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
logRequests=1, allow_none=False, encoding=None, logRequests=True, allow_none=False, encoding=None,
bind_and_activate=True): bind_and_activate=True):
SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests, SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
allow_none, encoding, bind_and_activate) allow_none, encoding, bind_and_activate)
......
...@@ -1255,7 +1255,7 @@ class ZipFile: ...@@ -1255,7 +1255,7 @@ class ZipFile:
class PyZipFile(ZipFile): class PyZipFile(ZipFile):
"""Class to create ZIP archives with Python library files and packages.""" """Class to create ZIP archives with Python library files and packages."""
def writepy(self, pathname, basename = ""): def writepy(self, pathname, basename=""):
"""Add all files from "pathname" to the ZIP archive. """Add all files from "pathname" to the ZIP archive.
If pathname is a package directory, search the directory and If pathname is a package directory, search the directory and
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment