to reading the Unicode character tables, available at
<http://www.cs.tut.fi/~jkorpela/unicode/guide.html>.
-Two other good introductory articles were written by Joel Spolsky
-<http://www.joelonsoftware.com/articles/Unicode.html> and Jason Orendorff
-<http://www.jorendorff.com/articles/unicode/>. If this introduction didn't make
-things clear to you, you should try reading one of these alternate articles
-before continuing.
+Another good introductory article was written by Joel Spolsky
+<http://www.joelonsoftware.com/articles/Unicode.html>.
+If this introduction didn't make things clear to you, you should try reading this
+alternate article before continuing.
+
+.. Jason Orendorff XXX http://www.jorendorff.com/articles/unicode/ is broken
Wikipedia entries are often helpful; see the entries for "character encoding"
<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
action="store_false", dest="verbose",
help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
- metavar="FILE", help="write output to FILE"),
+ metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode",
default="intermediate",
help="interaction mode: novice, intermediate, "
from optparse import OptionParser, SUPPRESS_HELP
- parser = OptionParser()
- parser.add_option("-h", "--help", action="help"),
+ # usually, a help option is added automatically, but that can
+ # 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",
help="Be moderately verbose")
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)
If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, it
:file:`pdb.py` can also be invoked as a script to debug other scripts. For
example::
- python -m pdb myscript.py
+ python3 -m pdb myscript.py
When invoked as a script, pdb will automatically enter post-mortem debugging if
the program being debugged exits abnormally. After post-mortem debugging (or
class HistoryConsole(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>",
histfile=os.path.expanduser("~/.console-history")):
- code.InteractiveConsole.__init__(self)
+ code.InteractiveConsole.__init__(self, locals, filename)
self.init_history(histfile)
def init_history(self, histfile):
-
.. _someos:
**********************************
The modules described in this chapter provide interfaces to operating system
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
-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::
-
:mod:`spwd` --- The shadow password database
============================================
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.
-It defines the following items:
+The following functions are defined:
.. function:: getspnam(name)
-
:mod:`ssl` --- SSL wrapper for socket objects
-====================================================================
+=============================================
.. module:: ssl
:synopsis: SSL wrapper for socket objects
.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
-This module provides access to Transport Layer Security (often known
-as "Secure Sockets Layer") encryption and peer authentication
-facilities for network sockets, both client-side and server-side.
-This module uses the OpenSSL library. It is available on all modern
-Unix systems, Windows, Mac OS X, and probably additional
-platforms, as long as OpenSSL is installed on that platform.
+This module provides access to Transport Layer Security (often known as "Secure
+Sockets Layer") encryption and peer authentication facilities for network
+sockets, both client-side and server-side. This module uses the OpenSSL
+library. It is available on all modern Unix systems, Windows, Mac OS X, and
+probably additional platforms, as long as OpenSSL is installed on that platform.
.. note::
- Some behavior may be platform dependent, since calls are made to the operating
- system socket APIs. The installed version of OpenSSL may also cause
- variations in behavior.
+ Some behavior may be platform dependent, since calls are made to the
+ operating system socket APIs. The installed version of OpenSSL may also
+ cause variations in behavior.
-This section documents the objects and functions in the ``ssl`` module;
-for more general information about TLS, SSL, and certificates, the
-reader is referred to the documents in the "See Also" section at
-the bottom.
+This section documents the objects and functions in the ``ssl`` module; for more
+general information about TLS, SSL, and certificates, the reader is referred to
+the documents in the "See Also" section at the bottom.
-This module provides a class, :class:`ssl.SSLSocket`, which is
-derived from the :class:`socket.socket` type, and provides
-a socket-like wrapper that also encrypts and decrypts the data
-going over the socket with SSL. It supports additional
-:meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`,
-to retrieve the certificate of the other side of the connection, and
-a method, :meth:`cipher`, to retrieve the cipher being used for the
-secure connection.
+This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
+:class:`socket.socket` type, and provides a socket-like wrapper that also
+encrypts and decrypts the data going over the socket with SSL. It supports
+additional :meth:`read` and :meth:`write` methods, along with a method,
+:meth:`getpeercert`, to retrieve the certificate of the other side of the
+connection, and a method, :meth:`cipher`, to retrieve the cipher being used for
+the secure connection.
Functions, Constants, and Exceptions
------------------------------------
.. exception:: SSLError
Raised to signal an error from the underlying SSL implementation. This
- signifies some problem in the higher-level
- encryption and authentication layer that's superimposed on the underlying
- network connection. This error is a subtype of :exc:`socket.error`, which
- in turn is a subtype of :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)
-
- Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype
- of :class:`socket.socket`, which wraps the underlying socket in an SSL context.
- For client-side sockets, the context construction is lazy; if the underlying socket isn't
- connected yet, the context construction will be performed after :meth:`connect` is called
- on the socket. For server-side sockets, if the socket has no remote peer, it is assumed
- to be a listening socket, and the server-side SSL wrapping is 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`
- for more information on how the certificate is stored in the ``certfile``.
-
- Often the private key is stored
- 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.
- If the private key is stored in the ``certfile``, it should come before the first certificate
- in the certificate chain::
+ signifies some problem in the higher-level encryption and authentication
+ layer that's superimposed on the underlying network connection. This error
+ is a subtype of :exc:`socket.error`, which in turn is a subtype of
+ :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)
+
+ Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
+ of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
+ the underlying socket in an SSL context. For client-side sockets, the
+ context construction is lazy; if the underlying socket isn't connected yet,
+ the context construction will be performed after :meth:`connect` is called on
+ the socket. For server-side sockets, if the socket has no remote peer, it is
+ assumed to be a listening socket, and the server-side SSL wrapping is
+ 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` for more
+ information on how the certificate is stored in the ``certfile``.
+
+ Often the private key is stored 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. If the private key
+ is stored in the ``certfile``, it should come before the first certificate in
+ the certificate chain::
-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
- The parameter ``server_side`` is a boolean which identifies whether server-side or client-side
- behavior is desired from this socket.
-
- The parameter ``cert_reqs`` specifies whether a certificate is
- required from the other side of the connection, and whether it will
- be validated if provided. It must be one of the three values
- :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required,
- but validated if provided), or :const:`CERT_REQUIRED` (required and
- validated). If the value of this parameter is not :const:`CERT_NONE`, then
- the ``ca_certs`` parameter must point to a file of CA certificates.
-
- The ``ca_certs`` file contains a set of concatenated "certification authority" certificates,
- which are used to validate certificates passed from the other end of the connection.
- See the discussion of :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
- must adapt to the server's choice. Most of the versions are not interoperable
- with the other versions. If not specified, for client-side operation, the
- default SSL version is SSLv3; for server-side operation, SSLv23. These
- version selections provide the most compatibility with other versions.
-
- Here's a table showing which versions in a client (down the side)
- can connect to which versions in a server (along the top):
+ The parameter ``server_side`` is a boolean which identifies whether
+ server-side or client-side behavior is desired from this socket.
+
+ The parameter ``cert_reqs`` specifies whether a certificate is required from
+ the other side of the connection, and whether it will be validated if
+ provided. It must be one of the three values :const:`CERT_NONE`
+ (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
+ if provided), or :const:`CERT_REQUIRED` (required and validated). If the
+ value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
+ parameter must point to a file of CA certificates.
+
+ The ``ca_certs`` file contains a set of concatenated "certification
+ authority" certificates, which are used to validate certificates passed from
+ the other end of the connection. See the discussion of
+ :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 must adapt to the server's choice. Most of the versions are not
+ interoperable with the other versions. If not specified, for client-side
+ operation, the default SSL version is SSLv3; for server-side operation,
+ SSLv23. These version selections provide the most compatibility with other
+ versions.
+
+ 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::
*TLSv1* no no yes yes
======================== ========= ========= ========== =========
- In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4),
- an SSLv2 client could not connect to an SSLv23 server.
+ In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), an
+ SSLv2 client could not connect to an SSLv23 server.
The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
handshake automatically after doing a :meth:`socket.connect`, or whether the
- application program will call it explicitly, by invoking the :meth:`SSLSocket.do_handshake`
- method. Calling :meth:`SSLSocket.do_handshake` explicitly gives the program control over
- the blocking behavior of the socket I/O involved in the handshake.
+ application program will call it explicitly, by invoking the
+ :meth:`SSLSocket.do_handshake` method. Calling
+ :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`
- method should signal unexpected EOF from the other end of the connection. If specified
- as :const:`True` (the default), it returns a normal EOF in response to unexpected
- EOF errors raised from the underlying socket; if :const:`False`, it will raise
- the exceptions back to the caller.
+ The parameter ``suppress_ragged_eofs`` specifies how the
+ :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
+ of the connection. If specified as :const:`True` (the default), it returns a
+ normal EOF in response to unexpected EOF errors raised from the underlying
+ socket; if :const:`False`, it will raise the exceptions back to the caller.
.. function:: RAND_status()
- Returns True if the SSL pseudo-random number generator has been
- seeded with 'enough' randomness, and False otherwise. You can use
- :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness
- of the pseudo-random number generator.
+ Returns True if the SSL pseudo-random number generator has been seeded with
+ 'enough' randomness, and False otherwise. You can use :func:`ssl.RAND_egd`
+ and :func:`ssl.RAND_add` to increase the randomness of the pseudo-random
+ number generator.
.. function:: RAND_egd(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
- 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator
- to increase the security of generated secret keys. This is typically only
- necessary on systems without better sources of randomness.
+ is the pathname of a socket connection open to it, this will read 256 bytes
+ of randomness from the socket, and add it to the SSL pseudo-random number
+ generator to increase the security of generated secret keys. This is
+ typically only necessary on systems without better sources of randomness.
- See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for
- sources of entropy-gathering daemons.
+ See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
+ of entropy-gathering daemons.
.. function:: RAND_add(bytes, entropy)
- Mixes the given ``bytes`` into the SSL pseudo-random number generator.
- The parameter ``entropy`` (a float) is a lower bound on the entropy
- contained in string (so you can always use :const:`0.0`).
- See :rfc:`1750` for more information on sources of entropy.
+ Mixes the given ``bytes`` into the SSL pseudo-random number generator. The
+ parameter ``entropy`` (a float) is a lower bound on the entropy contained in
+ string (so you can always use :const:`0.0`). See :rfc:`1750` for more
+ information on sources of entropy.
.. function:: cert_time_to_seconds(timestring)
- Returns a floating-point value containing a normal seconds-after-the-epoch time
- value, given the time-string representing the "notBefore" or "notAfter" date
- from a certificate.
+ Returns a floating-point value containing a normal seconds-after-the-epoch
+ time value, given the time-string representing the "notBefore" or "notAfter"
+ date from a certificate.
Here's an example::
'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
- (*hostname*, *port-number*) pair, fetches the server's certificate,
- and returns it as a PEM-encoded string. If ``ssl_version`` is
- specified, uses that version of the SSL protocol to attempt to
- connect to the server. If ``ca_certs`` is specified, it should be
- a file containing a list of root certificates, the same format as
- used for the same parameter in :func:`wrap_socket`. The call will
- attempt to validate the server certificate against that set of root
+ Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
+ *port-number*) pair, fetches the server's certificate, and returns it as a
+ PEM-encoded string. If ``ssl_version`` is specified, uses that version of
+ the SSL protocol to attempt to connect to the server. If ``ca_certs`` is
+ specified, it should be a file containing a list of root certificates, the
+ same format as used for the same parameter in :func:`wrap_socket`. The call
+ will attempt to validate the server certificate against that set of root
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
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
- sequence of bytes for that same certificate.
+ Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
+ bytes for that same certificate.
.. data:: CERT_NONE
- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
- when no certificates will be required or validated from the other
- side of the socket connection.
+ Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
+ certificates will be required or validated from the other side of the socket
+ connection.
.. data:: CERT_OPTIONAL
- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
- when no certificates will be required from the other side of the
- socket connection, but if they are provided, will be validated.
- Note that use of this setting requires a valid certificate
- validation file also be passed as a value of the ``ca_certs``
- parameter.
+ Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when no
+ certificates will be required from the other side of the socket connection,
+ but if they are provided, will be validated. Note that use of this setting
+ requires a valid certificate validation file also be passed as a value of the
+ ``ca_certs`` parameter.
.. data:: CERT_REQUIRED
- Value to pass to the ``cert_reqs`` parameter to :func:`sslobject`
- when certificates will be required from the other side of the
- socket connection. Note that use of this setting requires a valid certificate
- validation file also be passed as a value of the ``ca_certs``
- parameter.
+ Value to pass to the ``cert_reqs`` parameter to :func:`sslobject` when
+ certificates will be required from the other side of the socket connection.
+ Note that use of this setting requires a valid certificate validation file
+ also be passed as a value of the ``ca_certs`` parameter.
.. data:: PROTOCOL_SSLv2
.. data:: PROTOCOL_SSLv23
- Selects SSL version 2 or 3 as the channel encryption protocol.
- This is a setting to use with servers for maximum compatibility
- with the other end of an SSL connection, but it may cause the
- specific ciphers chosen for the encryption to be of fairly low
- quality.
+ Selects SSL version 2 or 3 as the channel encryption protocol. This is a
+ setting to use with servers for maximum compatibility with the other end of
+ an SSL connection, but it may cause the specific ciphers chosen for the
+ encryption to be of fairly low quality.
.. data:: PROTOCOL_SSLv3
- Selects SSL version 3 as the channel encryption protocol.
- For clients, this is the maximally compatible SSL variant.
+ Selects SSL version 3 as the channel encryption protocol. For clients, this
+ is the maximally compatible SSL variant.
.. data:: PROTOCOL_TLSv1
- Selects TLS version 1 as the channel encryption protocol. This is
- the most modern version, and probably the best choice for maximum
- protection, if both sides can speak it.
+ Selects TLS version 1 as the channel encryption protocol. This is the most
+ modern version, and probably the best choice for maximum protection, if both
+ sides can speak it.
SSLSocket Objects
.. method:: SSLSocket.read(nbytes=1024, buffer=None)
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
- the minimum of the size of the buffer and ``nbytes``, if that is specified.
- If no buffer is specified, an immutable buffer is allocated and returned
- with the data read from the socket.
+ If the ``buffer`` is specified, it will attempt to read into the buffer the
+ minimum of the size of the buffer and ``nbytes``, if that is specified. If
+ no buffer is specified, an immutable buffer is allocated and returned with
+ the data read from the socket.
.. method:: SSLSocket.write(data)
- Writes the ``data`` to the other side of the connection, using the
- SSL channel to encrypt. Returns the number of bytes written.
+ Writes the ``data`` to the other side of the connection, using the SSL
+ channel to encrypt. Returns the number of bytes written.
.. method:: SSLSocket.do_handshake()
- Performs the SSL setup handshake. If the socket is non-blocking,
- this method may raise :exc:`SSLError` with the value of the exception
- instance's ``args[0]``
- being either :const:`SSL_ERROR_WANT_READ` or
- :const:`SSL_ERROR_WANT_WRITE`, and should be called again until
- it stops raising those exceptions. Here's an example of how to do
- that::
+ Performs the SSL setup handshake. If the socket is non-blocking, this method
+ may raise :exc:`SSLError` with the value of the exception instance's
+ ``args[0]`` being either :const:`SSL_ERROR_WANT_READ` or
+ :const:`SSL_ERROR_WANT_WRITE`, and should be called again until it stops
+ raising those exceptions. Here's an example of how to do that::
while True:
try:
.. method:: SSLSocket.unwrap()
- Performs the SSL shutdown handshake, which removes the TLS layer
- from the underlying socket, and returns the underlying socket
- object. This can be used to go from encrypted operation over a
- connection to unencrypted. The returned socket should always be
- used for further communication with the other side of the
- connection, rather than the original socket
+ Performs the SSL shutdown handshake, which removes the TLS layer from the
+ underlying socket, and returns the underlying socket object. This can be
+ used to go from encrypted operation over a connection to unencrypted. The
+ returned socket should always be used for further communication with the
+ other side of the connection, rather than the original socket
.. method:: SSLSocket.getpeercert(binary_form=False)
- If there is no certificate for the peer on the other end of the
- connection, returns ``None``.
-
- If the parameter ``binary_form`` is :const:`False`, and a
- certificate was received from the peer, this method returns a
- :class:`dict` instance. If the certificate was not validated, the
- dict is empty. If the certificate was validated, it returns a dict
- with the keys ``subject`` (the principal for which the certificate
- was issued), and ``notAfter`` (the time after which the certificate
- should not be trusted). The certificate was already validated, so
- the ``notBefore`` and ``issuer`` fields are not returned. If a
- certificate contains an instance of the *Subject Alternative Name*
- extension (see :rfc:`3280`), there will also be a
- ``subjectAltName`` key in the dictionary.
+ If there is no certificate for the peer on the other end of the connection,
+ returns ``None``.
+
+ If the parameter ``binary_form`` is :const:`False`, and a certificate was
+ received from the peer, this method returns a :class:`dict` instance. If the
+ certificate was not validated, the dict is empty. If the certificate was
+ validated, it returns a dict with the keys ``subject`` (the principal for
+ which the certificate was issued), and ``notAfter`` (the time after which the
+ certificate should not be trusted). The certificate was already validated,
+ so the ``notBefore`` and ``issuer`` fields are not returned. If a
+ certificate contains an instance of the *Subject Alternative Name* extension
+ (see :rfc:`3280`), there will also be a ``subjectAltName`` key in the
+ dictionary.
The "subject" field is a tuple containing the sequence of relative
- distinguished names (RDNs) given in the certificate's data
- structure for the principal, and each RDN is a sequence of
- name-value pairs::
+ distinguished names (RDNs) given in the certificate's data structure for the
+ principal, and each RDN is a sequence of name-value pairs::
{'notAfter': 'Feb 16 16:54:50 2013 GMT',
'subject': ((('countryName', 'US'),),
(('organizationalUnitName', 'SSL'),),
(('commonName', 'somemachine.python.org'),))}
- If the ``binary_form`` parameter is :const:`True`, and a
- certificate was provided, this method returns the DER-encoded form
- of the entire certificate as a sequence of bytes, or :const:`None` if the
- peer did not provide a certificate. This return
- value is independent of validation; if validation was required
- (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
+ If the ``binary_form`` parameter is :const:`True`, and a certificate was
+ provided, this method returns the DER-encoded form of the entire certificate
+ as a sequence of bytes, or :const:`None` if the peer did not provide a
+ certificate. This return value is independent of validation; if validation
+ was required (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have
been validated, but if :const:`CERT_NONE` was used to establish the
connection, the certificate, if present, will not have been validated.
.. method:: SSLSocket.cipher()
- Returns a three-value tuple containing the name of the cipher being
- used, the version of the SSL protocol that defines its use, and the
- number of secret bits being used. If no connection has been
- established, returns ``None``.
+ Returns a three-value tuple containing the name of the cipher being used, the
+ version of the SSL protocol that defines its use, and the number of secret
+ bits being used. If no connection has been established, returns ``None``.
.. method:: SSLSocket.unwrap()
- Performs the SSL shutdown handshake, which removes the TLS layer
- from the underlying socket, and returns the underlying socket
- object. This can be used to go from encrypted operation over a
- connection to unencrypted. The returned socket should always be
- used for further communication with the other side of the
- connection, rather than the original socket
+ Performs the SSL shutdown handshake, which removes the TLS layer from the
+ underlying socket, and returns the underlying socket object. This can be
+ used to go from encrypted operation over a connection to unencrypted. The
+ returned socket should always be used for further communication with the
+ other side of the connection, rather than the original socket.
.. index:: single: certificates
Certificates
------------
-Certificates in general are part of a public-key / private-key system. In this system, each *principal*,
-(which may be a machine, or a person, or an organization) is assigned a unique two-part encryption key.
-One part of the key is public, and is called the *public key*; the other part is kept secret, and is 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 **only** with the other part.
-
-A certificate contains information about two principals. It contains
-the name of a *subject*, and the subject's public key. It also
-contains a statement by a second principal, the *issuer*, that the
-subject is who he claims to be, and that this is indeed the subject's
-public key. The issuer's statement is signed with the issuer's
-private key, which only the issuer knows. However, anyone can verify
-the issuer's statement by finding the issuer's public key, decrypting
-the statement with it, and comparing it to the other information in
-the certificate. The certificate also contains information about the
-time period over which it is valid. This is expressed as two fields,
-called "notBefore" and "notAfter".
-
-In the Python use of certificates, a client or server
-can use a certificate to prove who they are. The other
-side of a network connection can also be required to produce a certificate,
-and that certificate can be validated to the satisfaction
-of the client or server that requires such validation.
-The connection attempt can be set to raise an exception if
-the validation fails. Validation is done
-automatically, by the underlying OpenSSL framework; the
-application need not concern itself with its mechanics.
-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 and a footer line::
+Certificates in general are part of a public-key / private-key system. In this
+system, each *principal*, (which may be a machine, or a person, or an
+organization) is assigned a unique two-part encryption key. One part of the key
+is public, and is called the *public key*; the other part is kept secret, and is
+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
+**only** with the other part.
+
+A certificate contains information about two principals. It contains the name
+of a *subject*, and the subject's public key. It also contains a statement by a
+second principal, the *issuer*, that the subject is who he claims to be, and
+that this is indeed the subject's public key. The issuer's statement is signed
+with the issuer's private key, which only the issuer knows. However, anyone can
+verify the issuer's statement by finding the issuer's public key, decrypting the
+statement with it, and comparing it to the other information in the certificate.
+The certificate also contains information about the time period over which it is
+valid. This is expressed as two fields, called "notBefore" and "notAfter".
+
+In the Python use of certificates, a client or server can use a certificate to
+prove who they are. The other side of a network connection can also be required
+to produce a certificate, and that certificate can be validated to the
+satisfaction of the client or server that requires such validation. The
+connection attempt can be set to raise an exception if the validation fails.
+Validation is done automatically, by the underlying OpenSSL framework; the
+application need not concern itself with its mechanics. 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
+and a footer line::
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----
-The Python files which contain certificates can contain a sequence
-of certificates, sometimes called a *certificate chain*. This chain
-should start with the specific certificate for the principal who "is"
-the client or server, and then the certificate for the issuer of that
-certificate, and then the certificate for the issuer of *that* certificate,
-and so on up the chain till you get to a certificate which is *self-signed*,
-that is, a certificate which has the same subject and issuer,
-sometimes called a *root certificate*. The certificates should just
-be concatenated together in the certificate file. For example, suppose
-we had a three certificate chain, from our server certificate to the
-certificate of the certification authority that signed our server certificate,
-to the root certificate of the agency which issued the certification authority's
-certificate::
+The Python files which contain certificates can contain a sequence of
+certificates, sometimes called a *certificate chain*. This chain should start
+with the specific certificate for the principal who "is" the client or server,
+and then the certificate for the issuer of that certificate, and then the
+certificate for the issuer of *that* certificate, and so on up the chain till
+you get to a certificate which is *self-signed*, that is, a certificate which
+has the same subject and issuer, sometimes called a *root certificate*. The
+certificates should just be concatenated together in the certificate file. For
+example, suppose we had a three certificate chain, from our server certificate
+to the certificate of the certification authority that signed our server
+certificate, to the root certificate of the agency which issued the
+certification authority's certificate::
-----BEGIN CERTIFICATE-----
... (certificate for your server)...
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
-chains for each issuer you are willing to trust. Again, this file just
-contains these chains concatenated together. For validation, Python will
-use the first chain it finds in the file which matches.
-Some "standard" root certificates are available from various certification
-authorities:
-`CACert.org <http://www.cacert.org/index.php?id=3>`_,
-`Thawte <http://www.thawte.com/roots/>`_,
-`Verisign <http://www.verisign.com/support/roots.html>`_,
-`Positive SSL <http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_ (used by python.org),
-`Equifax and GeoTrust <http://www.geotrust.com/resources/root_certificates/index.asp>`_.
-
-In general, if you are using
-SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file;
-you only need the root certificates, and the remote peer is supposed to
-furnish the other certificates necessary to chain from its certificate to
-a root certificate.
-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 many ways of acquiring appropriate certificates,
-such as buying one from a certification authority. Another common
-practice is to generate a self-signed certificate. The simplest
-way to do this is with the OpenSSL package, using something like
-the following::
+chains for each issuer you are willing to trust. Again, this file just contains
+these chains concatenated together. For validation, Python will use the first
+chain it finds in the file which matches. Some "standard" root certificates are
+available from various certification authorities: `CACert.org
+<http://www.cacert.org/index.php?id=3>`_, `Thawte
+<http://www.thawte.com/roots/>`_, `Verisign
+<http://www.verisign.com/support/roots.html>`_, `Positive SSL
+<http://www.PositiveSSL.com/ssl-certificate-support/cert_installation/UTN-USERFirst-Hardware.crt>`_
+(used by python.org), `Equifax and GeoTrust
+<http://www.geotrust.com/resources/root_certificates/index.asp>`_.
+
+In general, if you are using SSL3 or TLS1, you don't need to put the full chain
+in your "CA certs" file; you only need the root certificates, and the remote
+peer is supposed to furnish the other certificates necessary to chain from its
+certificate to a root certificate. 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
+many ways of acquiring appropriate certificates, such as buying one from a
+certification authority. Another common 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
Generating a 1024 bit RSA private key
Email Address []:ops@myserver.mygroup.myorganization.com
%
-The disadvantage of a self-signed certificate is that it is its
-own root certificate, and no one else will have it in their cache
-of known (and trusted) root certificates.
+The disadvantage of a self-signed certificate is that it is its own root
+certificate, and no one else will have it in their cache of known (and trusted)
+root certificates.
Examples
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:
import ssl
Client-side operation
^^^^^^^^^^^^^^^^^^^^^
-This example connects to an SSL server, prints the server's address and certificate,
-sends some bytes, and reads part of the response::
+This example connects to an SSL server, prints the server's address and
+certificate, sends some bytes, and reads part of the response::
import socket, ssl, pprint
# note that closing the SSLSocket will also close the underlying socket
ssl_sock.close()
-As of September 6, 2007, the certificate printed by this program
-looked like this::
+As of September 6, 2007, the certificate printed by this program looked like
+this::
{'notAfter': 'May 8 23:59:59 2009 GMT',
'subject': ((('serialNumber', '2497886'),),
Server-side operation
^^^^^^^^^^^^^^^^^^^^^
-For server operation, typically you'd need to have a server certificate, and private key, each in a file.
-You'd open a socket, bind it to a port, call :meth:`listen` on it, then start waiting for clients
-to connect::
+For server operation, typically you'd need to have a server certificate, and
+private key, each in a file. You'd open a socket, bind it to a port, call
+:meth:`listen` on it, then start waiting for clients to connect::
import socket, ssl
bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.listen(5)
-When one did, you'd call :meth:`accept` on the socket to get the new socket from the other
-end, and use :func:`wrap_socket` to create a server-side SSL context for it::
+When one did, you'd call :meth:`accept` on the socket to get the new socket from
+the other end, and use :func:`wrap_socket` to create a server-side SSL context
+for it::
while True:
newsocket, fromaddr = bindsocket.accept()
ssl_version=ssl.PROTOCOL_TLSv1)
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):
-
:mod:`stat` --- Interpreting :func:`stat` results
=================================================
.. 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>
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
any dictionary-like object with keys that match the placeholders in the
template. Alternatively, you can provide keyword arguments, where the
- keywords are the placeholders. When both *mapping* and *kws* are given
- and there are duplicates, the placeholders from *kws* take precedence.
+ keywords are the placeholders. When both *mapping* and *kwds* are given
+ 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
- *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,
unlike with :meth:`substitute`, any other appearances of the ``$`` will
simply return ``$`` instead of raising :exc:`ValueError`.
-
:mod:`stringprep` --- Internet String Preparation
=================================================
-
.. _stringservices:
***************
-
:mod:`struct` --- Interpret bytes as packed binary data
-=========================================================
+=======================================================
.. module:: struct
:synopsis: Interpret bytes as packed binary data.
(``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
if it contains exactly one item. The *buffer* must contain at least the amount
(``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.
(``len(buffer[offset:])`` must be at least :attr:`self.size`).
-
:mod:`subprocess` --- Subprocess management
===========================================
.. note::
- This feature is only available if Python is built with universal newline support
- (the default). Also, the newlines attribute of the file objects :attr:`stdout`,
- :attr:`stdin` and :attr:`stderr` are not updated by the :meth:`communicate` method.
+ This feature is only available if Python is built with universal newline
+ support (the default). Also, the newlines attribute of the file objects
+ :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
underlying CreateProcess() function. They can specify things such as appearance
-
:mod:`sunau` --- Read and write Sun AU files
============================================
-
:mod:`symbol` --- Constants used with Python parse trees
========================================================
-
:mod:`sys` --- System-specific parameters and functions
=======================================================
-
:mod:`syslog` --- Unix syslog library routines
==============================================
======================================================
.. module:: tabnanny
- :synopsis: Tool for detecting white space related problems in Python source files in a
- directory tree.
+ :synopsis: Tool for detecting white space related problems in Python
+ source files in a directory tree.
.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. sectionauthor:: Peter Funk <pf@artcom-gmbh.de>
-.. _tarfile-mod:
-
:mod:`tarfile` --- Read and write tar archive files
===================================================
-
:mod:`telnetlib` --- Telnet client
==================================
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
initially not connected by default; the :meth:`open` method must be used to
: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*
seconds have passed.
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
defaults to the standard Telnet port (23). The optional *timeout* parameter
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
present, they are substituted in the message using the standard string
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.
-
:mod:`tempfile` --- Generate temporary files and directories
============================================================
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.
The file is created using :func:`mkstemp`. It will be destroyed as soon
: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
the file is guaranteed to have a visible name in the file system (on
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
data is spooled in memory until the file size exceeds *max_size*, or
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
no race conditions in the file's creation, assuming that the platform
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
are no race conditions in the directory's creation. The directory is
: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
Use :func:`mkstemp` instead.
-
:mod:`termios` --- POSIX style tty control
==========================================
Convenience functions for common terminal control operations.
+.. _termios-example:
+
Example
-------
-.. _termios-example:
-
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` ...
:keyword:`finally` statement to ensure that the old tty attributes are restored
-
:mod:`test` --- Regression tests package for Python
===================================================
:mod:`test.support` --- Utility functions for tests
-========================================================
+===================================================
.. module:: test.support
:synopsis: Support for Python regression tests.
tests.
-.. function:: requires(resource[, msg])
+.. function:: requires(resource, msg=None)
Raises :exc:`ResourceDenied` if *resource* is not available. *msg* is the
argument to :exc:`ResourceDenied` if it is raised. Always returns true if called
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
specified exception type is raised. Any keyword arguments are treated as
-
:mod:`textwrap` --- Text wrapping and filling
=============================================
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*
- characters long. Returns a list of output lines, without final newlines.
+ Wraps the single paragraph in *text* (a string) so every line is at most
+ *width* characters long. Returns a list of output lines, without final
+ newlines.
Optional keyword arguments correspond to the instance attributes of
: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
wrapped paragraph. :func:`fill` is shorthand for ::
print(repr(dedent(s))) # prints 'hello\n world\n'
-.. class:: TextWrapper(...)
+.. class:: TextWrapper(**kwargs)
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="* ")
thread must release it once for each time it has acquired it.
-.. function:: Semaphore([value])
+.. function:: Semaphore(value=1)
:noindex:
A factory function that returns a new semaphore object. A semaphore manages a
given, *value* defaults to 1.
-.. function:: BoundedSemaphore([value])
+.. function:: BoundedSemaphore(value=1)
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
the *target* argument, if any, with sequential and keyword arguments taken
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
thread whose :meth:`join` method is called terminates -- either normally
All methods are executed atomically.
-.. method:: Lock.acquire([blocking=1])
+.. method:: Lock.acquire(blocking=True)
Acquire a lock, blocking or non-blocking.
:meth:`acquire` to proceed.
-.. method:: RLock.acquire([blocking=1])
+.. method:: RLock.acquire(blocking=True)
Acquire a lock, blocking or non-blocking.
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`
or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
Release the underlying lock. This method calls the corresponding method on
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
not acquired the lock when this method is called, a :exc:`RuntimeError` is
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
defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
raised.
- .. method:: acquire([blocking])
+ .. method:: acquire(blocking=True)
Acquire a semaphore.
:meth:`wait` will block until :meth:`.set` is called to set the internal
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
entry, return immediately. Otherwise, block until another thread calls
-
:mod:`time` --- Time access and conversions
===========================================
-
:mod:`timeit` --- Measure execution time of small code snippets
===============================================================
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.
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.
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.
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
statement once, and then returns the time it takes to execute the main statement
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
function and run its :meth:`repeat` method with the given repeat count and
*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
function and run its :meth:`timeit` method with *number* executions.
---------
-.. 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
application. It has an associated Tcl interpreter.
*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
if the widget state matches *statespec* and False otherwise. If callback
*statespec*.
- .. method:: state([statespec=None])
+ .. method:: state(statespec=None)
Modify or inquire widget state. If *statespec* is specified, sets the
widget state according to it and return a new *statespec* indicating
.. class:: Combobox
- .. method:: current([newindex=None])
+ .. method:: current(newindex=None)
If *newindex* is specified, sets the combobox value to the element
position *newindex*. Otherwise, returns the index of the current value or
See `Tab Options`_ for the list of available options.
- .. method:: select([tab_id])
+ .. method:: select(tab_id=None)
Selects the specified *tab_id*.
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*.
.. class:: Progressbar
- .. method:: start([interval])
+ .. method:: start(interval=None)
Begin autoincrement mode: schedules a recurring timer event that calls
:meth:`Progressbar.step` every *interval* milliseconds. If omitted,
*interval* defaults to 50 milliseconds.
- .. method:: step([amount])
+ .. method:: step(amount=None)
Increments the progress bar's value by *amount*.
.. class:: Treeview
- .. method:: bbox(item[, column=None])
+ .. method:: bbox(item, column=None)
Returns the bounding box (relative to the treeview widget's window) of
the specified *item* in the form (x, y, width, height).
scrolled offscreen), returns an empty string.
- .. method:: get_children([item])
+ .. method:: get_children(item=None)
Returns the list of children belonging to *item*.
*item*'s children.
- .. method:: column(column[, option=None[, **kw]])
+ .. method:: column(column, option=None, **kw)
Query or modify the options for the specified *column*.
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
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*.
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
item.
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*.
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
act according to the following selection methods.
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
specified *item*. With two arguments, returns the current value of the
*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*.
When an event is delivered to an item, the callbacks for each of the
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*.
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
*item* has the given *tagname*. Otherwise, returns a list of all items
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*.
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,
return the layout specification for given style.
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.
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
the current theme to *themename*, refreshes all widgets and emits a
-
:mod:`token` --- Constants used with Python parse trees
=======================================================
-
:mod:`trace` --- Trace or track Python statement execution
==========================================================
---------------------
-.. 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
parameters are optional. *count* enables counting of line numbers. *trace*
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
in the defined global and local environments. If not defined, *globals* and
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
or ``None``, all entries are printed. If *file* is omitted or ``None``, the
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
*traceback* to *file*. This differs from :func:`print_tb` in the following
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())``.
-.. 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,
sys.last_traceback, limit, file)``. In general it will work only after
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*
argument can be used to specify an alternate stack frame to start. The optional
: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
from the traceback object *traceback*. It is useful for alternate formatting of
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
the same format as for :func:`extract_tb`. The optional *f* and *limit*
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
same meaning as the corresponding arguments to :func:`print_exception`. The
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
file.
-.. function:: format_tb(tb[, limit])
+.. function:: format_tb(tb, limit=None)
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))``.
-
:mod:`tty` --- Terminal control 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
defaults to :const:`termios.TCSAFLUSH`, and is passed to
: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
defaults to :const:`termios.TCSAFLUSH`, and is passed to
-
.. _undoc:
********************
-
:mod:`unicodedata` --- Unicode Database
=======================================
Test cases
~~~~~~~~~~
-.. class:: TestCase([methodName])
+.. class:: TestCase(methodName='runTest')
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
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
*result*. If *result* is omitted or :const:`None`, a temporary result
failures.
- .. method:: assertTrue(expr[, msg])
- assert_(expr[, msg])
- failUnless(expr[, msg])
+ .. method:: assertTrue(expr, msg=None)
+ assert_(expr, msg=None)
+ failUnless(expr, msg=None)
Signal a test failure if *expr* is false; the explanation for the failure
will be *msg* if given, otherwise it will be :const:`None`.
:meth:`failUnless`.
- .. method:: assertEqual(first, second[, msg])
- failUnlessEqual(first, second[, msg])
+ .. method:: assertEqual(first, second, msg=None)
+ failUnlessEqual(first, second, msg=None)
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
:meth:`failUnlessEqual`.
- .. method:: assertNotEqual(first, second[, msg])
- failIfEqual(first, second[, msg])
+ .. method:: assertNotEqual(first, second, msg=None)
+ failIfEqual(first, second, msg=None)
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
:meth:`failIfEqual`.
- .. method:: assertAlmostEqual(first, second[, places[, msg]])
- failUnlessAlmostEqual(first, second[, places[, msg]])
+ .. method:: assertAlmostEqual(first, second, *, places=7, msg=None)
+ failUnlessAlmostEqual(first, second, *, places=7, msg=None)
Test that *first* and *second* are approximately equal by computing the
difference, rounding to the given number of decimal *places* (default 7),
:meth:`failUnlessAlmostEqual`.
- .. method:: assertNotAlmostEqual(first, second[, places[, msg]])
- failIfAlmostEqual(first, second[, places[, msg]])
+ .. method:: assertNotAlmostEqual(first, second, *, places=7, msg=None)
+ failIfAlmostEqual(first, second, *, places=7, msg=None)
Test that *first* and *second* are not approximately equal by computing
the difference, rounding to the given number of decimal *places* (default
.. 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
message including the pattern and the *text*. *regexp* may be
.. versionadded:: 3.1
- .. method:: assertRaises(exception[, callable, ...])
- failUnlessRaises(exception[, callable, ...])
+ .. method:: assertRaises(exception, callable, *args, **kwds)
+ failUnlessRaises(exception, callable, *args, **kwds)
+ assertRaises(exception)
+ failUnlessRaises(exception)
Test that an exception is raised when *callable* is called with any
positional or keyword arguments that are also passed to
To catch any of a group of exceptions, a tuple containing the exception
classes may be passed as *exception*.
- If *callable* is omitted or None, returns a context manager so that the
- code under test can be written inline rather than as a function::
+ If only the *exception* argument is given, returns a context manager so
+ that the code under test can be written inline rather than as a function::
with self.failUnlessRaises(some_error_class):
do_something()
.. versionadded:: 3.1
- .. method:: assertIsNone(expr[, msg])
+ .. method:: assertIsNone(expr, msg=None)
This signals a test failure if *expr* is not None.
.. versionadded:: 3.1
- .. method:: assertIsNotNone(expr[, msg])
+ .. method:: assertIsNotNone(expr, msg=None)
The inverse of the :meth:`assertIsNone` method.
This signals a test failure if *expr* is None.
.. 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
object.
.. versionadded:: 3.1
- .. method:: assertIsNot(expr1, expr2[, msg])
+ .. method:: assertIsNot(expr1, expr2, msg=None)
The inverse of the :meth:`assertIs` method.
This signals a test failure if *expr1* and *expr2* evaluate to the same
.. versionadded:: 3.1
- .. method:: assertFalse(expr[, msg])
- failIf(expr[, msg])
+ .. method:: assertFalse(expr, msg=None)
+ failIf(expr, msg=None)
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`
:meth:`failIf`.
- .. method:: fail([msg])
+ .. method:: fail(msg=None)
Signals a test failure unconditionally, with *msg* or :const:`None` for
the error message.
.. 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
used during the test. Functions will be called in reverse order to the
.. 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
allows the test runner to drive the test, but does not provide the methods which
Grouping tests
~~~~~~~~~~~~~~
-.. class:: TestSuite([tests])
+.. class:: TestSuite(tests=())
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
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.
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
than a single name. The return value is a test suite which supports all
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
has a few configurable parameters, but is essentially very simple. Graphical
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
test modules conveniently executable. The simplest use for this function is to
-
.. _unix:
**********************
to a value found in the dictionary of codes as found in
:attr:`http.server.BaseHTTPRequestHandler.responses`.
-.. exception:: ContentTooShortError(msg[, content])
+.. exception:: ContentTooShortError(msg, content)
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 :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
general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``.
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
:mimetype:`application/x-www-form-urlencoded`). Data are returned as a
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
:mimetype:`application/x-www-form-urlencoded`). Data are returned as a list of
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 should generally be used instead of :func:`urlparse` if the more recent URL
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
another URL (*url*). Informally, this uses components of the base URL, in
string. If there is no fragment identifier in *url*, return *url* unmodified
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,
digits, and the characters ``'_.-'`` are never quoted. The optional *safe*
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
quoting HTML form values when building up a query string to go into a URL.
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
:class:`str`, and does not perform string-to-bytes encoding.
Example: ``quote_from_bytes(b'a&\xef')`` yields
``'a%26%EF'``.
-.. function:: unquote(string[, encoding[, errors]])
+
+.. function:: unquote(string, encoding='utf-8', errors='replace')
Replace ``%xx`` escapes by their single-character equivalent.
The optional *encoding* and *errors* parameters specify how to decode
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
unquoting HTML form values.
Example: ``unquote_plus('/El+Ni%C3%B1o/')`` yields ``'/El Niño/'``.
+
.. function:: unquote_to_bytes(string)
Replace ``%xx`` escapes by their single-octet equivalent, and return a
``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"
string, suitable to pass to :func:`urlopen` above as the optional *data*
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
:class:`Request` object.
:class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
:class:`HTTPErrorProcessor`.
- If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
- :class:`HTTPSHandler` will also be added.
+ If the Python installation has SSL support (i.e., if the :mod:`ssl` module
+ can be imported), :class:`HTTPSHandler` will also be added.
A :class:`BaseHandler` subclass may also change its :attr:`handler_order`
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
points to a local file, or a valid cached copy of the object exists, the object
path. This does not accept a complete URL. This function uses :func:`unquote`
to decode *path*.
+
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.
document, and the user had no option to approve the automatic
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
objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
:class:`URLopener` objects will raise an :exc:`IOError` exception if the server
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
proxy information, then calls the appropriate open method with its input
:func:`urlopen`.
- .. method:: open_unknown(fullurl[, data])
+ .. method:: open_unknown(fullurl, data=None)
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
is a tuple consisting of a local filename and either a
A class to handle redirections.
-.. class:: HTTPCookieProcessor([cookiejar])
+.. class:: HTTPCookieProcessor(cookiejar=None)
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
dictionary mapping protocol names to URLs of proxies. The default is to read the
fits.
-.. class:: AbstractBasicAuthHandler([password_mgr])
+.. class:: AbstractBasicAuthHandler(password_mgr=None)
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
supported.
-.. class:: HTTPBasicAuthHandler([password_mgr])
+.. class:: HTTPBasicAuthHandler(password_mgr=None)
Handle authentication with the remote host. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section
supported.
-.. class:: ProxyBasicAuthHandler([password_mgr])
+.. class:: ProxyBasicAuthHandler(password_mgr=None)
Handle authentication with the proxy. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section
supported.
-.. class:: AbstractDigestAuthHandler([password_mgr])
+.. class:: AbstractDigestAuthHandler(password_mgr=None)
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
supported.
-.. class:: HTTPDigestAuthHandler([password_mgr])
+.. class:: HTTPDigestAuthHandler(password_mgr=None)
Handle authentication with the remote host. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section
supported.
-.. class:: ProxyDigestAuthHandler([password_mgr])
+.. class:: ProxyDigestAuthHandler(password_mgr=None)
Handle authentication with the proxy. *password_mgr*, if given, should be
something that is compatible with :class:`HTTPPasswordMgr`; refer to section
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
passing the given *data*. Arguments, return values and exceptions raised are
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
handlers for the given protocol with the given arguments (which are protocol
-
:mod:`uu` --- Encode and decode uuencode files
==============================================
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
the header specifying *name* and *mode* as the defaults for the results of
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
*out_file*. If *out_file* is a pathname, *mode* is used to set the permission
-
:mod:`uuid` --- UUID objects according to RFC 4122
==================================================
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
bytes as the *bytes* argument, a string of 16 bytes in little-endian order as
variant and version number set according to RFC 4122, overriding bits in the
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
.. 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*
is not given, :func:`getnode` is used to obtain the hardware address. If
-------------------
-.. 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*
argument, if given, must be a warning category class (see above); it defaults to
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
explicitly the message, category, filename and line number, and optionally the
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
``formatwarning(message, category, filename, lineno, line)`` and writes the
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
embedded newlines and ends in a newline. *line* is a line of source code to
*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
<warning-filter>`. The entry is inserted at the front by default; if
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
<warning-filter>`. The meaning of the function parameters is as for
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
and the :func:`showwarning` function.
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
file-like object. *mode* can be any of
-
:mod:`weakref` --- Weak references
==================================
but cannot be propagated; they are handled in exactly the same way as exceptions
raised from an object's :meth:`__del__` method.
- Weak references are :term:`hashable` if the *object* is hashable. They will maintain
- their hash value even after the *object* was deleted. If :func:`hash` is called
- the first time only after the *object* was deleted, the call will raise
- :exc:`TypeError`.
+ Weak references are :term:`hashable` if the *object* is hashable. They will
+ maintain their hash value even after the *object* was deleted. If
+ :func:`hash` is called the first time only after the *object* was deleted,
+ the call will raise :exc:`TypeError`.
Weak references support tests for equality, but not ordering. If the referents
are still alive, two references have the same equality relationship as their
-
:mod:`webbrowser` --- Convenient Web-browser controller
=======================================================
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
in the same browser window if possible. If *new* is 1, a new browser window
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 for a default browser appropriate to the caller's
- environment.
+ Return a controller object for the browser type *using*. If *using* is
+ ``None``, return a controller for a default browser appropriate to the
+ 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
:func:`get` function can return a controller for that browser type. If
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
browser window is opened if possible. If *new* is 2, a new browser page ("tab")
: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`
*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
- 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.
-
:mod:`winsound` --- Sound-playing interface for Windows
=======================================================
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
plays a sound as specified in the registry. The *type* argument specifies which
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
algorithm found in the "URL Reconstruction" section of :pep:`333`. If
: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
support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for
: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
for *app*. The return value is an instance of the supplied *server_class*, and
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
:mod:`os` modules, the CGI environment and I/O streams are specified explicitly.
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
servers. If you are writing an HTTP server implementation, you will probably
-
:mod:`xdrlib` --- Encode and decode XDR data
============================================
-
:mod:`xml.dom.minidom` --- Lightweight DOM implementation
=========================================================
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
either a file name, or a file-like object. *parser*, if given, must be a SAX2
instead:
-.. function:: parseString(string[, parser])
+.. function:: parseString(string, parser=None)
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`.
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
which matches that of the file object interface. The *indent* parameter is the
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.
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
indentation string and defaults to a tabulator; *newl* specifies the string
-
:mod:`xml.dom.pulldom` --- Support for building partial DOM trees
=================================================================
Object Model representation of a document from SAX events.
-.. class:: PullDOM([documentFactory])
+.. class:: PullDOM(documentFactory=None)
:class:`xml.sax.handler.ContentHandler` implementation that ...
...
-.. class:: SAX2DOM([documentFactory])
+.. class:: SAX2DOM(documentFactory=None)
: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
================================================
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
module name of a DOM implementation, or ``None``. If it is not ``None``, imports
-
:mod:`xml.etree.ElementTree` --- The ElementTree XML API
========================================================
---------
-.. function:: Comment([text])
+.. function:: Comment(text=None)
Comment element factory. This factory function creates a special element
that will be serialized as an XML comment. The comment string can be either
*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 interface. The exact class or type of that object is implementation
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
going on to the user. *source* is a filename or file object containing XML data.
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
object containing XML data. *parser* is an optional parser instance. If not
instance.
-.. function:: ProcessingInstruction(target[, text])
+.. function:: ProcessingInstruction(target, text=None)
PI element factory. This factory function creates a special element that will
be serialized as an XML processing instruction. *target* is a string containing
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
to an existing element.
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.
*element* is an Element instance. *encoding* is the output encoding (default is
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*.
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
tag name or path. Returns the text content of the first matching element, or
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
iterates over this element and all elements below it, in document (depth first)
-------------------
-.. class:: ElementTree([element,] [file])
+.. class:: ElementTree(element=None, file=None)
ElementTree wrapper class. This class represents an entire element hierarchy,
and adds some extra support for serialization to and from standard XML.
order.
- .. method:: findtext(path[, default])
+ .. method:: findtext(path, default=None)
Finds the element text for the first toplevel element with given tag.
Same as getroot().findtext(path). *path* is the toplevel element to look
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
loops over all elements in this tree, in section order. *tag* is the tag
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
name or file object. *parser* is an optional parser instance. If not
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
file object opened for writing. *encoding* [1]_ is the output encoding
-------------
-.. 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
get proper namespace handling on output. *text_or_uri* is a string containing
-------------------
-.. class:: TreeBuilder([element_factory])
+.. class:: TreeBuilder(element_factory=None)
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
----------------------
-.. class:: XMLTreeBuilder([html,] [target])
+.. class:: XMLTreeBuilder(html=0, target=None)
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
-
:mod:`xml.sax.handler` --- Base classes for SAX handlers
========================================================
-
:mod:`xml.sax.xmlreader` --- Interface for XML parsers
======================================================
methods may return ``None``.
-.. class:: InputSource([systemId])
+.. class:: InputSource(system_id=None)
Encapsulation of the information needed by the :class:`XMLReader` to read
entities.
-
:mod:`xml.sax` --- Support for SAX2 parsers
===========================================
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
be used. If *parser_list* is provided, it must be a sequence of strings which
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
*filename_or_stream*, can be a filename or a file object. The *handler*
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
parameter.
classes.
-.. exception:: SAXException(msg[, exception])
+.. exception:: SAXException(msg, exception=None)
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
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
confronted with an unrecognized feature or property. SAX applications and
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
enable a feature that is not supported, or to set a property to a value that the
-
:mod:`xml.sax.saxutils` --- SAX Utilities
=========================================
or as base classes.
-.. function:: escape(data[, entities])
+.. function:: escape(data, entities={})
Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data.
``'>'`` are always escaped, even if *entities* is provided.
-.. function:: unescape(data[, entities])
+.. function:: unescape(data, entities={})
Unescape ``'&'``, ``'<'``, and ``'>'`` in a string of data.
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
attribute value. The return value is a quoted version of *data* with any
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
events back into an XML document. In other words, using an :class:`XMLGenerator`
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
resolved :class:`InputSource` object ready for reading. The input source can be
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
remote XML-RPC server. The required first argument is a URI (Uniform Resource
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*
is true. *params* can be either a tuple of arguments or an instance of the
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,
methodname)``. *params* is a tuple of argument; *methodname* is a string, or
: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
functions that can be called by the XML-RPC protocol. The *requestHandler*
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
*allow_none* and *encoding* parameters are passed on to :mod:`xmlrpc.client`
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,
it will be the method name associated with *function*, otherwise
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
registered using :meth:`register_function`. If *instance* contains a
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,
it will be the method name associated with function, otherwise
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
data provided by the HTTP server, otherwise the contents of stdin will be used.
: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
:class:`SimpleXMLRPCServer`; *requestHandler* defaults to
-
:mod:`zipfile` --- Work with ZIP archives
=========================================
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
of this class are returned by the :meth:`getinfo` and :meth:`infolist`
---------------
-.. 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
file-like object. The *mode* parameter should be ``'r'`` to read an existing
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
the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
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*
must be its full name or a :class:`ZipInfo` object). Its file information is
*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*
specifies a different directory to extract to. *members* is optional and must
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
file in the archive, or a :class:`ZipInfo` object. The archive must be open for
: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
*arcname* (by default, this will be the same as *filename*, but without a drive
: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.
The corresponding file is a :file:`\*.pyo` file if available, else a
-
:mod:`zipimport` --- Import modules from Zip archives
=====================================================
-
:mod:`zlib` --- Compression compatible with :program:`gzip`
===========================================================
.. module:: zlib
- :synopsis: Low-level interface to compression and decompression routines compatible with
- gzip.
+ :synopsis: Low-level interface to compression and decompression routines
+ compatible with gzip.
For applications that require data compression, the functions in this module
perform the assignment, it raises an exception (usually but not necessarily
: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::
pair: subscription; assignment
object: mutable
*in-place* behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations.
-For targets which are attribute references, the initial value is retrieved with
-a :meth:`getattr` and the result is assigned with a :meth:`setattr`. Notice
-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
+For targets which are attribute references, the same :ref:`caveat about class
+and instance attributes <attr-target-note>` applies as for regular assignments.
.. _assert:
Body.enum.converters['lowerroman'] = \
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=[]):
issue = utils.unescape(text)
/* -- main layout ----------------------------------------------------------- */
-div.documentwrapper {
- float: left;
- width: 100%;
-}
-
-div.bodywrapper {
- margin: 0 0 0 230px;
-}
-
div.clearer {
clear: both;
}
font-style: italic;
}
+p.deprecated {
+ background-color: #ffe4e4;
+ border: 1px solid #f66;
+ padding: 7px
+}
+
.system-message {
background-color: #fda;
padding: 5px;
vertical-align: middle;
}
-div.math p {
+div.body div.math p {
text-align: center;
}
User-defined Exceptions
=======================
-Programs may name their own exceptions by creating a new exception class.
-Exceptions should typically be derived from the :exc:`Exception` class, either
-directly or indirectly. For example::
+Programs may name their own exceptions by creating a new exception class (see
+:ref:`tut-classes` for more about Python classes). Exceptions should typically
+be derived from the :exc:`Exception` class, either directly or indirectly. For
+example::
>>> class MyError(Exception):
... def __init__(self, value):
owner and owner.name,
self._count)
- def acquire(self, blocking=1):
+ def acquire(self, blocking=True):
me = current_thread()
if self._owner is me:
self._count = self._count + 1
self._cond = Condition(Lock())
self._value = value
- def acquire(self, blocking=1):
+ def acquire(self, blocking=True):
rc = False
self._cond.acquire()
while self._value == 0:
tb = tb.tb_next
n = n+1
-def format_tb(tb, limit = None):
+def format_tb(tb, limit=None):
"""A shorthand for 'format_list(extract_stack(f, 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.
This is useful for alternate formatting of stack traces. If
f = sys.exc_info()[2].tb_frame.f_back
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.
The return value has the same format as for extract_tb(). The
res[-1] = b''.join(pct_sequence).decode(encoding, errors)
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.
Arguments:
dict[name] = [value]
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.
Arguments:
_safe_quoters[cachekey] = quoter
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.
If any values in the query arg are sequences and doseq is true, each
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"""
#
# Open the input file, if needed.
return s
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).
Use assertions to check that all arguments have the right type."""
else:
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).
A simple filter matches all modules and messages.
url += quote(environ.get('SCRIPT_NAME') or '/')
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"""
url = application_uri(environ)
from urllib.parse import quote
return 0
return 1
-def getDOMImplementation(name = None, features = ()):
+def getDOMImplementation(name=None, features=()):
"""getDOMImplementation(name = None, features = ()) -> DOM implementation.
Return a suitable DOM implementation. The name is either
def __bool__(self):
return True
- def toxml(self, encoding = None):
+ def toxml(self, encoding=None):
return self.toprettyxml("", "", encoding)
def toprettyxml(self, indent="\t", newl="\n", encoding=None):
# --- 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
returns a fully resolved InputSource object ready for reading."""
# by the way, if you don't understand what's going on in here,
# that's perfectly ok.
- def __init__(self, encoding=None, allow_none=0):
+ def __init__(self, encoding=None, allow_none=False):
self.memo = {}
self.data = None
self.encoding = encoding
# and again, if you don't understand what's going on in here,
# that's perfectly ok.
- def __init__(self, use_datetime=0):
+ def __init__(self, use_datetime=False):
self._type = None
self._stack = []
self._marks = []
#
# return A (parser, unmarshaller) tuple.
-def getparser(use_datetime=0):
+def getparser(use_datetime=False):
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
# @return A string containing marshalled data.
def dumps(params, methodname=None, methodresponse=None, encoding=None,
- allow_none=0):
+ allow_none=False):
"""data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
# (None if not present).
# @see Fault
-def loads(data, use_datetime=0):
+def loads(data, use_datetime=False):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
# client identifier (may be overridden)
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
##
# @param verbose Debugging flag.
# @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
http_conn = self.send_request(host, handler, request_body, verbose)
the given encoding.
"""
- def __init__(self, uri, transport=None, encoding=None, verbose=0,
- allow_none=0, use_datetime=0):
+ def __init__(self, uri, transport=None, encoding=None, verbose=False,
+ allow_none=False, use_datetime=False):
# establish a "logical" server connection
# get the url
self.instance = instance
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.
The optional name argument can be used to set a Unicode name
sys.stdout.buffer.write(response)
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.
If no XML data is given then it is read from stdin. The resulting
"""
def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
- logRequests=1, allow_none=False, encoding=None,
+ logRequests=True, allow_none=False, encoding=None,
bind_and_activate=True):
SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
allow_none, encoding, bind_and_activate)
class PyZipFile(ZipFile):
"""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.
If pathname is a package directory, search the directory and