Commit e41251e8 authored by Benjamin Peterson's avatar Benjamin Peterson

Merged revisions 62490 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r62490 | benjamin.peterson | 2008-04-24 20:29:10 -0500 (Thu, 24 Apr 2008) | 2 lines

  reformat some documentation of classes so methods and attributes are under the class directive
........
parent 768db92b
...@@ -197,7 +197,7 @@ asynchat - Auxiliary Classes and Functions ...@@ -197,7 +197,7 @@ asynchat - Auxiliary Classes and Functions
the data no larger than *buffer_size*. the data no larger than *buffer_size*.
.. method:: simple_producer.more() .. method:: more()
Produces the next chunk of information from the producer, or returns the Produces the next chunk of information from the producer, or returns the
empty string. empty string.
...@@ -212,23 +212,23 @@ asynchat - Auxiliary Classes and Functions ...@@ -212,23 +212,23 @@ asynchat - Auxiliary Classes and Functions
producers or data items to be written to the channel. producers or data items to be written to the channel.
.. method:: fifo.is_empty() .. method:: is_empty()
Returns ``True`` if and only if the fifo is empty. Returns ``True`` if and only if the fifo is empty.
.. method:: fifo.first() .. method:: first()
Returns the least-recently :meth:`push`\ ed item from the fifo. Returns the least-recently :meth:`push`\ ed item from the fifo.
.. method:: fifo.push(data) .. method:: push(data)
Adds the given data (which may be a string or a producer object) to the Adds the given data (which may be a string or a producer object) to the
producer fifo. producer fifo.
.. method:: fifo.pop() .. method:: pop()
If the fifo is not empty, returns ``True, first()``, deleting the popped If the fifo is not empty, returns ``True, first()``, deleting the popped
item. Returns ``False, None`` for an empty fifo. item. Returns ``False, None`` for an empty fifo.
......
...@@ -95,17 +95,17 @@ any that have been added to the map during asynchronous service) is closed. ...@@ -95,17 +95,17 @@ any that have been added to the map during asynchronous service) is closed.
should be added to the list of channels :cfunc:`select`\ ed or should be added to the list of channels :cfunc:`select`\ ed or
:cfunc:`poll`\ ed for read and write events. :cfunc:`poll`\ ed for read and write events.
Thus, the set of channel events is larger than the basic socket events. The Thus, the set of channel events is larger than the basic socket events. The
full set of methods that can be overridden in your subclass follows: full set of methods that can be overridden in your subclass follows:
.. method:: dispatcher.handle_read() .. method:: handle_read()
Called when the asynchronous loop detects that a :meth:`read` call on the Called when the asynchronous loop detects that a :meth:`read` call on the
channel's socket will succeed. channel's socket will succeed.
.. method:: dispatcher.handle_write() .. method:: handle_write()
Called when the asynchronous loop detects that a writable socket can be Called when the asynchronous loop detects that a writable socket can be
written. Often this method will implement the necessary buffering for written. Often this method will implement the necessary buffering for
...@@ -116,38 +116,38 @@ full set of methods that can be overridden in your subclass follows: ...@@ -116,38 +116,38 @@ full set of methods that can be overridden in your subclass follows:
self.buffer = self.buffer[sent:] self.buffer = self.buffer[sent:]
.. method:: dispatcher.handle_expt() .. method:: handle_expt()
Called when there is out of band (OOB) data for a socket connection. This Called when there is out of band (OOB) data for a socket connection. This
will almost never happen, as OOB is tenuously supported and rarely used. will almost never happen, as OOB is tenuously supported and rarely used.
.. method:: dispatcher.handle_connect() .. method:: handle_connect()
Called when the active opener's socket actually makes a connection. Might Called when the active opener's socket actually makes a connection. Might
send a "welcome" banner, or initiate a protocol negotiation with the remote send a "welcome" banner, or initiate a protocol negotiation with the
endpoint, for example. remote endpoint, for example.
.. method:: dispatcher.handle_close() .. method:: handle_close()
Called when the socket is closed. Called when the socket is closed.
.. method:: dispatcher.handle_error() .. method:: handle_error()
Called when an exception is raised and not otherwise handled. The default Called when an exception is raised and not otherwise handled. The default
version prints a condensed traceback. version prints a condensed traceback.
.. method:: dispatcher.handle_accept() .. method:: handle_accept()
Called on listening channels (passive openers) when a connection can be Called on listening channels (passive openers) when a connection can be
established with a new remote endpoint that has issued a :meth:`connect` established with a new remote endpoint that has issued a :meth:`connect`
call for the local endpoint. call for the local endpoint.
.. method:: dispatcher.readable() .. method:: readable()
Called each time around the asynchronous loop to determine whether a Called each time around the asynchronous loop to determine whether a
channel's socket should be added to the list on which read events can channel's socket should be added to the list on which read events can
...@@ -155,50 +155,50 @@ full set of methods that can be overridden in your subclass follows: ...@@ -155,50 +155,50 @@ full set of methods that can be overridden in your subclass follows:
default, all channels will be interested in read events. default, all channels will be interested in read events.
.. method:: dispatcher.writable() .. method:: writable()
Called each time around the asynchronous loop to determine whether a Called each time around the asynchronous loop to determine whether a
channel's socket should be added to the list on which write events can channel's socket should be added to the list on which write events can
occur. The default method simply returns ``True``, indicating that by occur. The default method simply returns ``True``, indicating that by
default, all channels will be interested in write events. default, all channels will be interested in write events.
In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.
In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.
.. method:: dispatcher.create_socket(family, type)
This is identical to the creation of a normal socket, and will use the same .. method:: create_socket(family, type)
options for creation. Refer to the :mod:`socket` documentation for
This is identical to the creation of a normal socket, and will use the
same options for creation. Refer to the :mod:`socket` documentation for
information on creating sockets. information on creating sockets.
.. method:: dispatcher.connect(address) .. method:: connect(address)
As with the normal socket object, *address* is a tuple with the first As with the normal socket object, *address* is a tuple with the first
element the host to connect to, and the second the port number. element the host to connect to, and the second the port number.
.. method:: dispatcher.send(data) .. method:: send(data)
Send *data* to the remote end-point of the socket. Send *data* to the remote end-point of the socket.
.. method:: dispatcher.recv(buffer_size) .. method:: recv(buffer_size)
Read at most *buffer_size* bytes from the socket's remote end-point. Read at most *buffer_size* bytes from the socket's remote end-point. An
An empty string implies that the channel has been closed from the other empty string implies that the channel has been closed from the other end.
end.
.. method:: dispatcher.listen(backlog) .. method:: listen(backlog)
Listen for connections made to the socket. The *backlog* argument Listen for connections made to the socket. The *backlog* argument
specifies the maximum number of queued connections and should be at least specifies the maximum number of queued connections and should be at least
1; the maximum value is system-dependent (usually 5). 1; the maximum value is system-dependent (usually 5).
.. method:: dispatcher.bind(address) .. method:: bind(address)
Bind the socket to *address*. The socket must not already be bound. (The Bind the socket to *address*. The socket must not already be bound. (The
format of *address* depends on the address family --- see above.) To mark format of *address* depends on the address family --- see above.) To mark
...@@ -206,7 +206,7 @@ Most of these are nearly identical to their socket partners. ...@@ -206,7 +206,7 @@ Most of these are nearly identical to their socket partners.
the :class:`dispatcher` object's :meth:`set_reuse_addr` method. the :class:`dispatcher` object's :meth:`set_reuse_addr` method.
.. method:: dispatcher.accept() .. method:: accept()
Accept a connection. The socket must be bound to an address and listening Accept a connection. The socket must be bound to an address and listening
for connections. The return value is a pair ``(conn, address)`` where for connections. The return value is a pair ``(conn, address)`` where
...@@ -215,7 +215,7 @@ Most of these are nearly identical to their socket partners. ...@@ -215,7 +215,7 @@ Most of these are nearly identical to their socket partners.
end of the connection. end of the connection.
.. method:: dispatcher.close() .. method:: close()
Close the socket. All future operations on the socket object will fail. Close the socket. All future operations on the socket object will fail.
The remote end-point will receive no more data (after queued data is The remote end-point will receive no more data (after queued data is
......
...@@ -34,110 +34,115 @@ to a handler. Code to create and run the server looks like this:: ...@@ -34,110 +34,115 @@ to a handler. Code to create and run the server looks like this::
.. class:: HTTPServer(server_address, RequestHandlerClass) .. class:: HTTPServer(server_address, RequestHandlerClass)
This class builds on the :class:`TCPServer` class by storing the server address This class builds on the :class:`TCPServer` class by storing the server
as instance variables named :attr:`server_name` and :attr:`server_port`. The address as instance variables named :attr:`server_name` and
server is accessible by the handler, typically through the handler's :attr:`server_port`. The server is accessible by the handler, typically
:attr:`server` instance variable. through the handler's :attr:`server` instance variable.
.. class:: BaseHTTPRequestHandler(request, client_address, server) .. class:: BaseHTTPRequestHandler(request, client_address, server)
This class is used to handle the HTTP requests that arrive at the server. By This class is used to handle the HTTP requests that arrive at the server. By
itself, it cannot respond to any actual HTTP requests; it must be subclassed to itself, it cannot respond to any actual HTTP requests; it must be subclassed
handle each request method (e.g. GET or POST). :class:`BaseHTTPRequestHandler` to handle each request method (e.g. GET or
provides a number of class and instance variables, and methods for use by POST). :class:`BaseHTTPRequestHandler` provides a number of class and
subclasses. instance variables, and methods for use by subclasses.
The handler will parse the request and the headers, then call a method specific The handler will parse the request and the headers, then call a method
to the request type. The method name is constructed from the request. For specific to the request type. The method name is constructed from the
example, for the request method ``SPAM``, the :meth:`do_SPAM` method will be request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
called with no arguments. All of the relevant information is stored in instance method will be called with no arguments. All of the relevant information is
variables of the handler. Subclasses should not need to override or extend the stored in instance variables of the handler. Subclasses should not need to
:meth:`__init__` method. override or extend the :meth:`__init__` method.
:class:`BaseHTTPRequestHandler` has the following instance variables: :class:`BaseHTTPRequestHandler` has the following instance variables:
.. attribute:: BaseHTTPRequestHandler.client_address .. attribute:: client_address
Contains a tuple of the form ``(host, port)`` referring to the client's address. Contains a tuple of the form ``(host, port)`` referring to the client's
address.
.. attribute:: BaseHTTPRequestHandler.command .. attribute:: command
Contains the command (request type). For example, ``'GET'``. Contains the command (request type). For example, ``'GET'``.
.. attribute:: BaseHTTPRequestHandler.path .. attribute:: path
Contains the request path. Contains the request path.
.. attribute:: BaseHTTPRequestHandler.request_version .. attribute:: request_version
Contains the version string from the request. For example, ``'HTTP/1.0'``. Contains the version string from the request. For example, ``'HTTP/1.0'``.
.. attribute:: BaseHTTPRequestHandler.headers .. attribute:: headers
Holds an instance of the class specified by the :attr:`MessageClass` class Holds an instance of the class specified by the :attr:`MessageClass` class
variable. This instance parses and manages the headers in the HTTP request. variable. This instance parses and manages the headers in the HTTP
request.
.. attribute:: BaseHTTPRequestHandler.rfile .. attribute:: rfile
Contains an input stream, positioned at the start of the optional input data. Contains an input stream, positioned at the start of the optional input
data.
.. attribute:: BaseHTTPRequestHandler.wfile .. attribute:: wfile
Contains the output stream for writing a response back to the client. Proper Contains the output stream for writing a response back to the
adherence to the HTTP protocol must be used when writing to this stream. client. Proper adherence to the HTTP protocol must be used when writing to
this stream.
:class:`BaseHTTPRequestHandler` has the following class variables:
:class:`BaseHTTPRequestHandler` has the following class variables:
.. attribute:: BaseHTTPRequestHandler.server_version
.. attribute:: server_version
Specifies the server software version. You may want to override this. The Specifies the server software version. You may want to override this. The
format is multiple whitespace-separated strings, where each string is of the format is multiple whitespace-separated strings, where each string is of
form name[/version]. For example, ``'BaseHTTP/0.2'``. the form name[/version]. For example, ``'BaseHTTP/0.2'``.
.. attribute:: BaseHTTPRequestHandler.sys_version .. attribute:: sys_version
Contains the Python system version, in a form usable by the Contains the Python system version, in a form usable by the
:attr:`version_string` method and the :attr:`server_version` class variable. For :attr:`version_string` method and the :attr:`server_version` class
example, ``'Python/1.4'``. variable. For example, ``'Python/1.4'``.
.. attribute:: BaseHTTPRequestHandler.error_message_format .. attribute:: error_message_format
Specifies a format string for building an error response to the client. It uses Specifies a format string for building an error response to the client. It
parenthesized, keyed format specifiers, so the format operand must be a uses parenthesized, keyed format specifiers, so the format operand must be
dictionary. The *code* key should be an integer, specifying the numeric HTTP a dictionary. The *code* key should be an integer, specifying the numeric
error code value. *message* should be a string containing a (detailed) error HTTP error code value. *message* should be a string containing a
message of what occurred, and *explain* should be an explanation of the error (detailed) error message of what occurred, and *explain* should be an
code number. Default *message* and *explain* values can found in the *responses* explanation of the error code number. Default *message* and *explain*
class variable. values can found in the *responses* class variable.
.. attribute:: BaseHTTPRequestHandler.error_content_type .. attribute:: error_content_type
Specifies the Content-Type HTTP header of error responses sent to the client. Specifies the Content-Type HTTP header of error responses sent to the
The default value is ``'text/html'``. client. The default value is ``'text/html'``.
.. attribute:: BaseHTTPRequestHandler.protocol_version .. attribute:: protocol_version
This specifies the HTTP protocol version used in responses. If set to This specifies the HTTP protocol version used in responses. If set to
``'HTTP/1.1'``, the server will permit HTTP persistent connections; however, ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
your server *must* then include an accurate ``Content-Length`` header (using however, your server *must* then include an accurate ``Content-Length``
:meth:`send_header`) in all of its responses to clients. For backwards header (using :meth:`send_header`) in all of its responses to clients.
compatibility, the setting defaults to ``'HTTP/1.0'``. For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
.. attribute:: BaseHTTPRequestHandler.MessageClass .. attribute:: MessageClass
.. index:: single: Message (in module mimetools) .. index:: single: Message (in module mimetools)
...@@ -146,7 +151,7 @@ to a handler. Code to create and run the server looks like this:: ...@@ -146,7 +151,7 @@ to a handler. Code to create and run the server looks like this::
:class:`mimetools.Message`. :class:`mimetools.Message`.
.. attribute:: BaseHTTPRequestHandler.responses .. attribute:: responses
This variable contains a mapping of error code integers to two-element tuples This variable contains a mapping of error code integers to two-element tuples
containing a short and long message. For example, ``{code: (shortmessage, containing a short and long message. For example, ``{code: (shortmessage,
...@@ -154,23 +159,25 @@ to a handler. Code to create and run the server looks like this:: ...@@ -154,23 +159,25 @@ to a handler. Code to create and run the server looks like this::
error response, and *longmessage* as the *explain* key (see the error response, and *longmessage* as the *explain* key (see the
:attr:`error_message_format` class variable). :attr:`error_message_format` class variable).
A :class:`BaseHTTPRequestHandler` instance has the following methods:
A :class:`BaseHTTPRequestHandler` instance has the following methods:
.. method:: BaseHTTPRequestHandler.handle() .. method:: handle()
Calls :meth:`handle_one_request` once (or, if persistent connections are Calls :meth:`handle_one_request` once (or, if persistent connections are
enabled, multiple times) to handle incoming HTTP requests. You should never need enabled, multiple times) to handle incoming HTTP requests. You should
to override it; instead, implement appropriate :meth:`do_\*` methods. never need to override it; instead, implement appropriate :meth:`do_\*`
methods.
.. method:: BaseHTTPRequestHandler.handle_one_request() .. method:: handle_one_request()
This method will parse and dispatch the request to the appropriate :meth:`do_\*` This method will parse and dispatch the request to the appropriate
method. You should never need to override it. :meth:`do_\*` method. You should never need to override it.
.. method:: BaseHTTPRequestHandler.send_error(code[, message]) .. method:: send_error(code[, message])
Sends and logs a complete error reply to the client. The numeric *code* Sends and logs a complete error reply to the client. The numeric *code*
specifies the HTTP error code, with *message* as optional, more specific text. A specifies the HTTP error code, with *message* as optional, more specific text. A
...@@ -178,72 +185,73 @@ A :class:`BaseHTTPRequestHandler` instance has the following methods: ...@@ -178,72 +185,73 @@ A :class:`BaseHTTPRequestHandler` instance has the following methods:
:attr:`error_message_format` class variable. :attr:`error_message_format` class variable.
.. method:: BaseHTTPRequestHandler.send_response(code[, message]) .. method:: send_response(code[, message])
Sends a response header and logs the accepted request. The HTTP response line is Sends a response header and logs the accepted request. The HTTP response
sent, followed by *Server* and *Date* headers. The values for these two headers line is sent, followed by *Server* and *Date* headers. The values for
are picked up from the :meth:`version_string` and :meth:`date_time_string` these two headers are picked up from the :meth:`version_string` and
methods, respectively. :meth:`date_time_string` methods, respectively.
.. method:: BaseHTTPRequestHandler.send_header(keyword, value) .. method:: send_header(keyword, value)
Writes a specific HTTP header to the output stream. *keyword* should specify the Writes a specific HTTP header to the output stream. *keyword* should
header keyword, with *value* specifying its value. specify the header keyword, with *value* specifying its value.
.. method:: BaseHTTPRequestHandler.end_headers() .. method:: end_headers()
Sends a blank line, indicating the end of the HTTP headers in the response. Sends a blank line, indicating the end of the HTTP headers in the
response.
.. method:: BaseHTTPRequestHandler.log_request([code[, size]]) .. method:: log_request([code[, size]])
Logs an accepted (successful) request. *code* should specify the numeric HTTP Logs an accepted (successful) request. *code* should specify the numeric
code associated with the response. If a size of the response is available, then HTTP code associated with the response. If a size of the response is
it should be passed as the *size* parameter. available, then it should be passed as the *size* parameter.
.. method:: BaseHTTPRequestHandler.log_error(...) .. method:: log_error(...)
Logs an error when a request cannot be fulfilled. By default, it passes the Logs an error when a request cannot be fulfilled. By default, it passes
message to :meth:`log_message`, so it takes the same arguments (*format* and the message to :meth:`log_message`, so it takes the same arguments
additional values). (*format* and additional values).
.. method:: BaseHTTPRequestHandler.log_message(format, ...) .. method:: log_message(format, ...)
Logs an arbitrary message to ``sys.stderr``. This is typically overridden to Logs an arbitrary message to ``sys.stderr``. This is typically overridden
create custom error logging mechanisms. The *format* argument is a standard to create custom error logging mechanisms. The *format* argument is a
printf-style format string, where the additional arguments to standard printf-style format string, where the additional arguments to
:meth:`log_message` are applied as inputs to the formatting. The client address :meth:`log_message` are applied as inputs to the formatting. The client
and current date and time are prefixed to every message logged. address and current date and time are prefixed to every message logged.
.. method:: BaseHTTPRequestHandler.version_string() .. method:: version_string()
Returns the server software's version string. This is a combination of the Returns the server software's version string. This is a combination of the
:attr:`server_version` and :attr:`sys_version` class variables. :attr:`server_version` and :attr:`sys_version` class variables.
.. method:: BaseHTTPRequestHandler.date_time_string([timestamp]) .. method:: date_time_string([timestamp])
Returns the date and time given by *timestamp* (which must be in the format Returns the date and time given by *timestamp* (which must be in the
returned by :func:`time.time`), formatted for a message header. If *timestamp* format returned by :func:`time.time`), formatted for a message header. If
is omitted, it uses the current date and time. *timestamp* is omitted, it uses the current date and time.
The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
.. method:: BaseHTTPRequestHandler.log_date_time_string() .. method:: log_date_time_string()
Returns the current date and time, formatted for logging. Returns the current date and time, formatted for logging.
.. method:: BaseHTTPRequestHandler.address_string() .. method:: address_string()
Returns the client address, formatted for logging. A name lookup is performed on Returns the client address, formatted for logging. A name lookup is
the client's IP address. performed on the client's IP address.
.. seealso:: .. seealso::
......
...@@ -31,23 +31,26 @@ The :mod:`bdb` module also defines two classes: ...@@ -31,23 +31,26 @@ The :mod:`bdb` module also defines two classes:
first line of that function is executed. A conditional breakpoint always first line of that function is executed. A conditional breakpoint always
counts a hit. counts a hit.
:class:`Breakpoint` instances have the following methods: :class:`Breakpoint` instances have the following methods:
.. method:: Breakpoint.deleteMe() .. method:: deleteMe()
Delete the breakpoint from the list associated to a file/line. If it is the Delete the breakpoint from the list associated to a file/line. If it is
last breakpoint in that position, it also deletes the entry for the the last breakpoint in that position, it also deletes the entry for the
file/line. file/line.
.. method:: Breakpoint.enable()
.. method:: enable()
Mark the breakpoint as enabled. Mark the breakpoint as enabled.
.. method:: Breakpoint.disable()
.. method:: disable()
Mark the breakpoint as disabled. Mark the breakpoint as disabled.
.. method:: Breakpoint.bpprint([out])
.. method:: pprint([out])
Print all the information about the breakpoint: Print all the information about the breakpoint:
...@@ -68,28 +71,27 @@ The :mod:`bdb` module also defines two classes: ...@@ -68,28 +71,27 @@ The :mod:`bdb` module also defines two classes:
(:class:`pdb.Pdb`) is an example. (:class:`pdb.Pdb`) is an example.
The following methods of :class:`Bdb` normally don't need to be overridden. The following methods of :class:`Bdb` normally don't need to be overridden.
.. method:: Bdb.canonic(filename) .. method:: canonic(filename)
Auxiliary method for getting a filename in a canonical form, that is, as a Auxiliary method for getting a filename in a canonical form, that is, as a
case-normalized (on case-insensitive filesystems) absolute path, stripped case-normalized (on case-insensitive filesystems) absolute path, stripped
of surrounding angle brackets. of surrounding angle brackets.
.. method:: Bdb.reset() .. method:: reset()
Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and
:attr:`quitting` attributes with values ready to start debugging. :attr:`quitting` attributes with values ready to start debugging.
.. method:: trace_dispatch(frame, event, arg)
.. method:: Bdb.trace_dispatch(frame, event, arg)
This function is installed as the trace function of debugged frames. Its This function is installed as the trace function of debugged frames. Its
return value is the new trace function (in most cases, that is, itself). return value is the new trace function (in most cases, that is, itself).
The default implementation decides how to dispatch a frame, depending on the The default implementation decides how to dispatch a frame, depending on
type of event (passed as a string) that is about to be executed. *event* can the type of event (passed as a string) that is about to be executed.
be one of the following: *event* can be one of the following:
* ``"line"``: A new line of code is going to be executed. * ``"line"``: A new line of code is going to be executed.
* ``"call"``: A function is about to be called, or another code block * ``"call"``: A function is about to be called, or another code block
...@@ -100,39 +102,39 @@ The following methods of :class:`Bdb` normally don't need to be overridden. ...@@ -100,39 +102,39 @@ The following methods of :class:`Bdb` normally don't need to be overridden.
* ``"c_return"``: A C function has returned. * ``"c_return"``: A C function has returned.
* ``"c_exception"``: A C function has thrown an exception. * ``"c_exception"``: A C function has thrown an exception.
For the Python events, specialized functions (see below) are called. For the For the Python events, specialized functions (see below) are called. For
C events, no action is taken. the C events, no action is taken.
The *arg* parameter depends on the previous event. The *arg* parameter depends on the previous event.
For more information on trace functions, see :ref:`debugger-hooks`. For more For more information on trace functions, see :ref:`debugger-hooks`. For
information on code and frame objects, refer to :ref:`types`. more information on code and frame objects, refer to :ref:`types`.
.. method:: Bdb.dispatch_line(frame) .. method:: dispatch_line(frame)
If the debugger should stop on the current line, invoke the :meth:`user_line` If the debugger should stop on the current line, invoke the
method (which should be overridden in subclasses). Raise a :exc:`BdbQuit` :meth:`user_line` method (which should be overridden in subclasses).
exception if the :attr:`Bdb.quitting` flag is set (which can be set from Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
:meth:`user_line`). Return a reference to the :meth:`trace_dispatch` method (which can be set from :meth:`user_line`). Return a reference to the
for further tracing in that scope. :meth:`trace_dispatch` method for further tracing in that scope.
.. method:: Bdb.dispatch_call(frame, arg) .. method:: dispatch_call(frame, arg)
If the debugger should stop on this function call, invoke the If the debugger should stop on this function call, invoke the
:meth:`user_call` method (which should be overridden in subclasses). Raise a :meth:`user_call` method (which should be overridden in subclasses).
:exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
be set from :meth:`user_call`). Return a reference to the (which can be set from :meth:`user_call`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope. :meth:`trace_dispatch` method for further tracing in that scope.
.. method:: Bdb.dispatch_return(frame, arg) .. method:: dispatch_return(frame, arg)
If the debugger should stop on this function return, invoke the If the debugger should stop on this function return, invoke the
:meth:`user_return` method (which should be overridden in subclasses). Raise :meth:`user_return` method (which should be overridden in subclasses).
a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
be set from :meth:`user_return`). Return a reference to the (which can be set from :meth:`user_return`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope. :meth:`trace_dispatch` method for further tracing in that scope.
.. method:: Bdb.dispatch_exception(frame, arg) .. method:: dispatch_exception(frame, arg)
If the debugger should stop at this exception, invokes the If the debugger should stop at this exception, invokes the
:meth:`user_exception` method (which should be overridden in subclasses). :meth:`user_exception` method (which should be overridden in subclasses).
...@@ -140,144 +142,144 @@ The following methods of :class:`Bdb` normally don't need to be overridden. ...@@ -140,144 +142,144 @@ The following methods of :class:`Bdb` normally don't need to be overridden.
(which can be set from :meth:`user_exception`). Return a reference to the (which can be set from :meth:`user_exception`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope. :meth:`trace_dispatch` method for further tracing in that scope.
Normally derived classes don't override the following methods, but they may if Normally derived classes don't override the following methods, but they may
they want to redefine the definition of stopping and breakpoints. if they want to redefine the definition of stopping and breakpoints.
.. method:: Bdb.stop_here(frame) .. method:: stop_here(frame)
This method checks if the *frame* is somewhere below :attr:`botframe` in the This method checks if the *frame* is somewhere below :attr:`botframe` in
call stack. :attr:`botframe` is the frame in which debugging started. the call stack. :attr:`botframe` is the frame in which debugging started.
.. method:: Bdb.break_here(frame) .. method:: break_here(frame)
This method checks if there is a breakpoint in the filename and line This method checks if there is a breakpoint in the filename and line
belonging to *frame* or, at least, in the current function. If the belonging to *frame* or, at least, in the current function. If the
breakpoint is a temporary one, this method deletes it. breakpoint is a temporary one, this method deletes it.
.. method:: Bdb.break_anywhere(frame) .. method:: break_anywhere(frame)
This method checks if there is a breakpoint in the filename of the current This method checks if there is a breakpoint in the filename of the current
frame. frame.
Derived classes should override these methods to gain control over debugger Derived classes should override these methods to gain control over debugger
operation. operation.
.. method:: Bdb.user_call(frame, argument_list) .. method:: user_call(frame, argument_list)
This method is called from :meth:`dispatch_call` when there is the This method is called from :meth:`dispatch_call` when there is the
possibility that a break might be necessary anywhere inside the called possibility that a break might be necessary anywhere inside the called
function. function.
.. method:: Bdb.user_line(frame) .. method:: user_line(frame)
This method is called from :meth:`dispatch_line` when either This method is called from :meth:`dispatch_line` when either
:meth:`stop_here` or :meth:`break_here` yields True. :meth:`stop_here` or :meth:`break_here` yields True.
.. method:: Bdb.user_return(frame, return_value) .. method:: user_return(frame, return_value)
This method is called from :meth:`dispatch_return` when :meth:`stop_here` This method is called from :meth:`dispatch_return` when :meth:`stop_here`
yields True. yields True.
.. method:: Bdb.user_exception(frame, exc_info) .. method:: user_exception(frame, exc_info)
This method is called from :meth:`dispatch_exception` when :meth:`stop_here` This method is called from :meth:`dispatch_exception` when
yields True. :meth:`stop_here` yields True.
.. method:: Bdb.do_clear(arg) .. method:: do_clear(arg)
Handle how a breakpoint must be removed when it is a temporary one. Handle how a breakpoint must be removed when it is a temporary one.
This method must be implemented by derived classes. This method must be implemented by derived classes.
Derived classes and clients can call the following methods to affect the Derived classes and clients can call the following methods to affect the
stepping state. stepping state.
.. method:: Bdb.set_step() .. method:: set_step()
Stop after one line of code. Stop after one line of code.
.. method:: Bdb.set_next(frame) .. method:: set_next(frame)
Stop on the next line in or below the given frame. Stop on the next line in or below the given frame.
.. method:: Bdb.set_return(frame) .. method:: set_return(frame)
Stop when returning from the given frame. Stop when returning from the given frame.
.. method:: Bdb.set_trace([frame]) .. method:: set_trace([frame])
Start debugging from *frame*. If *frame* is not specified, debugging starts Start debugging from *frame*. If *frame* is not specified, debugging
from caller's frame. starts from caller's frame.
.. method:: Bdb.set_continue() .. method:: set_continue()
Stop only at breakpoints or when finished. If there are no breakpoints, set Stop only at breakpoints or when finished. If there are no breakpoints,
the system trace function to None. set the system trace function to None.
.. method:: Bdb.set_quit() .. method:: set_quit()
Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in
the next call to one of the :meth:`dispatch_\*` methods. the next call to one of the :meth:`dispatch_\*` methods.
Derived classes and clients can call the following methods to manipulate Derived classes and clients can call the following methods to manipulate
breakpoints. These methods return a string containing an error message if breakpoints. These methods return a string containing an error message if
something went wrong, or ``None`` if all is well. something went wrong, or ``None`` if all is well.
.. method:: Bdb.set_break(filename, lineno[, temporary=0[, cond[, funcname]]]) .. method:: set_break(filename, lineno[, temporary=0[, cond[, funcname]]])
Set a new breakpoint. If the *lineno* line doesn't exist for the *filename* Set a new breakpoint. If the *lineno* line doesn't exist for the
passed as argument, return an error message. The *filename* should be in *filename* passed as argument, return an error message. The *filename*
canonical form, as described in the :meth:`canonic` method. should be in canonical form, as described in the :meth:`canonic` method.
.. method:: Bdb.clear_break(filename, lineno) .. method:: clear_break(filename, lineno)
Delete the breakpoints in *filename* and *lineno*. If none were set, an Delete the breakpoints in *filename* and *lineno*. If none were set, an
error message is returned. error message is returned.
.. method:: Bdb.clear_bpbynumber(arg) .. method:: clear_bpbynumber(arg)
Delete the breakpoint which has the index *arg* in the Delete the breakpoint which has the index *arg* in the
:attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range, :attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range,
return an error message. return an error message.
.. method:: Bdb.clear_all_file_breaks(filename) .. method:: clear_all_file_breaks(filename)
Delete all breakpoints in *filename*. If none were set, an error message is Delete all breakpoints in *filename*. If none were set, an error message
returned. is returned.
.. method:: Bdb.clear_all_breaks() .. method:: clear_all_breaks()
Delete all existing breakpoints. Delete all existing breakpoints.
.. method:: Bdb.get_break(filename, lineno) .. method:: get_break(filename, lineno)
Check if there is a breakpoint for *lineno* of *filename*. Check if there is a breakpoint for *lineno* of *filename*.
.. method:: Bdb.get_breaks(filename, lineno) .. method:: get_breaks(filename, lineno)
Return all breakpoints for *lineno* in *filename*, or an empty list if none Return all breakpoints for *lineno* in *filename*, or an empty list if
are set. none are set.
.. method:: Bdb.get_file_breaks(filename) .. method:: get_file_breaks(filename)
Return all breakpoints in *filename*, or an empty list if none are set. Return all breakpoints in *filename*, or an empty list if none are set.
.. method:: Bdb.get_all_breaks() .. method:: get_all_breaks()
Return all breakpoints that are set. Return all breakpoints that are set.
Derived classes and clients can call the following methods to get a data Derived classes and clients can call the following methods to get a data
structure representing a stack trace. structure representing a stack trace.
.. method:: Bdb.get_stack(f, t) .. method:: get_stack(f, t)
Get a list of records for a frame and all higher (calling) and lower frames, Get a list of records for a frame and all higher (calling) and lower
and the size of the higher part. frames, and the size of the higher part.
.. method:: Bdb.format_stack_entry(frame_lineno, [lprefix=': ']) .. method:: format_stack_entry(frame_lineno, [lprefix=': '])
Return a string with information about a stack entry, identified by a Return a string with information about a stack entry, identified by a
``(frame, lineno)`` tuple: ``(frame, lineno)`` tuple:
...@@ -289,24 +291,24 @@ structure representing a stack trace. ...@@ -289,24 +291,24 @@ structure representing a stack trace.
* The line of code (if it exists). * The line of code (if it exists).
The following two methods can be called by clients to use a debugger to debug a The following two methods can be called by clients to use a debugger to debug
:term:`statement`, given as a string. a :term:`statement`, given as a string.
.. method:: Bdb.run(cmd, [globals, [locals]]) .. method:: run(cmd, [globals, [locals]])
Debug a statement executed via the :func:`exec` function. *globals* Debug a statement executed via the :func:`exec` function. *globals*
defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*.
.. method:: Bdb.runeval(expr, [globals, [locals]]) .. method:: runeval(expr, [globals, [locals]])
Debug an expression executed via the :func:`eval` function. *globals* and Debug an expression executed via the :func:`eval` function. *globals* and
*locals* have the same meaning as in :meth:`run`. *locals* have the same meaning as in :meth:`run`.
.. method:: Bdb.runctx(cmd, globals, locals) .. method:: runctx(cmd, globals, locals)
For backwards compatibility. Calls the :meth:`run` method. For backwards compatibility. Calls the :meth:`run` method.
.. method:: Bdb.runcall(func, *args, **kwds) .. method:: runcall(func, *args, **kwds)
Debug a single function call, and return its result. Debug a single function call, and return its result.
......
...@@ -46,73 +46,75 @@ Handling of compressed files is offered by the :class:`BZ2File` class. ...@@ -46,73 +46,75 @@ Handling of compressed files is offered by the :class:`BZ2File` class.
Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default)
or writing. When opened for writing, the file will be created if it doesn't or writing. When opened for writing, the file will be created if it doesn't
exist, and truncated otherwise. If *buffering* is given, ``0`` means unbuffered, exist, and truncated otherwise. If *buffering* is given, ``0`` means
and larger numbers specify the buffer size; the default is ``0``. If unbuffered, and larger numbers specify the buffer size; the default is
*compresslevel* is given, it must be a number between ``1`` and ``9``; the ``0``. If *compresslevel* is given, it must be a number between ``1`` and
default is ``9``. Add a ``'U'`` to mode to open the file for input with ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input
universal newline support. Any line ending in the input file will be seen as a with universal newline support. Any line ending in the input file will be
``'\n'`` in Python. Also, a file so opened gains the attribute seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute
:attr:`newlines`; the value for this attribute is one of ``None`` (no newline :attr:`newlines`; the value for this attribute is one of ``None`` (no newline
read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the newline read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the
types seen. Universal newlines are available only when reading. Instances newline types seen. Universal newlines are available only when
support iteration in the same way as normal :class:`file` instances. reading. Instances support iteration in the same way as normal :class:`file`
instances.
.. method:: BZ2File.close() .. method:: close()
Close the file. Sets data attribute :attr:`closed` to true. A closed file cannot Close the file. Sets data attribute :attr:`closed` to true. A closed file
be used for further I/O operations. :meth:`close` may be called more than once cannot be used for further I/O operations. :meth:`close` may be called
without error. more than once without error.
.. method:: BZ2File.read([size]) .. method:: read([size])
Read at most *size* uncompressed bytes, returned as a string. If the *size* Read at most *size* uncompressed bytes, returned as a string. If the
argument is negative or omitted, read until EOF is reached. *size* argument is negative or omitted, read until EOF is reached.
.. method:: BZ2File.readline([size]) .. method:: readline([size])
Return the next line from the file, as a string, retaining newline. A Return the next line from the file, as a string, retaining newline. A
non-negative *size* argument limits the maximum number of bytes to return (an non-negative *size* argument limits the maximum number of bytes to return
incomplete line may be returned then). Return an empty string at EOF. (an incomplete line may be returned then). Return an empty string at EOF.
.. method:: BZ2File.readlines([size]) .. method:: readlines([size])
Return a list of lines read. The optional *size* argument, if given, is an Return a list of lines read. The optional *size* argument, if given, is an
approximate bound on the total number of bytes in the lines returned. approximate bound on the total number of bytes in the lines returned.
.. method:: BZ2File.seek(offset[, whence]) .. method:: seek(offset[, whence])
Move to new file position. Argument *offset* is a byte count. Optional argument Move to new file position. Argument *offset* is a byte count. Optional
*whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start of file; offset argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start
should be ``>= 0``); other values are ``os.SEEK_CUR`` or ``1`` (move relative to of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or
current position; offset can be positive or negative), and ``os.SEEK_END`` or ``1`` (move relative to current position; offset can be positive or
``2`` (move relative to end of file; offset is usually negative, although many negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file;
platforms allow seeking beyond the end of a file). offset is usually negative, although many platforms allow seeking beyond
the end of a file).
Note that seeking of bz2 files is emulated, and depending on the parameters the Note that seeking of bz2 files is emulated, and depending on the
operation may be extremely slow. parameters the operation may be extremely slow.
.. method:: BZ2File.tell() .. method:: tell()
Return the current file position, an integer. Return the current file position, an integer.
.. method:: BZ2File.write(data) .. method:: write(data)
Write string *data* to file. Note that due to buffering, :meth:`close` may be Write string *data* to file. Note that due to buffering, :meth:`close` may
needed before the file on disk reflects the data written. be needed before the file on disk reflects the data written.
.. method:: BZ2File.writelines(sequence_of_strings) .. method:: writelines(sequence_of_strings)
Write the sequence of strings to the file. Note that newlines are not added. The Write the sequence of strings to the file. Note that newlines are not
sequence can be any iterable object producing strings. This is equivalent to added. The sequence can be any iterable object producing strings. This is
calling write() for each string. equivalent to calling write() for each string.
Sequential (de)compression Sequential (de)compression
...@@ -125,23 +127,23 @@ Sequential compression and decompression is done using the classes ...@@ -125,23 +127,23 @@ Sequential compression and decompression is done using the classes
.. class:: BZ2Compressor([compresslevel]) .. class:: BZ2Compressor([compresslevel])
Create a new compressor object. This object may be used to compress data Create a new compressor object. This object may be used to compress data
sequentially. If you want to compress data in one shot, use the :func:`compress` sequentially. If you want to compress data in one shot, use the
function instead. The *compresslevel* parameter, if given, must be a number :func:`compress` function instead. The *compresslevel* parameter, if given,
between ``1`` and ``9``; the default is ``9``. must be a number between ``1`` and ``9``; the default is ``9``.
.. method:: BZ2Compressor.compress(data) .. method:: compress(data)
Provide more data to the compressor object. It will return chunks of compressed Provide more data to the compressor object. It will return chunks of
data whenever possible. When you've finished providing data to compress, call compressed data whenever possible. When you've finished providing data to
the :meth:`flush` method to finish the compression process, and return what is compress, call the :meth:`flush` method to finish the compression process,
left in internal buffers. and return what is left in internal buffers.
.. method:: BZ2Compressor.flush() .. method:: flush()
Finish the compression process and return what is left in internal buffers. You Finish the compression process and return what is left in internal
must not use the compressor object after calling this method. buffers. You must not use the compressor object after calling this method.
.. class:: BZ2Decompressor() .. class:: BZ2Decompressor()
...@@ -151,12 +153,13 @@ Sequential compression and decompression is done using the classes ...@@ -151,12 +153,13 @@ Sequential compression and decompression is done using the classes
:func:`decompress` function instead. :func:`decompress` function instead.
.. method:: BZ2Decompressor.decompress(data) .. method:: decompress(data)
Provide more data to the decompressor object. It will return chunks of Provide more data to the decompressor object. It will return chunks of
decompressed data whenever possible. If you try to decompress data after the end decompressed data whenever possible. If you try to decompress data after
of stream is found, :exc:`EOFError` will be raised. If any data was found after the end of stream is found, :exc:`EOFError` will be raised. If any data
the end of stream, it'll be ignored and saved in :attr:`unused_data` attribute. was found after the end of stream, it'll be ignored and saved in
:attr:`unused_data` attribute.
One-shot (de)compression One-shot (de)compression
...@@ -168,13 +171,13 @@ and :func:`decompress` functions. ...@@ -168,13 +171,13 @@ and :func:`decompress` functions.
.. function:: compress(data[, compresslevel]) .. function:: compress(data[, compresslevel])
Compress *data* in one shot. If you want to compress data sequentially, use an Compress *data* in one shot. If you want to compress data sequentially, use
instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, if an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter,
given, must be a number between ``1`` and ``9``; the default is ``9``. if given, must be a number between ``1`` and ``9``; the default is ``9``.
.. function:: decompress(data) .. function:: decompress(data)
Decompress *data* in one shot. If you want to decompress data sequentially, use Decompress *data* in one shot. If you want to decompress data sequentially,
an instance of :class:`BZ2Decompressor` instead. use an instance of :class:`BZ2Decompressor` instead.
...@@ -33,70 +33,71 @@ it's the base calendar for all computations. ...@@ -33,70 +33,71 @@ it's the base calendar for all computations.
itself. This is the job of subclasses. itself. This is the job of subclasses.
:class:`Calendar` instances have the following methods: :class:`Calendar` instances have the following methods:
.. method:: Calendar.iterweekdays(weekday) .. method:: iterweekdays(weekday)
Return an iterator for the week day numbers that will be used for one week. Return an iterator for the week day numbers that will be used for one
The first value from the iterator will be the same as the value of the week. The first value from the iterator will be the same as the value of
:attr:`firstweekday` property. the :attr:`firstweekday` property.
.. method:: Calendar.itermonthdates(year, month) .. method:: itermonthdates(year, month)
Return an iterator for the month *month* (1-12) in the year *year*. This Return an iterator for the month *month* (1-12) in the year *year*. This
iterator will return all days (as :class:`datetime.date` objects) for the month iterator will return all days (as :class:`datetime.date` objects) for the
and all days before the start of the month or after the end of the month that month and all days before the start of the month or after the end of the
are required to get a complete week. month that are required to get a complete week.
.. method:: Calendar.itermonthdays2(year, month) .. method:: itermonthdays2(year, month)
Return an iterator for the month *month* in the year *year* similar to Return an iterator for the month *month* in the year *year* similar to
:meth:`itermonthdates`. Days returned will be tuples consisting of a day number :meth:`itermonthdates`. Days returned will be tuples consisting of a day
and a week day number. number and a week day number.
.. method:: Calendar.itermonthdays(year, month) .. method:: itermonthdays(year, month)
Return an iterator for the month *month* in the year *year* similar to Return an iterator for the month *month* in the year *year* similar to
:meth:`itermonthdates`. Days returned will simply be day numbers. :meth:`itermonthdates`. Days returned will simply be day numbers.
.. method:: Calendar.monthdatescalendar(year, month) .. method:: monthdatescalendar(year, month)
Return a list of the weeks in the month *month* of the *year* as full weeks. Return a list of the weeks in the month *month* of the *year* as full
Weeks are lists of seven :class:`datetime.date` objects. weeks. Weeks are lists of seven :class:`datetime.date` objects.
.. method:: Calendar.monthdays2calendar(year, month) .. method:: monthdays2calendar(year, month)
Return a list of the weeks in the month *month* of the *year* as full weeks. Return a list of the weeks in the month *month* of the *year* as full
Weeks are lists of seven tuples of day numbers and weekday numbers. weeks. Weeks are lists of seven tuples of day numbers and weekday
numbers.
.. method:: Calendar.monthdayscalendar(year, month) .. method:: monthdayscalendar(year, month)
Return a list of the weeks in the month *month* of the *year* as full weeks. Return a list of the weeks in the month *month* of the *year* as full
Weeks are lists of seven day numbers. weeks. Weeks are lists of seven day numbers.
.. method:: Calendar.yeardatescalendar(year[, width]) .. method:: yeardatescalendar(year[, width])
Return the data for the specified year ready for formatting. The return value Return the data for the specified year ready for formatting. The return
is a list of month rows. Each month row contains up to *width* months value is a list of month rows. Each month row contains up to *width*
(defaulting to 3). Each month contains between 4 and 6 weeks and each week months (defaulting to 3). Each month contains between 4 and 6 weeks and
contains 1--7 days. Days are :class:`datetime.date` objects. each week contains 1--7 days. Days are :class:`datetime.date` objects.
.. method:: Calendar.yeardays2calendar(year[, width]) .. method:: yeardays2calendar(year[, width])
Return the data for the specified year ready for formatting (similar to Return the data for the specified year ready for formatting (similar to
:meth:`yeardatescalendar`). Entries in the week lists are tuples of day :meth:`yeardatescalendar`). Entries in the week lists are tuples of day
numbers and weekday numbers. Day numbers outside this month are zero. numbers and weekday numbers. Day numbers outside this month are zero.
.. method:: Calendar.yeardayscalendar(year[, width]) .. method:: yeardayscalendar(year[, width])
Return the data for the specified year ready for formatting (similar to Return the data for the specified year ready for formatting (similar to
:meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day
...@@ -108,33 +109,33 @@ it's the base calendar for all computations. ...@@ -108,33 +109,33 @@ it's the base calendar for all computations.
This class can be used to generate plain text calendars. This class can be used to generate plain text calendars.
:class:`TextCalendar` instances have the following methods: :class:`TextCalendar` instances have the following methods:
.. method:: TextCalendar.formatmonth(theyear, themonth[, w[, l]]) .. method:: formatmonth(theyear, themonth[, w[, l]])
Return a month's calendar in a multi-line string. If *w* is provided, it Return a month's calendar in a multi-line string. If *w* is provided, it
specifies the width of the date columns, which are centered. If *l* is given, specifies the width of the date columns, which are centered. If *l* is
it specifies the number of lines that each week will use. Depends on the given, it specifies the number of lines that each week will use. Depends
first weekday as specified in the constructor or set by the on the first weekday as specified in the constructor or set by the
:meth:`setfirstweekday` method. :meth:`setfirstweekday` method.
.. method:: TextCalendar.prmonth(theyear, themonth[, w[, l]]) .. method:: prmonth(theyear, themonth[, w[, l]])
Print a month's calendar as returned by :meth:`formatmonth`. Print a month's calendar as returned by :meth:`formatmonth`.
.. method:: TextCalendar.formatyear(theyear, themonth[, w[, l[, c[, m]]]]) .. method:: formatyear(theyear, themonth[, w[, l[, c[, m]]]])
Return a *m*-column calendar for an entire year as a multi-line string. Return a *m*-column calendar for an entire year as a multi-line string.
Optional parameters *w*, *l*, and *c* are for date column width, lines per Optional parameters *w*, *l*, and *c* are for date column width, lines per
week, and number of spaces between month columns, respectively. Depends on week, and number of spaces between month columns, respectively. Depends on
the first weekday as specified in the constructor or set by the the first weekday as specified in the constructor or set by the
:meth:`setfirstweekday` method. The earliest year for which a calendar can :meth:`setfirstweekday` method. The earliest year for which a calendar
be generated is platform-dependent. can be generated is platform-dependent.
.. method:: TextCalendar.pryear(theyear[, w[, l[, c[, m]]]]) .. method:: pryear(theyear[, w[, l[, c[, m]]]])
Print the calendar for an entire year as returned by :meth:`formatyear`. Print the calendar for an entire year as returned by :meth:`formatyear`.
...@@ -144,43 +145,44 @@ it's the base calendar for all computations. ...@@ -144,43 +145,44 @@ it's the base calendar for all computations.
This class can be used to generate HTML calendars. This class can be used to generate HTML calendars.
:class:`HTMLCalendar` instances have the following methods: :class:`HTMLCalendar` instances have the following methods:
.. method:: HTMLCalendar.formatmonth(theyear, themonth[, withyear]) .. method:: formatmonth(theyear, themonth[, withyear])
Return a month's calendar as an HTML table. If *withyear* is true the year will Return a month's calendar as an HTML table. If *withyear* is true the year
be included in the header, otherwise just the month name will be used. will be included in the header, otherwise just the month name will be
used.
.. method:: HTMLCalendar.formatyear(theyear, themonth[, width]) .. method:: formatyear(theyear, themonth[, width])
Return a year's calendar as an HTML table. *width* (defaulting to 3) specifies Return a year's calendar as an HTML table. *width* (defaulting to 3)
the number of months per row. specifies the number of months per row.
.. method:: HTMLCalendar.formatyearpage(theyear[, width[, css[, encoding]]]) .. method:: formatyearpage(theyear[, width[, css[, encoding]]])
Return a year's calendar as a complete HTML page. *width* (defaulting to 3) Return a year's calendar as a complete HTML page. *width* (defaulting to
specifies the number of months per row. *css* is the name for the cascading 3) specifies the number of months per row. *css* is the name for the
style sheet to be used. :const:`None` can be passed if no style sheet should be cascading style sheet to be used. :const:`None` can be passed if no style
used. *encoding* specifies the encoding to be used for the output (defaulting to sheet should be used. *encoding* specifies the encoding to be used for the
the system default encoding). output (defaulting to the system default encoding).
.. class:: LocaleTextCalendar([firstweekday[, locale]]) .. class:: LocaleTextCalendar([firstweekday[, locale]])
This subclass of :class:`TextCalendar` can be passed a locale name in the This subclass of :class:`TextCalendar` can be passed a locale name in the
constructor and will return month and weekday names in the specified locale. If constructor and will return month and weekday names in the specified
this locale includes an encoding all strings containing month and weekday names locale. If this locale includes an encoding all strings containing month and
will be returned as unicode. weekday names will be returned as unicode.
.. class:: LocaleHTMLCalendar([firstweekday[, locale]]) .. class:: LocaleHTMLCalendar([firstweekday[, locale]])
This subclass of :class:`HTMLCalendar` can be passed a locale name in the This subclass of :class:`HTMLCalendar` can be passed a locale name in the
constructor and will return month and weekday names in the specified locale. If constructor and will return month and weekday names in the specified
this locale includes an encoding all strings containing month and weekday names locale. If this locale includes an encoding all strings containing month and
will be returned as unicode. weekday names will be returned as unicode.
For simple text calendars this module provides the following functions. For simple text calendars this module provides the following functions.
......
...@@ -43,22 +43,22 @@ The :mod:`CGIHTTPServer` module defines the following class: ...@@ -43,22 +43,22 @@ The :mod:`CGIHTTPServer` module defines the following class:
and serve the output, instead of serving files, if the request leads to and serve the output, instead of serving files, if the request leads to
somewhere below the ``cgi_directories`` path. somewhere below the ``cgi_directories`` path.
The :class:`CGIHTTPRequestHandler` defines the following data member: The :class:`CGIHTTPRequestHandler` defines the following data member:
.. attribute:: CGIHTTPRequestHandler.cgi_directories .. attribute:: cgi_directories
This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to treat This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
as containing CGI scripts. treat as containing CGI scripts.
The :class:`CGIHTTPRequestHandler` defines the following methods: The :class:`CGIHTTPRequestHandler` defines the following methods:
.. method:: CGIHTTPRequestHandler.do_POST() .. method:: do_POST()
This method serves the ``'POST'`` request type, only allowed for CGI scripts. This method serves the ``'POST'`` request type, only allowed for CGI
Error 501, "Can only POST to CGI scripts", is output when trying to POST to a scripts. Error 501, "Can only POST to CGI scripts", is output when trying
non-CGI url. to POST to a non-CGI url.
Note that CGI scripts will be run with UID of user nobody, for security reasons. Note that CGI scripts will be run with UID of user nobody, for security reasons.
Problems with the CGI script will be translated to error 403. Problems with the CGI script will be translated to error 403.
......
...@@ -66,62 +66,64 @@ instance will fail with a :exc:`EOFError` exception. ...@@ -66,62 +66,64 @@ instance will fail with a :exc:`EOFError` exception.
optional argument *inclheader* is true, the size given in the chunk header optional argument *inclheader* is true, the size given in the chunk header
includes the size of the header. The default value is false. includes the size of the header. The default value is false.
A :class:`Chunk` object supports the following methods: A :class:`Chunk` object supports the following methods:
.. method:: Chunk.getname() .. method:: getname()
Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. Returns the name (ID) of the chunk. This is the first 4 bytes of the
chunk.
.. method:: Chunk.getsize() .. method:: getsize()
Returns the size of the chunk. Returns the size of the chunk.
.. method:: Chunk.close() .. method:: close()
Close and skip to the end of the chunk. This does not close the underlying Close and skip to the end of the chunk. This does not close the
file. underlying file.
The remaining methods will raise :exc:`IOError` if called after the The remaining methods will raise :exc:`IOError` if called after the
:meth:`close` method has been called. :meth:`close` method has been called.
.. method:: Chunk.isatty() .. method:: isatty()
Returns ``False``. Returns ``False``.
.. method:: Chunk.seek(pos[, whence]) .. method:: seek(pos[, whence])
Set the chunk's current position. The *whence* argument is optional and Set the chunk's current position. The *whence* argument is optional and
defaults to ``0`` (absolute file positioning); other values are ``1`` (seek defaults to ``0`` (absolute file positioning); other values are ``1``
relative to the current position) and ``2`` (seek relative to the file's end). (seek relative to the current position) and ``2`` (seek relative to the
There is no return value. If the underlying file does not allow seek, only file's end). There is no return value. If the underlying file does not
forward seeks are allowed. allow seek, only forward seeks are allowed.
.. method:: Chunk.tell() .. method:: tell()
Return the current position into the chunk. Return the current position into the chunk.
.. method:: Chunk.read([size]) .. method:: read([size])
Read at most *size* bytes from the chunk (less if the read hits the end of the Read at most *size* bytes from the chunk (less if the read hits the end of
chunk before obtaining *size* bytes). If the *size* argument is negative or the chunk before obtaining *size* bytes). If the *size* argument is
omitted, read all data until the end of the chunk. The bytes are returned as a negative or omitted, read all data until the end of the chunk. The bytes
string object. An empty string is returned when the end of the chunk is are returned as a string object. An empty string is returned when the end
encountered immediately. of the chunk is encountered immediately.
.. method:: Chunk.skip() .. method:: skip()
Skip to the end of the chunk. All further calls to :meth:`read` for the
chunk will return ``''``. If you are not interested in the contents of
the chunk, this method should be called so that the file points to the
start of the next chunk.
Skip to the end of the chunk. All further calls to :meth:`read` for the chunk
will return ``''``. If you are not interested in the contents of the chunk,
this method should be called so that the file points to the start of the next
chunk.
.. rubric:: Footnotes .. rubric:: Footnotes
......
...@@ -425,14 +425,14 @@ define in order to be compatible with the Python codec registry. ...@@ -425,14 +425,14 @@ define in order to be compatible with the Python codec registry.
:func:`register_error`. :func:`register_error`.
.. method:: IncrementalEncoder.encode(object[, final]) .. method:: encode(object[, final])
Encodes *object* (taking the current state of the encoder into account) and Encodes *object* (taking the current state of the encoder into account)
returns the resulting encoded object. If this is the last call to :meth:`encode` and returns the resulting encoded object. If this is the last call to
*final* must be true (the default is false). :meth:`encode` *final* must be true (the default is false).
.. method:: IncrementalEncoder.reset() .. method:: reset()
Reset the encoder to the initial state. Reset the encoder to the initial state.
...@@ -488,42 +488,43 @@ define in order to be compatible with the Python codec registry. ...@@ -488,42 +488,43 @@ define in order to be compatible with the Python codec registry.
:func:`register_error`. :func:`register_error`.
.. method:: IncrementalDecoder.decode(object[, final]) .. method:: decode(object[, final])
Decodes *object* (taking the current state of the decoder into account) and Decodes *object* (taking the current state of the decoder into account)
returns the resulting decoded object. If this is the last call to :meth:`decode` and returns the resulting decoded object. If this is the last call to
*final* must be true (the default is false). If *final* is true the decoder must :meth:`decode` *final* must be true (the default is false). If *final* is
decode the input completely and must flush all buffers. If this isn't possible true the decoder must decode the input completely and must flush all
(e.g. because of incomplete byte sequences at the end of the input) it must buffers. If this isn't possible (e.g. because of incomplete byte sequences
initiate error handling just like in the stateless case (which might raise an at the end of the input) it must initiate error handling just like in the
exception). stateless case (which might raise an exception).
.. method:: IncrementalDecoder.reset() .. method:: reset()
Reset the decoder to the initial state. Reset the decoder to the initial state.
.. method:: IncrementalDecoder.getstate() .. method:: getstate()
Return the current state of the decoder. This must be a tuple with two items, Return the current state of the decoder. This must be a tuple with two
the first must be the buffer containing the still undecoded input. The second items, the first must be the buffer containing the still undecoded
must be an integer and can be additional state info. (The implementation should input. The second must be an integer and can be additional state
make sure that ``0`` is the most common additional state info.) If this info. (The implementation should make sure that ``0`` is the most common
additional state info is ``0`` it must be possible to set the decoder to the additional state info.) If this additional state info is ``0`` it must be
state which has no input buffered and ``0`` as the additional state info, so possible to set the decoder to the state which has no input buffered and
that feeding the previously buffered input to the decoder returns it to the ``0`` as the additional state info, so that feeding the previously
previous state without producing any output. (Additional state info that is more buffered input to the decoder returns it to the previous state without
complicated than integers can be converted into an integer by producing any output. (Additional state info that is more complicated than
marshaling/pickling the info and encoding the bytes of the resulting string into integers can be converted into an integer by marshaling/pickling the info
an integer.) and encoding the bytes of the resulting string into an integer.)
.. method:: IncrementalDecoder.setstate(state) .. method:: setstate(state)
Set the state of the encoder to *state*. *state* must be a decoder state Set the state of the encoder to *state*. *state* must be a decoder state
returned by :meth:`getstate`. returned by :meth:`getstate`.
The :class:`StreamWriter` and :class:`StreamReader` classes provide generic The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
working interfaces which can be used to implement new encoding submodules very working interfaces which can be used to implement new encoding submodules very
easily. See :mod:`encodings.utf_8` for an example of how this is done. easily. See :mod:`encodings.utf_8` for an example of how this is done.
...@@ -570,24 +571,25 @@ compatible with the Python codec registry. ...@@ -570,24 +571,25 @@ compatible with the Python codec registry.
:func:`register_error`. :func:`register_error`.
.. method:: StreamWriter.write(object) .. method:: write(object)
Writes the object's contents encoded to the stream. Writes the object's contents encoded to the stream.
.. method:: StreamWriter.writelines(list) .. method:: writelines(list)
Writes the concatenated list of strings to the stream (possibly by reusing the Writes the concatenated list of strings to the stream (possibly by reusing
:meth:`write` method). the :meth:`write` method).
.. method:: StreamWriter.reset() .. method:: reset()
Flushes and resets the codec buffers used for keeping state. Flushes and resets the codec buffers used for keeping state.
Calling this method should ensure that the data on the output is put into a Calling this method should ensure that the data on the output is put into
clean state that allows appending of new fresh data without having to rescan the a clean state that allows appending of new fresh data without having to
whole stream to recover state. rescan the whole stream to recover state.
In addition to the above methods, the :class:`StreamWriter` must also inherit In addition to the above methods, the :class:`StreamWriter` must also inherit
all other methods and attributes from the underlying stream. all other methods and attributes from the underlying stream.
...@@ -630,55 +632,59 @@ compatible with the Python codec registry. ...@@ -630,55 +632,59 @@ compatible with the Python codec registry.
:func:`register_error`. :func:`register_error`.
.. method:: StreamReader.read([size[, chars, [firstline]]]) .. method:: read([size[, chars, [firstline]]])
Decodes data from the stream and returns the resulting object. Decodes data from the stream and returns the resulting object.
*chars* indicates the number of characters to read from the stream. :func:`read` *chars* indicates the number of characters to read from the
will never return more than *chars* characters, but it might return less, if stream. :func:`read` will never return more than *chars* characters, but
there are not enough characters available. it might return less, if there are not enough characters available.
*size* indicates the approximate maximum number of bytes to read from the stream *size* indicates the approximate maximum number of bytes to read from the
for decoding purposes. The decoder can modify this setting as appropriate. The stream for decoding purposes. The decoder can modify this setting as
default value -1 indicates to read and decode as much as possible. *size* is appropriate. The default value -1 indicates to read and decode as much as
intended to prevent having to decode huge files in one step. possible. *size* is intended to prevent having to decode huge files in
one step.
*firstline* indicates that it would be sufficient to only return the first line, *firstline* indicates that it would be sufficient to only return the first
if there are decoding errors on later lines. line, if there are decoding errors on later lines.
The method should use a greedy read strategy meaning that it should read as much The method should use a greedy read strategy meaning that it should read
data as is allowed within the definition of the encoding and the given size, as much data as is allowed within the definition of the encoding and the
e.g. if optional encoding endings or state markers are available on the stream, given size, e.g. if optional encoding endings or state markers are
these should be read too. available on the stream, these should be read too.
.. method:: StreamReader.readline([size[, keepends]]) .. method:: readline([size[, keepends]])
Read one line from the input stream and return the decoded data. Read one line from the input stream and return the decoded data.
*size*, if given, is passed as size argument to the stream's :meth:`readline` *size*, if given, is passed as size argument to the stream's
method. :meth:`readline` method.
If *keepends* is false line-endings will be stripped from the lines returned. If *keepends* is false line-endings will be stripped from the lines
returned.
.. method:: StreamReader.readlines([sizehint[, keepends]]) .. method:: readlines([sizehint[, keepends]])
Read all lines available on the input stream and return them as a list of lines. Read all lines available on the input stream and return them as a list of
lines.
Line-endings are implemented using the codec's decoder method and are included Line-endings are implemented using the codec's decoder method and are
in the list entries if *keepends* is true. included in the list entries if *keepends* is true.
*sizehint*, if given, is passed as the *size* argument to the stream's *sizehint*, if given, is passed as the *size* argument to the stream's
:meth:`read` method. :meth:`read` method.
.. method:: StreamReader.reset() .. method:: reset()
Resets the codec buffers used for keeping state. Resets the codec buffers used for keeping state.
Note that no stream repositioning should take place. This method is primarily Note that no stream repositioning should take place. This method is
intended to be able to recover from decoding errors. primarily intended to be able to recover from decoding errors.
In addition to the above methods, the :class:`StreamReader` must also inherit In addition to the above methods, the :class:`StreamReader` must also inherit
all other methods and attributes from the underlying stream. all other methods and attributes from the underlying stream.
...@@ -747,6 +753,7 @@ The design is such that one can use the factory functions returned by the ...@@ -747,6 +753,7 @@ The design is such that one can use the factory functions returned by the
Error handling is done in the same way as defined for the stream readers and Error handling is done in the same way as defined for the stream readers and
writers. writers.
:class:`StreamRecoder` instances define the combined interfaces of :class:`StreamRecoder` instances define the combined interfaces of
:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other :class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
methods and attributes from the underlying stream. methods and attributes from the underlying stream.
......
...@@ -166,60 +166,61 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin: ...@@ -166,60 +166,61 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
where only the most recent activity is of interest. where only the most recent activity is of interest.
Deque objects support the following methods: Deque objects support the following methods:
.. method:: deque.append(x) .. method:: append(x)
Add *x* to the right side of the deque. Add *x* to the right side of the deque.
.. method:: deque.appendleft(x) .. method:: appendleft(x)
Add *x* to the left side of the deque. Add *x* to the left side of the deque.
.. method:: deque.clear() .. method:: clear()
Remove all elements from the deque leaving it with length 0. Remove all elements from the deque leaving it with length 0.
.. method:: deque.extend(iterable) .. method:: extend(iterable)
Extend the right side of the deque by appending elements from the iterable Extend the right side of the deque by appending elements from the iterable
argument. argument.
.. method:: deque.extendleft(iterable) .. method:: extendleft(iterable)
Extend the left side of the deque by appending elements from *iterable*. Note, Extend the left side of the deque by appending elements from *iterable*.
the series of left appends results in reversing the order of elements in the Note, the series of left appends results in reversing the order of
iterable argument. elements in the iterable argument.
.. method:: deque.pop() .. method:: pop()
Remove and return an element from the right side of the deque. If no elements Remove and return an element from the right side of the deque. If no
are present, raises an :exc:`IndexError`. elements are present, raises an :exc:`IndexError`.
.. method:: deque.popleft() .. method:: popleft()
Remove and return an element from the left side of the deque. If no elements are Remove and return an element from the left side of the deque. If no
present, raises an :exc:`IndexError`. elements are present, raises an :exc:`IndexError`.
.. method:: deque.remove(value) .. method:: remove(value)
Removed the first occurrence of *value*. If not found, raises a Removed the first occurrence of *value*. If not found, raises a
:exc:`ValueError`. :exc:`ValueError`.
.. method:: deque.rotate(n) .. method:: rotate(n)
Rotate the deque *n* steps to the right. If *n* is negative, rotate to the Rotate the deque *n* steps to the right. If *n* is negative, rotate to
left. Rotating one step to the right is equivalent to: the left. Rotating one step to the right is equivalent to:
``d.appendleft(d.pop())``. ``d.appendleft(d.pop())``.
In addition to the above, deques support iteration, pickling, ``len(d)``, In addition to the above, deques support iteration, pickling, ``len(d)``,
``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
the :keyword:`in` operator, and subscript references such as ``d[-1]``. the :keyword:`in` operator, and subscript references such as ``d[-1]``.
...@@ -348,32 +349,34 @@ in Unix:: ...@@ -348,32 +349,34 @@ in Unix::
arguments. arguments.
:class:`defaultdict` objects support the following method in addition to the :class:`defaultdict` objects support the following method in addition to the
standard :class:`dict` operations: standard :class:`dict` operations:
.. method:: defaultdict.__missing__(key) .. method:: defaultdict.__missing__(key)
If the :attr:`default_factory` attribute is ``None``, this raises an If the :attr:`default_factory` attribute is ``None``, this raises an
:exc:`KeyError` exception with the *key* as argument. :exc:`KeyError` exception with the *key* as argument.
If :attr:`default_factory` is not ``None``, it is called without arguments to If :attr:`default_factory` is not ``None``, it is called without arguments
provide a default value for the given *key*, this value is inserted in the to provide a default value for the given *key*, this value is inserted in
dictionary for the *key*, and returned. the dictionary for the *key*, and returned.
If calling :attr:`default_factory` raises an exception this exception is If calling :attr:`default_factory` raises an exception this exception is
propagated unchanged. propagated unchanged.
This method is called by the :meth:`__getitem__` method of the :class:`dict` This method is called by the :meth:`__getitem__` method of the
class when the requested key is not found; whatever it returns or raises is then :class:`dict` class when the requested key is not found; whatever it
returned or raised by :meth:`__getitem__`. returns or raises is then returned or raised by :meth:`__getitem__`.
:class:`defaultdict` objects support the following instance variable: :class:`defaultdict` objects support the following instance variable:
.. attribute:: defaultdict.default_factory .. attribute:: defaultdict.default_factory
This attribute is used by the :meth:`__missing__` method; it is initialized from This attribute is used by the :meth:`__missing__` method; it is
the first argument to the constructor, if present, or to ``None``, if absent. initialized from the first argument to the constructor, if present, or to
``None``, if absent.
.. _defaultdict-examples: .. _defaultdict-examples:
......
...@@ -209,19 +209,20 @@ The :mod:`csv` module defines the following classes: ...@@ -209,19 +209,20 @@ The :mod:`csv` module defines the following classes:
The :class:`Sniffer` class is used to deduce the format of a CSV file. The :class:`Sniffer` class is used to deduce the format of a CSV file.
The :class:`Sniffer` class provides two methods: The :class:`Sniffer` class provides two methods:
.. method:: Sniffer.sniff(sample[, delimiters=None]) .. method:: sniff(sample[, delimiters=None])
Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the Analyze the given *sample* and return a :class:`Dialect` subclass
parameters found. If the optional *delimiters* parameter is given, it is reflecting the parameters found. If the optional *delimiters* parameter
interpreted as a string containing possible valid delimiter characters. is given, it is interpreted as a string containing possible valid
delimiter characters.
.. method:: Sniffer.has_header(sample) .. method:: has_header(sample)
Analyze the sample text (presumed to be in CSV format) and return :const:`True` Analyze the sample text (presumed to be in CSV format) and return
if the first row appears to be a series of column headers. :const:`True` if the first row appears to be a series of column headers.
An example for :class:`Sniffer` use:: An example for :class:`Sniffer` use::
......
...@@ -1441,7 +1441,7 @@ loader instance. ...@@ -1441,7 +1441,7 @@ loader instance.
so repeated attribute accesses return the same library each time. so repeated attribute accesses return the same library each time.
.. method:: LibraryLoader.LoadLibrary(name) .. method:: LoadLibrary(name)
Load a shared library into the process and return it. This method always Load a shared library into the process and return it. This method always
returns a new instance of the library. returns a new instance of the library.
...@@ -1501,50 +1501,51 @@ They are instances of a private class: ...@@ -1501,50 +1501,51 @@ They are instances of a private class:
Base class for C callable foreign functions. Base class for C callable foreign functions.
Instances of foreign functions are also C compatible data types; they represent Instances of foreign functions are also C compatible data types; they
C function pointers. represent C function pointers.
This behavior can be customized by assigning to special attributes of the This behavior can be customized by assigning to special attributes of the
foreign function object. foreign function object.
.. attribute:: _FuncPtr.restype .. attribute:: restype
Assign a ctypes type to specify the result type of the foreign function. Use Assign a ctypes type to specify the result type of the foreign function.
``None`` for ``void`` a function not returning anything. Use ``None`` for ``void`` a function not returning anything.
It is possible to assign a callable Python object that is not a ctypes type, in It is possible to assign a callable Python object that is not a ctypes
this case the function is assumed to return a C ``int``, and the callable will type, in this case the function is assumed to return a C ``int``, and the
be called with this integer, allowing to do further processing or error callable will be called with this integer, allowing to do further
checking. Using this is deprecated, for more flexible post processing or error processing or error checking. Using this is deprecated, for more flexible
checking use a ctypes data type as :attr:`restype` and assign a callable to the post processing or error checking use a ctypes data type as
:attr:`errcheck` attribute. :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.
.. attribute:: _FuncPtr.argtypes .. attribute:: argtypes
Assign a tuple of ctypes types to specify the argument types that the function Assign a tuple of ctypes types to specify the argument types that the
accepts. Functions using the ``stdcall`` calling convention can only be called function accepts. Functions using the ``stdcall`` calling convention can
with the same number of arguments as the length of this tuple; functions using only be called with the same number of arguments as the length of this
the C calling convention accept additional, unspecified arguments as well. tuple; functions using the C calling convention accept additional,
unspecified arguments as well.
When a foreign function is called, each actual argument is passed to the When a foreign function is called, each actual argument is passed to the
:meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this :meth:`from_param` class method of the items in the :attr:`argtypes`
method allows to adapt the actual argument to an object that the foreign tuple, this method allows to adapt the actual argument to an object that
function accepts. For example, a :class:`c_char_p` item in the :attr:`argtypes` the foreign function accepts. For example, a :class:`c_char_p` item in
tuple will convert a unicode string passed as argument into an byte string using the :attr:`argtypes` tuple will convert a unicode string passed as
ctypes conversion rules. argument into an byte string using ctypes conversion rules.
New: It is now possible to put items in argtypes which are not ctypes types, but New: It is now possible to put items in argtypes which are not ctypes
each item must have a :meth:`from_param` method which returns a value usable as types, but each item must have a :meth:`from_param` method which returns a
argument (integer, string, ctypes instance). This allows to define adapters value usable as argument (integer, string, ctypes instance). This allows
that can adapt custom objects as function parameters. to define adapters that can adapt custom objects as function parameters.
.. attribute:: _FuncPtr.errcheck .. attribute:: errcheck
Assign a Python function or another callable to this attribute. The callable Assign a Python function or another callable to this attribute. The
will be called with three or more arguments: callable will be called with three or more arguments:
.. function:: callable(result, func, arguments) .. function:: callable(result, func, arguments)
...@@ -1559,9 +1560,9 @@ foreign function object. ...@@ -1559,9 +1560,9 @@ foreign function object.
``arguments`` is a tuple containing the parameters originally passed to the ``arguments`` is a tuple containing the parameters originally passed to the
function call, this allows to specialize the behavior on the arguments used. function call, this allows to specialize the behavior on the arguments used.
The object that this function returns will be returned from the foreign function The object that this function returns will be returned from the foreign
call, but it can also check the result value and raise an exception if the function call, but it can also check the result value and raise an exception
foreign function call failed. if the foreign function call failed.
.. exception:: ArgumentError() .. exception:: ArgumentError()
...@@ -1943,57 +1944,58 @@ Data types ...@@ -1943,57 +1944,58 @@ Data types
:attr:`_objects`; this contains other Python objects that need to be kept alive :attr:`_objects`; this contains other Python objects that need to be kept alive
in case the memory block contains pointers. in case the memory block contains pointers.
Common methods of ctypes data types, these are all class methods (to be exact, Common methods of ctypes data types, these are all class methods (to be
they are methods of the :term:`metaclass`): exact, they are methods of the :term:`metaclass`):
.. method:: _CData.from_address(address) .. method:: from_address(address)
This method returns a ctypes type instance using the memory specified by address This method returns a ctypes type instance using the memory specified by
which must be an integer. address which must be an integer.
.. method:: _CData.from_param(obj) .. method:: from_param(obj)
This method adapts obj to a ctypes type. It is called with the actual object This method adapts obj to a ctypes type. It is called with the actual
used in a foreign function call, when the type is present in the foreign object used in a foreign function call, when the type is present in the
functions :attr:`argtypes` tuple; it must return an object that can be used as foreign functions :attr:`argtypes` tuple; it must return an object that
function call parameter. can be used as function call parameter.
All ctypes data types have a default implementation of this classmethod, All ctypes data types have a default implementation of this classmethod,
normally it returns ``obj`` if that is an instance of the type. Some types normally it returns ``obj`` if that is an instance of the type. Some
accept other objects as well. types accept other objects as well.
.. method:: _CData.in_dll(library, name) .. method:: in_dll(library, name)
This method returns a ctypes type instance exported by a shared library. *name* This method returns a ctypes type instance exported by a shared
is the name of the symbol that exports the data, *library* is the loaded shared library. *name* is the name of the symbol that exports the data, *library*
library. is the loaded shared library.
Common instance variables of ctypes data types:
Common instance variables of ctypes data types:
.. attribute:: _CData._b_base_
.. attribute:: _b_base_
Sometimes ctypes data instances do not own the memory block they contain, Sometimes ctypes data instances do not own the memory block they contain,
instead they share part of the memory block of a base object. The instead they share part of the memory block of a base object. The
:attr:`_b_base_` read-only member is the root ctypes object that owns the memory :attr:`_b_base_` read-only member is the root ctypes object that owns the
block. memory block.
.. attribute:: _CData._b_needsfree_ .. attribute:: _b_needsfree_
This read-only variable is true when the ctypes data instance has allocated the This read-only variable is true when the ctypes data instance has
memory block itself, false otherwise. allocated the memory block itself, false otherwise.
.. attribute:: _CData._objects .. attribute:: _objects
This member is either ``None`` or a dictionary containing Python objects that This member is either ``None`` or a dictionary containing Python objects
need to be kept alive so that the memory block contents is kept valid. This that need to be kept alive so that the memory block contents is kept
object is only exposed for debugging; never modify the contents of this valid. This object is only exposed for debugging; never modify the
dictionary. contents of this dictionary.
.. _ctypes-fundamental-data-types-2: .. _ctypes-fundamental-data-types-2:
...@@ -2010,19 +2012,20 @@ Fundamental data types ...@@ -2010,19 +2012,20 @@ Fundamental data types
so it inherits their methods and attributes. ctypes data types that are not so it inherits their methods and attributes. ctypes data types that are not
and do not contain pointers can now be pickled. and do not contain pointers can now be pickled.
Instances have a single attribute: Instances have a single attribute:
.. attribute:: _SimpleCData.value .. attribute:: value
This attribute contains the actual value of the instance. For integer and This attribute contains the actual value of the instance. For integer and
pointer types, it is an integer, for character types, it is a single character pointer types, it is an integer, for character types, it is a single
string, for character pointer types it is a Python string or unicode string. character string, for character pointer types it is a Python string or
unicode string.
When the ``value`` attribute is retrieved from a ctypes instance, usually a new When the ``value`` attribute is retrieved from a ctypes instance, usually
object is returned each time. ``ctypes`` does *not* implement original object a new object is returned each time. ``ctypes`` does *not* implement
return, always a new object is constructed. The same is true for all other original object return, always a new object is constructed. The same is
ctypes object instances. true for all other ctypes object instances.
Fundamental data types, when returned as foreign function call results, or, for Fundamental data types, when returned as foreign function call results, or, for
example, by retrieving structure field members or array items, are transparently example, by retrieving structure field members or array items, are transparently
...@@ -2258,27 +2261,28 @@ other data types containing pointer type fields. ...@@ -2258,27 +2261,28 @@ other data types containing pointer type fields.
Abstract base class for structures in *native* byte order. Abstract base class for structures in *native* byte order.
Concrete structure and union types must be created by subclassing one of these Concrete structure and union types must be created by subclassing one of these
types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
create :term:`descriptor`\s which allow reading and writing the fields by direct create :term:`descriptor`\s which allow reading and writing the fields by direct
attribute accesses. These are the attribute accesses. These are the
.. attribute:: Structure._fields_ .. attribute:: _fields_
A sequence defining the structure fields. The items must be 2-tuples or A sequence defining the structure fields. The items must be 2-tuples or
3-tuples. The first item is the name of the field, the second item specifies 3-tuples. The first item is the name of the field, the second item
the type of the field; it can be any ctypes data type. specifies the type of the field; it can be any ctypes data type.
For integer type fields like :class:`c_int`, a third optional item can be given. For integer type fields like :class:`c_int`, a third optional item can be
It must be a small positive integer defining the bit width of the field. given. It must be a small positive integer defining the bit width of the
field.
Field names must be unique within one structure or union. This is not checked, Field names must be unique within one structure or union. This is not
only one field can be accessed when names are repeated. checked, only one field can be accessed when names are repeated.
It is possible to define the :attr:`_fields_` class variable *after* the class It is possible to define the :attr:`_fields_` class variable *after* the
statement that defines the Structure subclass, this allows to create data types class statement that defines the Structure subclass, this allows to create
that directly or indirectly reference themselves:: data types that directly or indirectly reference themselves::
class List(Structure): class List(Structure):
pass pass
...@@ -2286,38 +2290,38 @@ attribute accesses. These are the ...@@ -2286,38 +2290,38 @@ attribute accesses. These are the
... ...
] ]
The :attr:`_fields_` class variable must, however, be defined before the type is The :attr:`_fields_` class variable must, however, be defined before the
first used (an instance is created, ``sizeof()`` is called on it, and so on). type is first used (an instance is created, ``sizeof()`` is called on it,
Later assignments to the :attr:`_fields_` class variable will raise an and so on). Later assignments to the :attr:`_fields_` class variable will
AttributeError. raise an AttributeError.
Structure and union subclass constructors accept both positional and named Structure and union subclass constructors accept both positional and named
arguments. Positional arguments are used to initialize the fields in the same arguments. Positional arguments are used to initialize the fields in the
order as they appear in the :attr:`_fields_` definition, named arguments are same order as they appear in the :attr:`_fields_` definition, named
used to initialize the fields with the corresponding name. arguments are used to initialize the fields with the corresponding name.
It is possible to defined sub-subclasses of structure types, they inherit the It is possible to defined sub-subclasses of structure types, they inherit
fields of the base class plus the :attr:`_fields_` defined in the sub-subclass, the fields of the base class plus the :attr:`_fields_` defined in the
if any. sub-subclass, if any.
.. attribute:: Structure._pack_ .. attribute:: _pack_
An optional small integer that allows to override the alignment of structure An optional small integer that allows to override the alignment of
fields in the instance. :attr:`_pack_` must already be defined when structure fields in the instance. :attr:`_pack_` must already be defined
:attr:`_fields_` is assigned, otherwise it will have no effect. when :attr:`_fields_` is assigned, otherwise it will have no effect.
.. attribute:: Structure._anonymous_ .. attribute:: _anonymous_
An optional sequence that lists the names of unnamed (anonymous) fields. An optional sequence that lists the names of unnamed (anonymous) fields.
``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
otherwise it will have no effect. otherwise it will have no effect.
The fields listed in this variable must be structure or union type fields. The fields listed in this variable must be structure or union type fields.
``ctypes`` will create descriptors in the structure type that allows to access ``ctypes`` will create descriptors in the structure type that allows to
the nested fields directly, without the need to create the structure or union access the nested fields directly, without the need to create the
field. structure or union field.
Here is an example type (Windows):: Here is an example type (Windows)::
...@@ -2332,11 +2336,12 @@ attribute accesses. These are the ...@@ -2332,11 +2336,12 @@ attribute accesses. These are the
_anonymous_ = ("u",) _anonymous_ = ("u",)
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
which one of the union fields is valid. Since the ``u`` field is defined as specifies which one of the union fields is valid. Since the ``u`` field
anonymous field, it is now possible to access the members directly off the is defined as anonymous field, it is now possible to access the members
TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
former is faster since it does not need to create a temporary union instance:: are equivalent, but the former is faster since it does not need to create
a temporary union instance::
td = TYPEDESC() td = TYPEDESC()
td.vt = VT_PTR td.vt = VT_PTR
......
...@@ -1567,22 +1567,24 @@ You can instantiate a :class:`Textbox` object as follows: ...@@ -1567,22 +1567,24 @@ You can instantiate a :class:`Textbox` object as follows:
containing window, with coordinates ``(0, 0)``. The instance's containing window, with coordinates ``(0, 0)``. The instance's
:attr:`stripspaces` flag is initially on. :attr:`stripspaces` flag is initially on.
:class:`Textbox` objects have the following methods: :class:`Textbox` objects have the following methods:
.. method:: Textbox.edit([validator]) .. method:: edit([validator])
This is the entry point you will normally use. It accepts editing keystrokes This is the entry point you will normally use. It accepts editing
until one of the termination keystrokes is entered. If *validator* is supplied, keystrokes until one of the termination keystrokes is entered. If
it must be a function. It will be called for each keystroke entered with the *validator* is supplied, it must be a function. It will be called for
keystroke as a parameter; command dispatch is done on the result. This method each keystroke entered with the keystroke as a parameter; command dispatch
returns the window contents as a string; whether blanks in the window are is done on the result. This method returns the window contents as a
included is affected by the :attr:`stripspaces` member. string; whether blanks in the window are included is affected by the
:attr:`stripspaces` member.
.. method:: Textbox.do_command(ch) .. method:: do_command(ch)
Process a single command keystroke. Here are the supported special keystrokes: Process a single command keystroke. Here are the supported special
keystrokes:
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| Keystroke | Action | | Keystroke | Action |
...@@ -1619,8 +1621,8 @@ You can instantiate a :class:`Textbox` object as follows: ...@@ -1619,8 +1621,8 @@ You can instantiate a :class:`Textbox` object as follows:
| :kbd:`Control-P` | Cursor up; move up one line. | | :kbd:`Control-P` | Cursor up; move up one line. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
Move operations do nothing if the cursor is at an edge where the movement is not Move operations do nothing if the cursor is at an edge where the movement
possible. The following synonyms are supported where possible: is not possible. The following synonyms are supported where possible:
+------------------------+------------------+ +------------------------+------------------+
| Constant | Keystroke | | Constant | Keystroke |
...@@ -1636,23 +1638,23 @@ You can instantiate a :class:`Textbox` object as follows: ...@@ -1636,23 +1638,23 @@ You can instantiate a :class:`Textbox` object as follows:
| :const:`KEY_BACKSPACE` | :kbd:`Control-h` | | :const:`KEY_BACKSPACE` | :kbd:`Control-h` |
+------------------------+------------------+ +------------------------+------------------+
All other keystrokes are treated as a command to insert the given character and All other keystrokes are treated as a command to insert the given
move right (with line wrapping). character and move right (with line wrapping).
.. method:: Textbox.gather() .. method:: gather()
This method returns the window contents as a string; whether blanks in the This method returns the window contents as a string; whether blanks in the
window are included is affected by the :attr:`stripspaces` member. window are included is affected by the :attr:`stripspaces` member.
.. attribute:: Textbox.stripspaces .. attribute:: stripspaces
This data member is a flag which controls the interpretation of blanks in the This data member is a flag which controls the interpretation of blanks in
window. When it is on, trailing blanks on each line are ignored; any cursor the window. When it is on, trailing blanks on each line are ignored; any
motion that would land the cursor on a trailing blank goes to the end of that cursor motion that would land the cursor on a trailing blank goes to the
line instead, and trailing blanks are stripped when the window contents are end of that line instead, and trailing blanks are stripped when the window
gathered. contents are gathered.
:mod:`curses.wrapper` --- Terminal handler for curses programs :mod:`curses.wrapper` --- Terminal handler for curses programs
......
...@@ -340,115 +340,103 @@ Decimal objects ...@@ -340,115 +340,103 @@ Decimal objects
Once constructed, :class:`Decimal` objects are immutable. Once constructed, :class:`Decimal` objects are immutable.
Decimal floating point objects share many properties with the other built-in
numeric types such as :class:`float` and :class:`int`. All of the usual math
operations and special methods apply. Likewise, decimal objects can be
copied, pickled, printed, used as dictionary keys, used as set elements,
compared, sorted, and coerced to another type (such as :class:`float` or
:class:`long`).
Decimal floating point objects share many properties with the other built-in In addition to the standard numeric properties, decimal floating point
numeric types such as :class:`float` and :class:`int`. All of the usual math objects also have a number of specialized methods:
operations and special methods apply. Likewise, decimal objects can be copied,
pickled, printed, used as dictionary keys, used as set elements, compared,
sorted, and converted to another type (such as :class:`float` or :class:`int`).
In addition to the standard numeric properties, decimal floating point objects
also have a number of specialized methods:
.. method:: adjusted()
.. method:: Decimal.adjusted() Return the adjusted exponent after shifting out the coefficient's
rightmost digits until only the lead digit remains:
``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
position of the most significant digit with respect to the decimal point.
Return the adjusted exponent after shifting out the coefficient's rightmost
digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
returns seven. Used for determining the position of the most significant digit
with respect to the decimal point.
.. method:: as_tuple()
.. method:: Decimal.as_tuple()
Return a :term:`named tuple` representation of the number: Return a :term:`named tuple` representation of the number:
``DecimalTuple(sign, digits, exponent)``. ``DecimalTuple(sign, digits, exponent)``.
.. method:: Decimal.canonical() .. method:: canonical()
Return the canonical encoding of the argument. Currently, the
encoding of a :class:`Decimal` instance is always canonical, so
this operation returns its argument unchanged.
Return the canonical encoding of the argument. Currently, the encoding of
a :class:`Decimal` instance is always canonical, so this operation returns
its argument unchanged.
.. method:: Decimal.compare(other[, context]) .. method:: compare(other[, context])
Compare the values of two Decimal instances. This operation Compare the values of two Decimal instances. This operation behaves in
behaves in the same way as the usual comparison method the same way as the usual comparison method :meth:`__cmp__`, except that
:meth:`__cmp__`, except that :meth:`compare` returns a Decimal :meth:`compare` returns a Decimal instance rather than an integer, and if
instance rather than an integer, and if either operand is a NaN either operand is a NaN then the result is a NaN::
then the result is a NaN::
a or b is a NaN ==> Decimal('NaN') a or b is a NaN ==> Decimal('NaN')
a < b ==> Decimal('-1') a < b ==> Decimal('-1')
a == b ==> Decimal('0') a == b ==> Decimal('0')
a > b ==> Decimal('1') a > b ==> Decimal('1')
.. method:: Decimal.compare_signal(other[, context]) .. method:: compare_signal(other[, context])
This operation is identical to the :meth:`compare` method, except This operation is identical to the :meth:`compare` method, except that all
that all NaNs signal. That is, if neither operand is a signaling NaNs signal. That is, if neither operand is a signaling NaN then any
NaN then any quiet NaN operand is treated as though it were a quiet NaN operand is treated as though it were a signaling NaN.
signaling NaN.
.. method:: compare_total(other)
.. method:: Decimal.compare_total(other) Compare two operands using their abstract representation rather than their
numerical value. Similar to the :meth:`compare` method, but the result
Compare two operands using their abstract representation rather gives a total ordering on :class:`Decimal` instances. Two
than their numerical value. Similar to the :meth:`compare` method, :class:`Decimal` instances with the same numeric value but different
but the result gives a total ordering on :class:`Decimal` representations compare unequal in this ordering:
instances. Two :class:`Decimal` instances with the same numeric
value but different representations compare unequal in this
ordering:
>>> Decimal('12.0').compare_total(Decimal('12')) >>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1') Decimal('-1')
Quiet and signaling NaNs are also included in the total ordering. Quiet and signaling NaNs are also included in the total ordering. The
The result of this function is ``Decimal('0')`` if both operands result of this function is ``Decimal('0')`` if both operands have the same
have the same representation, ``Decimal('-1')`` if the first representation, ``Decimal('-1')`` if the first operand is lower in the
operand is lower in the total order than the second, and total order than the second, and ``Decimal('1')`` if the first operand is
``Decimal('1')`` if the first operand is higher in the total order higher in the total order than the second operand. See the specification
than the second operand. See the specification for details of the for details of the total order.
total order.
.. method:: Decimal.compare_total_mag(other) .. method:: compare_total_mag(other)
Compare two operands using their abstract representation rather Compare two operands using their abstract representation rather than their
than their value as in :meth:`compare_total`, but ignoring the sign value as in :meth:`compare_total`, but ignoring the sign of each operand.
of each operand. ``x.compare_total_mag(y)`` is equivalent to ``x.compare_total_mag(y)`` is equivalent to
``x.copy_abs().compare_total(y.copy_abs())``. ``x.copy_abs().compare_total(y.copy_abs())``.
.. method:: copy_abs()
.. method:: Decimal.copy_abs() Return the absolute value of the argument. This operation is unaffected
by the context and is quiet: no flags are changed and no rounding is
Return the absolute value of the argument. This operation is performed.
unaffected by the context and is quiet: no flags are changed and no
rounding is performed.
.. method:: Decimal.copy_negate()
Return the negation of the argument. This operation is unaffected .. method:: copy_negate()
by the context and is quiet: no flags are changed and no rounding
is performed.
Return the negation of the argument. This operation is unaffected by the
context and is quiet: no flags are changed and no rounding is performed.
.. method:: Decimal.copy_sign(other) .. method:: copy_sign(other)
Return a copy of the first operand with the sign set to be the Return a copy of the first operand with the sign set to be the same as the
same as the sign of the second operand. For example: sign of the second operand. For example:
>>> Decimal('2.3').copy_sign(Decimal('-1.5')) >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3') Decimal('-2.3')
This operation is unaffected by the context and is quiet: no flags This operation is unaffected by the context and is quiet: no flags are
are changed and no rounding is performed. changed and no rounding is performed.
.. method:: exp([context])
.. method:: Decimal.exp([context])
Return the value of the (natural) exponential function ``e**x`` at the Return the value of the (natural) exponential function ``e**x`` at the
given number. The result is correctly rounded using the given number. The result is correctly rounded using the
...@@ -459,190 +447,163 @@ also have a number of specialized methods: ...@@ -459,190 +447,163 @@ also have a number of specialized methods:
>>> Decimal(321).exp() >>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139') Decimal('2.561702493119680037517373933E+139')
.. method:: fma(other, third[, context])
.. method:: Decimal.fma(other, third[, context]) Fused multiply-add. Return self*other+third with no rounding of the
intermediate product self*other.
Fused multiply-add. Return self*other+third with no rounding of
the intermediate product self*other.
>>> Decimal(2).fma(3, 5) >>> Decimal(2).fma(3, 5)
Decimal('11') Decimal('11')
.. method:: is_canonical()
.. method:: Decimal.is_canonical() Return :const:`True` if the argument is canonical and :const:`False`
otherwise. Currently, a :class:`Decimal` instance is always canonical, so
Return :const:`True` if the argument is canonical and this operation always returns :const:`True`.
:const:`False` otherwise. Currently, a :class:`Decimal` instance
is always canonical, so this operation always returns
:const:`True`.
.. method:: is_finite()
.. method:: is_finite()
Return :const:`True` if the argument is a finite number, and Return :const:`True` if the argument is a finite number, and
:const:`False` if the argument is an infinity or a NaN. :const:`False` if the argument is an infinity or a NaN.
.. method:: is_infinite()
.. method:: is_infinite() Return :const:`True` if the argument is either positive or negative
infinity and :const:`False` otherwise.
Return :const:`True` if the argument is either positive or
negative infinity and :const:`False` otherwise.
.. method:: is_nan() .. method:: is_nan()
Return :const:`True` if the argument is a (quiet or signaling) Return :const:`True` if the argument is a (quiet or signaling) NaN and
NaN and :const:`False` otherwise. :const:`False` otherwise.
.. method:: is_normal()
Return :const:`True` if the argument is a *normal* finite number. .. method:: is_normal()
Return :const:`False` if the argument is zero, subnormal, infinite
or a NaN.
Return :const:`True` if the argument is a *normal* finite number. Return
:const:`False` if the argument is zero, subnormal, infinite or a NaN.
.. method:: is_qnan() .. method:: is_qnan()
Return :const:`True` if the argument is a quiet NaN, and Return :const:`True` if the argument is a quiet NaN, and
:const:`False` otherwise. :const:`False` otherwise.
.. method:: is_signed()
.. method:: is_signed()
Return :const:`True` if the argument has a negative sign and Return :const:`True` if the argument has a negative sign and
:const:`False` otherwise. Note that zeros and NaNs can both carry :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
signs.
.. method:: is_snan()
.. method:: is_snan() Return :const:`True` if the argument is a signaling NaN and :const:`False`
otherwise.
Return :const:`True` if the argument is a signaling NaN and .. method:: is_subnormal()
:const:`False` otherwise.
Return :const:`True` if the argument is subnormal, and :const:`False`
otherwise.
.. method:: is_subnormal() .. method:: is_zero()
Return :const:`True` if the argument is subnormal, and Return :const:`True` if the argument is a (positive or negative) zero and
:const:`False` otherwise. :const:`False` otherwise.
.. method:: ln([context])
.. method:: is_zero() Return the natural (base e) logarithm of the operand. The result is
Return :const:`True` if the argument is a (positive or negative)
zero and :const:`False` otherwise.
.. method:: Decimal.ln([context])
Return the natural (base e) logarithm of the operand. The result
is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
mode.
.. method:: Decimal.log10([context])
Return the base ten logarithm of the operand. The result is
correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
.. method:: log10([context])
.. method:: Decimal.logb([context]) Return the base ten logarithm of the operand. The result is correctly
rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
For a nonzero number, return the adjusted exponent of its operand
as a :class:`Decimal` instance. If the operand is a zero then
``Decimal('-Infinity')`` is returned and the
:const:`DivisionByZero` flag is raised. If the operand is an
infinity then ``Decimal('Infinity')`` is returned.
.. method:: logb([context])
.. method:: Decimal.logical_and(other[, context]) For a nonzero number, return the adjusted exponent of its operand as a
:class:`Decimal` instance. If the operand is a zero then
``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
returned.
:meth:`logical_and` is a logical operation which takes two .. method:: logical_and(other[, context])
*logical operands* (see :ref:`logical_operands_label`). The result
is the digit-wise ``and`` of the two operands.
:meth:`logical_and` is a logical operation which takes two *logical
operands* (see :ref:`logical_operands_label`). The result is the
digit-wise ``and`` of the two operands.
.. method:: Decimal.logical_invert(other[, context]) .. method:: logical_invert(other[, context])
:meth:`logical_invert` is a logical operation. The argument must :meth:`logical_invert` is a logical operation. The argument must
be a *logical operand* (see :ref:`logical_operands_label`). The be a *logical operand* (see :ref:`logical_operands_label`). The
result is the digit-wise inversion of the operand. result is the digit-wise inversion of the operand.
.. method:: logical_or(other[, context])
.. method:: Decimal.logical_or(other[, context])
:meth:`logical_or` is a logical operation which takes two *logical :meth:`logical_or` is a logical operation which takes two *logical
operands* (see :ref:`logical_operands_label`). The result is the operands* (see :ref:`logical_operands_label`). The result is the
digit-wise ``or`` of the two operands. digit-wise ``or`` of the two operands.
.. method:: logical_xor(other[, context])
.. method:: Decimal.logical_xor(other[, context]) :meth:`logical_xor` is a logical operation which takes two *logical
operands* (see :ref:`logical_operands_label`). The result is the
:meth:`logical_xor` is a logical operation which takes two digit-wise exclusive or of the two operands.
*logical operands* (see :ref:`logical_operands_label`). The result
is the digit-wise exclusive or of the two operands.
.. method:: Decimal.max(other[, context]) .. method:: max(other[, context])
Like ``max(self, other)`` except that the context rounding rule is applied Like ``max(self, other)`` except that the context rounding rule is applied
before returning and that :const:`NaN` values are either signaled or ignored before returning and that :const:`NaN` values are either signaled or
(depending on the context and whether they are signaling or quiet). ignored (depending on the context and whether they are signaling or
quiet).
.. method:: Decimal.max_mag(other[, context])
Similar to the :meth:`max` method, but the comparison is done using .. method:: max_mag(other[, context])
the absolute values of the operands.
Similar to the :meth:`max` method, but the comparison is done using the
absolute values of the operands.
.. method:: Decimal.min(other[, context]) .. method:: min(other[, context])
Like ``min(self, other)`` except that the context rounding rule is applied Like ``min(self, other)`` except that the context rounding rule is applied
before returning and that :const:`NaN` values are either signaled or ignored before returning and that :const:`NaN` values are either signaled or
(depending on the context and whether they are signaling or quiet). ignored (depending on the context and whether they are signaling or
quiet).
.. method:: Decimal.min_mag(other[, context]) .. method:: min_mag(other[, context])
Similar to the :meth:`min` method, but the comparison is done using Similar to the :meth:`min` method, but the comparison is done using the
the absolute values of the operands. absolute values of the operands.
.. method:: next_minus([context])
.. method:: Decimal.next_minus([context]) Return the largest number representable in the given context (or in the
current thread's context if no context is given) that is smaller than the
given operand.
Return the largest number representable in the given context (or .. method:: next_plus([context])
in the current thread's context if no context is given) that is smaller
than the given operand.
Return the smallest number representable in the given context (or in the
current thread's context if no context is given) that is larger than the
given operand.
.. method:: Decimal.next_plus([context]) .. method:: next_toward(other[, context])
Return the smallest number representable in the given context (or If the two operands are unequal, return the number closest to the first
in the current thread's context if no context is given) that is operand in the direction of the second operand. If both operands are
larger than the given operand. numerically equal, return a copy of the first operand with the sign set to
be the same as the sign of the second operand.
.. method:: normalize([context])
.. method:: Decimal.next_toward(other[, context]) Normalize the number by stripping the rightmost trailing zeros and
converting any result equal to :const:`Decimal('0')` to
:const:`Decimal('0e0')`. Used for producing canonical values for members
of an equivalence class. For example, ``Decimal('32.100')`` and
``Decimal('0.321000e+2')`` both normalize to the equivalent value
``Decimal('32.1')``.
If the two operands are unequal, return the number closest to the .. method:: number_class([context])
first operand in the direction of the second operand. If both
operands are numerically equal, return a copy of the first operand
with the sign set to be the same as the sign of the second operand.
Return a string describing the *class* of the operand. The returned value
.. method:: Decimal.normalize([context]) is one of the following ten strings.
Normalize the number by stripping the rightmost trailing zeros and converting
any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
producing canonical values for members of an equivalence class. For example,
``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
equivalent value ``Decimal('32.1')``.
.. method:: Decimal.number_class([context])
Return a string describing the *class* of the operand. The
returned value is one of the following ten strings.
* ``"-Infinity"``, indicating that the operand is negative infinity. * ``"-Infinity"``, indicating that the operand is negative infinity.
* ``"-Normal"``, indicating that the operand is a negative normal number. * ``"-Normal"``, indicating that the operand is a negative normal number.
...@@ -655,127 +616,118 @@ also have a number of specialized methods: ...@@ -655,127 +616,118 @@ also have a number of specialized methods:
* ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
* ``"sNaN"``, indicating that the operand is a signaling NaN. * ``"sNaN"``, indicating that the operand is a signaling NaN.
.. method:: quantize(exp[, rounding[, context[, watchexp]]])
.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) Return a value equal to the first operand after rounding and having the
exponent of the second operand.
Return a value equal to the first operand after rounding and
having the exponent of the second operand.
>>> Decimal('1.41421356').quantize(Decimal('1.000')) >>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414') Decimal('1.414')
Unlike other operations, if the length of the coefficient after the Unlike other operations, if the length of the coefficient after the
quantize operation would be greater than precision, then an quantize operation would be greater than precision, then an
:const:`InvalidOperation` is signaled. This guarantees that, unless :const:`InvalidOperation` is signaled. This guarantees that, unless there
there is an error condition, the quantized exponent is always equal is an error condition, the quantized exponent is always equal to that of
to that of the right-hand operand. the right-hand operand.
Also unlike other operations, quantize never signals Underflow, Also unlike other operations, quantize never signals Underflow, even if
even if the result is subnormal and inexact. the result is subnormal and inexact.
If the exponent of the second operand is larger than that of the If the exponent of the second operand is larger than that of the first
first then rounding may be necessary. In this case, the rounding then rounding may be necessary. In this case, the rounding mode is
mode is determined by the ``rounding`` argument if given, else by determined by the ``rounding`` argument if given, else by the given
the given ``context`` argument; if neither argument is given the ``context`` argument; if neither argument is given the rounding mode of
rounding mode of the current thread's context is used. the current thread's context is used.
If *watchexp* is set (default), then an error is returned whenever the If *watchexp* is set (default), then an error is returned whenever the
resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. resulting exponent is greater than :attr:`Emax` or less than
:attr:`Etiny`.
.. method:: Decimal.radix() .. method:: radix()
Return ``Decimal(10)``, the radix (base) in which the Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
:class:`Decimal` class does all its arithmetic. Included for class does all its arithmetic. Included for compatibility with the
compatibility with the specification. specification.
.. method:: remainder_near(other[, context])
.. method:: Decimal.remainder_near(other[, context]) Compute the modulo as either a positive or negative value depending on
which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Compute the modulo as either a positive or negative value depending on which is If both are equally close, the one chosen will have the same sign as
closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns *self*.
``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
If both are equally close, the one chosen will have the same sign as *self*. .. method:: rotate(other[, context])
.. method:: Decimal.rotate(other[, context])
Return the result of rotating the digits of the first operand by
an amount specified by the second operand. The second operand
must be an integer in the range -precision through precision. The
absolute value of the second operand gives the number of places to
rotate. If the second operand is positive then rotation is to the
left; otherwise rotation is to the right. The coefficient of the
first operand is padded on the left with zeros to length precision
if necessary. The sign and exponent of the first operand are
unchanged.
Return the result of rotating the digits of the first operand by an amount
specified by the second operand. The second operand must be an integer in
the range -precision through precision. The absolute value of the second
operand gives the number of places to rotate. If the second operand is
positive then rotation is to the left; otherwise rotation is to the right.
The coefficient of the first operand is padded on the left with zeros to
length precision if necessary. The sign and exponent of the first operand
are unchanged.
.. method:: Decimal.same_quantum(other[, context]) .. method:: same_quantum(other[, context])
Test whether self and other have the same exponent or whether both are Test whether self and other have the same exponent or whether both are
:const:`NaN`. :const:`NaN`.
.. method:: Decimal.scaleb(other[, context]) .. method:: scaleb(other[, context])
Return the first operand with exponent adjusted by the second. Return the first operand with exponent adjusted by the second.
Equivalently, return the first operand multiplied by ``10**other``. Equivalently, return the first operand multiplied by ``10**other``. The
The second operand must be an integer. second operand must be an integer.
.. method:: shift(other[, context])
.. method:: Decimal.shift(other[, context]) Return the result of shifting the digits of the first operand by an amount
specified by the second operand. The second operand must be an integer in
Return the result of shifting the digits of the first operand by the range -precision through precision. The absolute value of the second
an amount specified by the second operand. The second operand must operand gives the number of places to shift. If the second operand is
be an integer in the range -precision through precision. The positive then the shift is to the left; otherwise the shift is to the
absolute value of the second operand gives the number of places to right. Digits shifted into the coefficient are zeros. The sign and
shift. If the second operand is positive then the shift is to the exponent of the first operand are unchanged.
left; otherwise the shift is to the right. Digits shifted into the
coefficient are zeros. The sign and exponent of the first operand
are unchanged.
.. method:: Decimal.sqrt([context]) .. method:: sqrt([context])
Return the square root of the argument to full precision. Return the square root of the argument to full precision.
.. method:: Decimal.to_eng_string([context]) .. method:: to_eng_string([context])
Convert to an engineering-type string. Convert to an engineering-type string.
Engineering notation has an exponent which is a multiple of 3, so there are up Engineering notation has an exponent which is a multiple of 3, so there
to 3 digits left of the decimal place. For example, converts are up to 3 digits left of the decimal place. For example, converts
``Decimal('123E+1')`` to ``Decimal('1.23E+3')`` ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
.. method:: Decimal.to_integral([rounding[, context]]) .. method:: to_integral([rounding[, context]])
Identical to the :meth:`to_integral_value` method. The ``to_integral`` Identical to the :meth:`to_integral_value` method. The ``to_integral``
name has been kept for compatibility with older versions. name has been kept for compatibility with older versions.
.. method:: Decimal.to_integral_exact([rounding[, context]]) .. method:: to_integral_exact([rounding[, context]])
Round to the nearest integer, signaling
:const:`Inexact` or :const:`Rounded` as appropriate if rounding
occurs. The rounding mode is determined by the ``rounding``
parameter if given, else by the given ``context``. If neither
parameter is given then the rounding mode of the current context is
used.
Round to the nearest integer, signaling :const:`Inexact` or
:const:`Rounded` as appropriate if rounding occurs. The rounding mode is
determined by the ``rounding`` parameter if given, else by the given
``context``. If neither parameter is given then the rounding mode of the
current context is used.
.. method:: Decimal.to_integral_value([rounding[, context]]) .. method:: to_integral_value([rounding[, context]])
Round to the nearest integer without signaling :const:`Inexact` or Round to the nearest integer without signaling :const:`Inexact` or
:const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
method in either the supplied *context* or the current context. rounding method in either the supplied *context* or the current context.
.. method:: Decimal.trim() .. method:: trim()
Return the decimal with *insignificant* trailing zeros removed. Return the decimal with *insignificant* trailing zeros removed. Here, a
Here, a trailing zero is considered insignificant either if it trailing zero is considered insignificant either if it follows the decimal
follows the decimal point, or if the exponent of the argument (that point, or if the exponent of the argument (that is, the last element of
is, the last element of the :meth:`as_tuple` representation) is the :meth:`as_tuple` representation) is positive.
positive.
.. _logical_operands_label: .. _logical_operands_label:
...@@ -916,38 +868,37 @@ In addition to the three supplied contexts, new contexts can be created with the ...@@ -916,38 +868,37 @@ In addition to the three supplied contexts, new contexts can be created with the
lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
The :class:`Context` class defines several general purpose methods as The :class:`Context` class defines several general purpose methods as well as
well as a large number of methods for doing arithmetic directly in a a large number of methods for doing arithmetic directly in a given context.
given context. In addition, for each of the :class:`Decimal` methods In addition, for each of the :class:`Decimal` methods described above (with
described above (with the exception of the :meth:`adjusted` and the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
:meth:`as_tuple` methods) there is a corresponding :class:`Context` a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
method. For example, ``C.exp(x)`` is equivalent to equivalent to ``x.exp(context=C)``.
``x.exp(context=C)``.
.. method:: Context.clear_flags()
Resets all of the flags to :const:`0`. .. method:: clear_flags()
Resets all of the flags to :const:`0`.
.. method:: Context.copy() .. method:: copy()
Return a duplicate of the context. Return a duplicate of the context.
.. method:: Context.copy_decimal(num) .. method:: copy_decimal(num)
Return a copy of the Decimal instance num. Return a copy of the Decimal instance num.
.. method:: Context.create_decimal(num) .. method:: create_decimal(num)
Creates a new Decimal instance from *num* but using *self* as context. Unlike Creates a new Decimal instance from *num* but using *self* as
the :class:`Decimal` constructor, the context precision, rounding method, flags, context. Unlike the :class:`Decimal` constructor, the context precision,
and traps are applied to the conversion. rounding method, flags, and traps are applied to the conversion.
This is useful because constants are often given to a greater precision than is This is useful because constants are often given to a greater precision
needed by the application. Another benefit is that rounding immediately than is needed by the application. Another benefit is that rounding
eliminates unintended effects from digits beyond the current precision. In the immediately eliminates unintended effects from digits beyond the current
following example, using unrounded inputs means that adding zero to a sum can precision. In the following example, using unrounded inputs means that
change the result: adding zero to a sum can change the result:
.. doctest:: newcontext .. doctest:: newcontext
...@@ -957,107 +908,105 @@ method. For example, ``C.exp(x)`` is equivalent to ...@@ -957,107 +908,105 @@ method. For example, ``C.exp(x)`` is equivalent to
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44') Decimal('4.44')
This method implements the to-number operation of the IBM This method implements the to-number operation of the IBM specification.
specification. If the argument is a string, no leading or trailing If the argument is a string, no leading or trailing whitespace is
whitespace is permitted. permitted.
.. method:: Context.Etiny() .. method:: Etiny()
Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
for subnormal results. When underflow occurs, the exponent is set to value for subnormal results. When underflow occurs, the exponent is set
:const:`Etiny`. to :const:`Etiny`.
.. method:: Context.Etop() .. method:: Etop()
Returns a value equal to ``Emax - prec + 1``. Returns a value equal to ``Emax - prec + 1``.
The usual approach to working with decimals is to create :class:`Decimal` The usual approach to working with decimals is to create :class:`Decimal`
instances and then apply arithmetic operations which take place within the instances and then apply arithmetic operations which take place within the
current context for the active thread. An alternative approach is to use context current context for the active thread. An alternative approach is to use
methods for calculating within a specific context. The methods are similar to context methods for calculating within a specific context. The methods are
those for the :class:`Decimal` class and are only briefly recounted here. similar to those for the :class:`Decimal` class and are only briefly
recounted here.
.. method:: Context.abs(x) .. method:: abs(x)
Returns the absolute value of *x*. Returns the absolute value of *x*.
.. method:: Context.add(x, y) .. method:: add(x, y)
Return the sum of *x* and *y*. Return the sum of *x* and *y*.
.. method:: Context.divide(x, y) .. method:: divide(x, y)
Return *x* divided by *y*. Return *x* divided by *y*.
.. method:: Context.divide_int(x, y) .. method:: divide_int(x, y)
Return *x* divided by *y*, truncated to an integer. Return *x* divided by *y*, truncated to an integer.
.. method:: Context.divmod(x, y) .. method:: divmod(x, y)
Divides two numbers and returns the integer part of the result. Divides two numbers and returns the integer part of the result.
.. method:: Context.minus(x) .. method:: minus(x)
Minus corresponds to the unary prefix minus operator in Python. Minus corresponds to the unary prefix minus operator in Python.
.. method:: Context.multiply(x, y) .. method:: multiply(x, y)
Return the product of *x* and *y*. Return the product of *x* and *y*.
.. method:: Context.plus(x) .. method:: plus(x)
Plus corresponds to the unary prefix plus operator in Python. This operation Plus corresponds to the unary prefix plus operator in Python. This
applies the context precision and rounding, so it is *not* an identity operation applies the context precision and rounding, so it is *not* an
operation. identity operation.
.. method:: Context.power(x, y[, modulo]) .. method:: power(x, y[, modulo])
Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
given.
With two arguments, compute ``x**y``. If ``x`` is negative then With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
``y`` must be integral. The result will be inexact unless ``y`` is must be integral. The result will be inexact unless ``y`` is integral and
integral and the result is finite and can be expressed exactly in the result is finite and can be expressed exactly in 'precision' digits.
'precision' digits. The result should always be correctly rounded, The result should always be correctly rounded, using the rounding mode of
using the rounding mode of the current thread's context. the current thread's context.
With three arguments, compute ``(x**y) % modulo``. For the three With three arguments, compute ``(x**y) % modulo``. For the three argument
argument form, the following restrictions on the arguments hold: form, the following restrictions on the arguments hold:
- all three arguments must be integral - all three arguments must be integral
- ``y`` must be nonnegative - ``y`` must be nonnegative
- at least one of ``x`` or ``y`` must be nonzero - at least one of ``x`` or ``y`` must be nonzero
- ``modulo`` must be nonzero and have at most 'precision' digits - ``modulo`` must be nonzero and have at most 'precision' digits
The result of ``Context.power(x, y, modulo)`` is identical to The result of ``Context.power(x, y, modulo)`` is identical to the result
the result that would be obtained by computing ``(x**y) % that would be obtained by computing ``(x**y) % modulo`` with unbounded
modulo`` with unbounded precision, but is computed more precision, but is computed more efficiently. It is always exact.
efficiently. It is always exact.
.. method:: Context.remainder(x, y) .. method:: remainder(x, y)
Returns the remainder from integer division. Returns the remainder from integer division.
The sign of the result, if non-zero, is the same as that of the original The sign of the result, if non-zero, is the same as that of the original
dividend. dividend.
.. method:: Context.subtract(x, y) .. method:: subtract(x, y)
Return the difference between *x* and *y*. Return the difference between *x* and *y*.
.. method:: Context.to_sci_string(x) .. method:: to_sci_string(x)
Converts a number to a string using scientific notation. Converts a number to a string using scientific notation.
...@@ -1138,28 +1087,29 @@ condition. ...@@ -1138,28 +1087,29 @@ condition.
Numerical overflow. Numerical overflow.
Indicates the exponent is larger than :attr:`Emax` after rounding has occurred. Indicates the exponent is larger than :attr:`Emax` after rounding has
If not trapped, the result depends on the rounding mode, either pulling inward occurred. If not trapped, the result depends on the rounding mode, either
to the largest representable finite number or rounding outward to pulling inward to the largest representable finite number or rounding outward
:const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
also signaled. are also signaled.
.. class:: Rounded .. class:: Rounded
Rounding occurred though possibly no information was lost. Rounding occurred though possibly no information was lost.
Signaled whenever rounding discards digits; even if those digits are zero (such Signaled whenever rounding discards digits; even if those digits are zero
as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
unchanged. This signal is used to detect loss of significant digits. the result unchanged. This signal is used to detect loss of significant
digits.
.. class:: Subnormal .. class:: Subnormal
Exponent was lower than :attr:`Emin` prior to rounding. Exponent was lower than :attr:`Emin` prior to rounding.
Occurs when an operation result is subnormal (the exponent is too small). If not Occurs when an operation result is subnormal (the exponent is too small). If
trapped, returns the result unchanged. not trapped, returns the result unchanged.
.. class:: Underflow .. class:: Underflow
......
...@@ -343,57 +343,59 @@ The :class:`SequenceMatcher` class has this constructor: ...@@ -343,57 +343,59 @@ The :class:`SequenceMatcher` class has this constructor:
The optional arguments *a* and *b* are sequences to be compared; both default to The optional arguments *a* and *b* are sequences to be compared; both default to
empty strings. The elements of both sequences must be :term:`hashable`. empty strings. The elements of both sequences must be :term:`hashable`.
:class:`SequenceMatcher` objects have the following methods: :class:`SequenceMatcher` objects have the following methods:
.. method:: SequenceMatcher.set_seqs(a, b) .. method:: set_seqs(a, b)
Set the two sequences to be compared. Set the two sequences to be compared.
:class:`SequenceMatcher` computes and caches detailed information about the :class:`SequenceMatcher` computes and caches detailed information about the
second sequence, so if you want to compare one sequence against many sequences, second sequence, so if you want to compare one sequence against many
use :meth:`set_seq2` to set the commonly used sequence once and call sequences, use :meth:`set_seq2` to set the commonly used sequence once and
:meth:`set_seq1` repeatedly, once for each of the other sequences. call :meth:`set_seq1` repeatedly, once for each of the other sequences.
.. method:: SequenceMatcher.set_seq1(a) .. method:: set_seq1(a)
Set the first sequence to be compared. The second sequence to be compared is Set the first sequence to be compared. The second sequence to be compared
not changed. is not changed.
.. method:: SequenceMatcher.set_seq2(b) .. method:: set_seq2(b)
Set the second sequence to be compared. The first sequence to be compared is Set the second sequence to be compared. The first sequence to be compared
not changed. is not changed.
.. method:: SequenceMatcher.find_longest_match(alo, ahi, blo, bhi) .. method:: find_longest_match(alo, ahi, blo, bhi)
Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns ``(i, j, If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <= ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i == k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks, <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
return one that starts earliest in *a*, and of all those maximal matching blocks all maximal matching blocks, return one that starts earliest in *a*, and
that start earliest in *a*, return the one that starts earliest in *b*. of all those maximal matching blocks that start earliest in *a*, return
the one that starts earliest in *b*.
>>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9) >>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5) Match(a=0, b=4, size=5)
If *isjunk* was provided, first the longest matching block is determined as If *isjunk* was provided, first the longest matching block is determined
above, but with the additional restriction that no junk element appears in the as above, but with the additional restriction that no junk element appears
block. Then that block is extended as far as possible by matching (only) junk in the block. Then that block is extended as far as possible by matching
elements on both sides. So the resulting block never matches on junk except as (only) junk elements on both sides. So the resulting block never matches
identical junk happens to be adjacent to an interesting match. on junk except as identical junk happens to be adjacent to an interesting
match.
Here's the same example as before, but considering blanks to be junk. That Here's the same example as before, but considering blanks to be junk. That
prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
sequence directly. Instead only the ``'abcd'`` can match, and matches the second sequence directly. Instead only the ``'abcd'`` can match, and
leftmost ``'abcd'`` in the second sequence: matches the leftmost ``'abcd'`` in the second sequence:
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9) >>> s.find_longest_match(0, 5, 0, 9)
...@@ -404,17 +406,17 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -404,17 +406,17 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
This method returns a :term:`named tuple` ``Match(a, b, size)``. This method returns a :term:`named tuple` ``Match(a, b, size)``.
.. method:: SequenceMatcher.get_matching_blocks() .. method:: get_matching_blocks()
Return list of triples describing matching subsequences. Each triple is of the Return list of triples describing matching subsequences. Each triple is of
form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The triples are the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The
monotonically increasing in *i* and *j*. triples are monotonically increasing in *i* and *j*.
The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It is The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It
the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` are is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')``
adjacent triples in the list, and the second is not the last triple in the list, are adjacent triples in the list, and the second is not the last triple in
then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
describe non-adjacent equal blocks. triples always describe non-adjacent equal blocks.
.. XXX Explain why a dummy is used! .. XXX Explain why a dummy is used!
...@@ -425,12 +427,12 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -425,12 +427,12 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
.. method:: SequenceMatcher.get_opcodes() .. method:: get_opcodes()
Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is of Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == 0``, and of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 ==
remaining tuples have *i1* equal to the *i2* from the preceding tuple, and, 0``, and remaining tuples have *i1* equal to the *i2* from the preceding
likewise, *j1* equal to the previous *j2*. tuple, and, likewise, *j1* equal to the previous *j2*.
The *tag* values are strings, with these meanings: The *tag* values are strings, with these meanings:
...@@ -466,43 +468,46 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -466,43 +468,46 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
insert a[6:6] () b[5:6] (f) insert a[6:6] () b[5:6] (f)
.. method:: SequenceMatcher.get_grouped_opcodes([n]) .. method:: get_grouped_opcodes([n])
Return a :term:`generator` of groups with up to *n* lines of context. Return a :term:`generator` of groups with up to *n* lines of context.
Starting with the groups returned by :meth:`get_opcodes`, this method splits out Starting with the groups returned by :meth:`get_opcodes`, this method
smaller change clusters and eliminates intervening ranges which have no changes. splits out smaller change clusters and eliminates intervening ranges which
have no changes.
The groups are returned in the same format as :meth:`get_opcodes`. The groups are returned in the same format as :meth:`get_opcodes`.
.. method:: SequenceMatcher.ratio() .. method:: ratio()
Return a measure of the sequences' similarity as a float in the range [0, 1]. Return a measure of the sequences' similarity as a float in the range [0,
1].
Where T is the total number of elements in both sequences, and M is the number Where T is the total number of elements in both sequences, and M is the
of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the sequences are number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
identical, and ``0.0`` if they have nothing in common. sequences are identical, and ``0.0`` if they have nothing in common.
This is expensive to compute if :meth:`get_matching_blocks` or This is expensive to compute if :meth:`get_matching_blocks` or
:meth:`get_opcodes` hasn't already been called, in which case you may want to :meth:`get_opcodes` hasn't already been called, in which case you may want
try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper bound. to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
upper bound.
.. method:: SequenceMatcher.quick_ratio() .. method:: quick_ratio()
Return an upper bound on :meth:`ratio` relatively quickly. Return an upper bound on :meth:`ratio` relatively quickly.
This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
faster to compute. is faster to compute.
.. method:: SequenceMatcher.real_quick_ratio() .. method:: real_quick_ratio()
Return an upper bound on :meth:`ratio` very quickly. Return an upper bound on :meth:`ratio` very quickly.
This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`.
The three methods that return the ratio of matching to total characters can give The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although different results due to differing levels of approximation, although
...@@ -589,10 +594,10 @@ The :class:`Differ` class has this constructor: ...@@ -589,10 +594,10 @@ The :class:`Differ` class has this constructor:
length 1), and returns true if the character is junk. The default is ``None``, length 1), and returns true if the character is junk. The default is ``None``,
meaning that no character is considered junk. meaning that no character is considered junk.
:class:`Differ` objects are used (deltas generated) via a single method: :class:`Differ` objects are used (deltas generated) via a single method:
.. method:: Differ.compare(a, b) .. method:: Differ.compare(a, b)
Compare two sequences of lines, and generate the delta (a sequence of lines). Compare two sequences of lines, and generate the delta (a sequence of lines).
......
...@@ -1113,17 +1113,17 @@ DocTest Objects ...@@ -1113,17 +1113,17 @@ DocTest Objects
names. names.
:class:`DocTest` defines the following member variables. They are initialized :class:`DocTest` defines the following member variables. They are initialized by
by the constructor, and should not be modified directly. the constructor, and should not be modified directly.
.. attribute:: DocTest.examples .. attribute:: examples
A list of :class:`Example` objects encoding the individual interactive Python A list of :class:`Example` objects encoding the individual interactive Python
examples that should be run by this test. examples that should be run by this test.
.. attribute:: DocTest.globs .. attribute:: globs
The namespace (aka globals) that the examples should be run in. This is a The namespace (aka globals) that the examples should be run in. This is a
dictionary mapping names to values. Any changes to the namespace made by the dictionary mapping names to values. Any changes to the namespace made by the
...@@ -1131,27 +1131,27 @@ by the constructor, and should not be modified directly. ...@@ -1131,27 +1131,27 @@ by the constructor, and should not be modified directly.
after the test is run. after the test is run.
.. attribute:: DocTest.name .. attribute:: name
A string name identifying the :class:`DocTest`. Typically, this is the name of A string name identifying the :class:`DocTest`. Typically, this is the name
the object or file that the test was extracted from. of the object or file that the test was extracted from.
.. attribute:: DocTest.filename .. attribute:: filename
The name of the file that this :class:`DocTest` was extracted from; or ``None`` The name of the file that this :class:`DocTest` was extracted from; or
if the filename is unknown, or if the :class:`DocTest` was not extracted from a ``None`` if the filename is unknown, or if the :class:`DocTest` was not
file. extracted from a file.
.. attribute:: DocTest.lineno .. attribute:: lineno
The line number within :attr:`filename` where this :class:`DocTest` begins, or The line number within :attr:`filename` where this :class:`DocTest` begins, or
``None`` if the line number is unavailable. This line number is zero-based with ``None`` if the line number is unavailable. This line number is zero-based
respect to the beginning of the file. with respect to the beginning of the file.
.. attribute:: DocTest.docstring .. attribute:: docstring
The string that the test was extracted from, or 'None' if the string is The string that the test was extracted from, or 'None' if the string is
unavailable, or if the test was not extracted from a string. unavailable, or if the test was not extracted from a string.
...@@ -1170,26 +1170,26 @@ Example Objects ...@@ -1170,26 +1170,26 @@ Example Objects
of the same names. of the same names.
:class:`Example` defines the following member variables. They are initialized :class:`Example` defines the following member variables. They are initialized by
by the constructor, and should not be modified directly. the constructor, and should not be modified directly.
.. attribute:: Example.source .. attribute:: source
A string containing the example's source code. This source code consists of a A string containing the example's source code. This source code consists of a
single Python statement, and always ends with a newline; the constructor adds a single Python statement, and always ends with a newline; the constructor adds
newline when necessary. a newline when necessary.
.. attribute:: Example.want .. attribute:: want
The expected output from running the example's source code (either from stdout, The expected output from running the example's source code (either from
or a traceback in case of exception). :attr:`want` ends with a newline unless stdout, or a traceback in case of exception). :attr:`want` ends with a
no output is expected, in which case it's an empty string. The constructor adds newline unless no output is expected, in which case it's an empty string. The
a newline when necessary. constructor adds a newline when necessary.
.. attribute:: Example.exc_msg .. attribute:: exc_msg
The exception message generated by the example, if the example is expected to The exception message generated by the example, if the example is expected to
generate an exception; or ``None`` if it is not expected to generate an generate an exception; or ``None`` if it is not expected to generate an
...@@ -1198,24 +1198,24 @@ by the constructor, and should not be modified directly. ...@@ -1198,24 +1198,24 @@ by the constructor, and should not be modified directly.
unless it's ``None``. The constructor adds a newline if needed. unless it's ``None``. The constructor adds a newline if needed.
.. attribute:: Example.lineno .. attribute:: lineno
The line number within the string containing this example where the example The line number within the string containing this example where the example
begins. This line number is zero-based with respect to the beginning of the begins. This line number is zero-based with respect to the beginning of the
containing string. containing string.
.. attribute:: Example.indent .. attribute:: indent
The example's indentation in the containing string, i.e., the number of space The example's indentation in the containing string, i.e., the number of space
characters that precede the example's first prompt. characters that precede the example's first prompt.
.. attribute:: Example.options .. attribute:: options
A dictionary mapping from option flags to ``True`` or ``False``, which is used A dictionary mapping from option flags to ``True`` or ``False``, which is used
to override default options for this example. Any option flags not contained in to override default options for this example. Any option flags not contained
this dictionary are left at their default value (as specified by the in this dictionary are left at their default value (as specified by the
:class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
...@@ -1246,21 +1246,21 @@ DocTestFinder objects ...@@ -1246,21 +1246,21 @@ DocTestFinder objects
:meth:`DocTestFinder.find` will include tests for objects with empty docstrings. :meth:`DocTestFinder.find` will include tests for objects with empty docstrings.
:class:`DocTestFinder` defines the following method: :class:`DocTestFinder` defines the following method:
.. method:: DocTestFinder.find(obj[, name][, module][, globs][, extraglobs]) .. method:: find(obj[, name][, module][, globs][, extraglobs])
Return a list of the :class:`DocTest`\ s that are defined by *obj*'s docstring, Return a list of the :class:`DocTest`\ s that are defined by *obj*'s
or by any of its contained objects' docstrings. docstring, or by any of its contained objects' docstrings.
The optional argument *name* specifies the object's name; this name will be used The optional argument *name* specifies the object's name; this name will be
to construct names for the returned :class:`DocTest`\ s. If *name* is not used to construct names for the returned :class:`DocTest`\ s. If *name* is
specified, then ``obj.__name__`` is used. not specified, then ``obj.__name__`` is used.
The optional parameter *module* is the module that contains the given object. The optional parameter *module* is the module that contains the given object.
If the module is not specified or is None, then the test finder will attempt to If the module is not specified or is None, then the test finder will attempt
automatically determine the correct module. The object's module is used: to automatically determine the correct module. The object's module is used:
* As a default namespace, if *globs* is not specified. * As a default namespace, if *globs* is not specified.
...@@ -1280,8 +1280,8 @@ DocTestFinder objects ...@@ -1280,8 +1280,8 @@ DocTestFinder objects
The globals for each :class:`DocTest` is formed by combining *globs* and The globals for each :class:`DocTest` is formed by combining *globs* and
*extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
shallow copy of the globals dictionary is created for each :class:`DocTest`. If shallow copy of the globals dictionary is created for each :class:`DocTest`.
*globs* is not specified, then it defaults to the module's *__dict__*, if If *globs* is not specified, then it defaults to the module's *__dict__*, if
specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
defaults to ``{}``. defaults to ``{}``.
...@@ -1298,10 +1298,10 @@ DocTestParser objects ...@@ -1298,10 +1298,10 @@ DocTestParser objects
them to create a :class:`DocTest` object. them to create a :class:`DocTest` object.
:class:`DocTestParser` defines the following methods: :class:`DocTestParser` defines the following methods:
.. method:: DocTestParser.get_doctest(string, globs, name, filename, lineno) .. method:: get_doctest(string, globs, name, filename, lineno)
Extract all doctest examples from the given string, and collect them into a Extract all doctest examples from the given string, and collect them into a
:class:`DocTest` object. :class:`DocTest` object.
...@@ -1311,17 +1311,17 @@ DocTestParser objects ...@@ -1311,17 +1311,17 @@ DocTestParser objects
information. information.
.. method:: DocTestParser.get_examples(string[, name]) .. method:: get_examples(string[, name])
Extract all doctest examples from the given string, and return them as a list of Extract all doctest examples from the given string, and return them as a list
:class:`Example` objects. Line numbers are 0-based. The optional argument of :class:`Example` objects. Line numbers are 0-based. The optional argument
*name* is a name identifying this string, and is only used for error messages. *name* is a name identifying this string, and is only used for error messages.
.. method:: DocTestParser.parse(string[, name]) .. method:: parse(string[, name])
Divide the given string into examples and intervening text, and return them as a Divide the given string into examples and intervening text, and return them as
list of alternating :class:`Example`\ s and strings. Line numbers for the a list of alternating :class:`Example`\ s and strings. Line numbers for the
:class:`Example`\ s are 0-based. The optional argument *name* is a name :class:`Example`\ s are 0-based. The optional argument *name* is a name
identifying this string, and is only used for error messages. identifying this string, and is only used for error messages.
...@@ -1366,81 +1366,81 @@ DocTestRunner objects ...@@ -1366,81 +1366,81 @@ DocTestRunner objects
For more information, see section :ref:`doctest-options`. For more information, see section :ref:`doctest-options`.
:class:`DocTestParser` defines the following methods: :class:`DocTestParser` defines the following methods:
.. method:: DocTestRunner.report_start(out, test, example) .. method:: report_start(out, test, example)
Report that the test runner is about to process the given example. This method Report that the test runner is about to process the given example. This method
is provided to allow subclasses of :class:`DocTestRunner` to customize their is provided to allow subclasses of :class:`DocTestRunner` to customize their
output; it should not be called directly. output; it should not be called directly.
*example* is the example about to be processed. *test* is the test containing *example* is the example about to be processed. *test* is the test
*example*. *out* is the output function that was passed to *containing example*. *out* is the output function that was passed to
:meth:`DocTestRunner.run`. :meth:`DocTestRunner.run`.
.. method:: DocTestRunner.report_success(out, test, example, got) .. method:: report_success(out, test, example, got)
Report that the given example ran successfully. This method is provided to Report that the given example ran successfully. This method is provided to
allow subclasses of :class:`DocTestRunner` to customize their output; it should allow subclasses of :class:`DocTestRunner` to customize their output; it
not be called directly. should not be called directly.
*example* is the example about to be processed. *got* is the actual output from *example* is the example about to be processed. *got* is the actual output
the example. *test* is the test containing *example*. *out* is the output from the example. *test* is the test containing *example*. *out* is the
function that was passed to :meth:`DocTestRunner.run`. output function that was passed to :meth:`DocTestRunner.run`.
.. method:: DocTestRunner.report_failure(out, test, example, got) .. method:: report_failure(out, test, example, got)
Report that the given example failed. This method is provided to allow Report that the given example failed. This method is provided to allow
subclasses of :class:`DocTestRunner` to customize their output; it should not be subclasses of :class:`DocTestRunner` to customize their output; it should not
called directly. be called directly.
*example* is the example about to be processed. *got* is the actual output from *example* is the example about to be processed. *got* is the actual output
the example. *test* is the test containing *example*. *out* is the output from the example. *test* is the test containing *example*. *out* is the
function that was passed to :meth:`DocTestRunner.run`. output function that was passed to :meth:`DocTestRunner.run`.
.. method:: DocTestRunner.report_unexpected_exception(out, test, example, exc_info) .. method:: report_unexpected_exception(out, test, example, exc_info)
Report that the given example raised an unexpected exception. This method is Report that the given example raised an unexpected exception. This method is
provided to allow subclasses of :class:`DocTestRunner` to customize their provided to allow subclasses of :class:`DocTestRunner` to customize their
output; it should not be called directly. output; it should not be called directly.
*example* is the example about to be processed. *exc_info* is a tuple containing *example* is the example about to be processed. *exc_info* is a tuple
information about the unexpected exception (as returned by containing information about the unexpected exception (as returned by
:func:`sys.exc_info`). *test* is the test containing *example*. *out* is the :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the
output function that was passed to :meth:`DocTestRunner.run`. output function that was passed to :meth:`DocTestRunner.run`.
.. method:: DocTestRunner.run(test[, compileflags][, out][, clear_globs]) .. method:: run(test[, compileflags][, out][, clear_globs])
Run the examples in *test* (a :class:`DocTest` object), and display the results Run the examples in *test* (a :class:`DocTest` object), and display the
using the writer function *out*. results using the writer function *out*.
The examples are run in the namespace ``test.globs``. If *clear_globs* is true The examples are run in the namespace ``test.globs``. If *clear_globs* is
(the default), then this namespace will be cleared after the test runs, to help true (the default), then this namespace will be cleared after the test runs,
with garbage collection. If you would like to examine the namespace after the to help with garbage collection. If you would like to examine the namespace
test completes, then use *clear_globs=False*. after the test completes, then use *clear_globs=False*.
*compileflags* gives the set of flags that should be used by the Python compiler *compileflags* gives the set of flags that should be used by the Python
when running the examples. If not specified, then it will default to the set of compiler when running the examples. If not specified, then it will default to
future-import flags that apply to *globs*. the set of future-import flags that apply to *globs*.
The output of each example is checked using the :class:`DocTestRunner`'s output The output of each example is checked using the :class:`DocTestRunner`'s
checker, and the results are formatted by the :meth:`DocTestRunner.report_\*` output checker, and the results are formatted by the
methods. :meth:`DocTestRunner.report_\*` methods.
.. method:: DocTestRunner.summarize([verbose]) .. method:: summarize([verbose])
Print a summary of all the test cases that have been run by this DocTestRunner, Print a summary of all the test cases that have been run by this DocTestRunner,
and return a :term:`named tuple` ``TestResults(failed, attempted)``. and return a :term:`named tuple` ``TestResults(failed, attempted)``.
The optional *verbose* argument controls how detailed the summary is. If the The optional *verbose* argument controls how detailed the summary is. If the
verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used. verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
used.
.. _doctest-outputchecker: .. _doctest-outputchecker:
...@@ -1457,18 +1457,18 @@ OutputChecker objects ...@@ -1457,18 +1457,18 @@ OutputChecker objects
the differences between two outputs. the differences between two outputs.
:class:`OutputChecker` defines the following methods: :class:`OutputChecker` defines the following methods:
.. method:: OutputChecker.check_output(want, got, optionflags) .. method:: check_output(want, got, optionflags)
Return ``True`` iff the actual output from an example (*got*) matches the Return ``True`` iff the actual output from an example (*got*) matches the
expected output (*want*). These strings are always considered to match if they expected output (*want*). These strings are always considered to match if
are identical; but depending on what option flags the test runner is using, they are identical; but depending on what option flags the test runner is
several non-exact match types are also possible. See section using, several non-exact match types are also possible. See section
:ref:`doctest-options` for more information about option flags. :ref:`doctest-options` for more information about option flags.
.. method:: OutputChecker.output_difference(example, got, optionflags) .. method:: output_difference(example, got, optionflags)
Return a string describing the differences between the expected output for a Return a string describing the differences between the expected output for a
given example (*example*) and the actual output (*got*). *optionflags* is the given example (*example*) and the actual output (*got*). *optionflags* is the
......
...@@ -38,164 +38,168 @@ Import this class from the :mod:`email.charset` module. ...@@ -38,164 +38,168 @@ Import this class from the :mod:`email.charset` module.
will not be encoded, but output text will be converted from the ``euc-jp`` will not be encoded, but output text will be converted from the ``euc-jp``
character set to the ``iso-2022-jp`` character set. character set to the ``iso-2022-jp`` character set.
:class:`Charset` instances have the following data attributes: :class:`Charset` instances have the following data attributes:
.. data:: input_charset .. attribute:: input_charset
The initial character set specified. Common aliases are converted to their The initial character set specified. Common aliases are converted to
*official* email names (e.g. ``latin_1`` is converted to ``iso-8859-1``). their *official* email names (e.g. ``latin_1`` is converted to
Defaults to 7-bit ``us-ascii``. ``iso-8859-1``). Defaults to 7-bit ``us-ascii``.
.. data:: header_encoding .. attribute:: header_encoding
If the character set must be encoded before it can be used in an email header, If the character set must be encoded before it can be used in an email
this attribute will be set to ``Charset.QP`` (for quoted-printable), header, this attribute will be set to ``Charset.QP`` (for
``Charset.BASE64`` (for base64 encoding), or ``Charset.SHORTEST`` for the quoted-printable), ``Charset.BASE64`` (for base64 encoding), or
shortest of QP or BASE64 encoding. Otherwise, it will be ``None``. ``Charset.SHORTEST`` for the shortest of QP or BASE64 encoding. Otherwise,
it will be ``None``.
.. data:: body_encoding .. attribute:: body_encoding
Same as *header_encoding*, but describes the encoding for the mail message's Same as *header_encoding*, but describes the encoding for the mail
body, which indeed may be different than the header encoding. message's body, which indeed may be different than the header encoding.
``Charset.SHORTEST`` is not allowed for *body_encoding*. ``Charset.SHORTEST`` is not allowed for *body_encoding*.
.. data:: output_charset .. attribute:: output_charset
Some character sets must be converted before they can be used in email headers Some character sets must be converted before they can be used in email headers
or bodies. If the *input_charset* is one of them, this attribute will contain or bodies. If the *input_charset* is one of them, this attribute will
the name of the character set output will be converted to. Otherwise, it will contain the name of the character set output will be converted to. Otherwise, it will
be ``None``. be ``None``.
.. data:: input_codec .. attribute:: input_codec
The name of the Python codec used to convert the *input_charset* to Unicode. If The name of the Python codec used to convert the *input_charset* to
no conversion codec is necessary, this attribute will be ``None``. Unicode. If no conversion codec is necessary, this attribute will be
``None``.
.. data:: output_codec .. attribute:: output_codec
The name of the Python codec used to convert Unicode to the *output_charset*. The name of the Python codec used to convert Unicode to the
If no conversion codec is necessary, this attribute will have the same value as *output_charset*. If no conversion codec is necessary, this attribute
the *input_codec*. will have the same value as the *input_codec*.
:class:`Charset` instances also have the following methods: :class:`Charset` instances also have the following methods:
.. method:: Charset.get_body_encoding() .. method:: get_body_encoding()
Return the content transfer encoding used for body encoding. Return the content transfer encoding used for body encoding.
This is either the string ``quoted-printable`` or ``base64`` depending on the This is either the string ``quoted-printable`` or ``base64`` depending on
encoding used, or it is a function, in which case you should call the function the encoding used, or it is a function, in which case you should call the
with a single argument, the Message object being encoded. The function should function with a single argument, the Message object being encoded. The
then set the :mailheader:`Content-Transfer-Encoding` header itself to whatever function should then set the :mailheader:`Content-Transfer-Encoding`
is appropriate. header itself to whatever is appropriate.
Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, returns Returns the string ``quoted-printable`` if *body_encoding* is ``QP``,
the string ``base64`` if *body_encoding* is ``BASE64``, and returns the string returns the string ``base64`` if *body_encoding* is ``BASE64``, and
``7bit`` otherwise. returns the string ``7bit`` otherwise.
.. method:: Charset.convert(s) .. method:: convert(s)
Convert the string *s* from the *input_codec* to the *output_codec*. Convert the string *s* from the *input_codec* to the *output_codec*.
.. method:: Charset.to_splittable(s) .. method:: to_splittable(s)
Convert a possibly multibyte string to a safely splittable format. *s* is the Convert a possibly multibyte string to a safely splittable format. *s* is
string to split. the string to split.
Uses the *input_codec* to try and convert the string to Unicode, so it can be Uses the *input_codec* to try and convert the string to Unicode, so it can
safely split on character boundaries (even for multibyte characters). be safely split on character boundaries (even for multibyte characters).
Returns the string as-is if it isn't known how to convert *s* to Unicode with Returns the string as-is if it isn't known how to convert *s* to Unicode
the *input_charset*. with the *input_charset*.
Characters that could not be converted to Unicode will be replaced with the Characters that could not be converted to Unicode will be replaced with
Unicode replacement character ``'U+FFFD'``. the Unicode replacement character ``'U+FFFD'``.
.. method:: Charset.from_splittable(ustr[, to_output]) .. method:: from_splittable(ustr[, to_output])
Convert a splittable string back into an encoded string. *ustr* is a Unicode Convert a splittable string back into an encoded string. *ustr* is a
string to "unsplit". Unicode string to "unsplit".
This method uses the proper codec to try and convert the string from Unicode This method uses the proper codec to try and convert the string from
back into an encoded format. Return the string as-is if it is not Unicode, or Unicode back into an encoded format. Return the string as-is if it is not
if it could not be converted from Unicode. Unicode, or if it could not be converted from Unicode.
Characters that could not be converted from Unicode will be replaced with an Characters that could not be converted from Unicode will be replaced with
appropriate character (usually ``'?'``). an appropriate character (usually ``'?'``).
If *to_output* is ``True`` (the default), uses *output_codec* to convert to an If *to_output* is ``True`` (the default), uses *output_codec* to convert
encoded format. If *to_output* is ``False``, it uses *input_codec*. to an encoded format. If *to_output* is ``False``, it uses *input_codec*.
.. method:: Charset.get_output_charset() .. method:: get_output_charset()
Return the output character set. Return the output character set.
This is the *output_charset* attribute if that is not ``None``, otherwise it is This is the *output_charset* attribute if that is not ``None``, otherwise
*input_charset*. it is *input_charset*.
.. method:: Charset.encoded_header_len() .. method:: encoded_header_len()
Return the length of the encoded header string, properly calculating for Return the length of the encoded header string, properly calculating for
quoted-printable or base64 encoding. quoted-printable or base64 encoding.
.. method:: Charset.header_encode(s[, convert]) .. method:: header_encode(s[, convert])
Header-encode the string *s*. Header-encode the string *s*.
If *convert* is ``True``, the string will be converted from the input charset to If *convert* is ``True``, the string will be converted from the input
the output charset automatically. This is not useful for multibyte character charset to the output charset automatically. This is not useful for
sets, which have line length issues (multibyte characters must be split on a multibyte character sets, which have line length issues (multibyte
character, not a byte boundary); use the higher-level :class:`Header` class to characters must be split on a character, not a byte boundary); use the
deal with these issues (see :mod:`email.header`). *convert* defaults to higher-level :class:`Header` class to deal with these issues (see
``False``. :mod:`email.header`). *convert* defaults to ``False``.
The type of encoding (base64 or quoted-printable) will be based on the The type of encoding (base64 or quoted-printable) will be based on the
*header_encoding* attribute. *header_encoding* attribute.
.. method:: Charset.body_encode(s[, convert]) .. method:: body_encode(s[, convert])
Body-encode the string *s*. Body-encode the string *s*.
If *convert* is ``True`` (the default), the string will be converted from the If *convert* is ``True`` (the default), the string will be converted from
input charset to output charset automatically. Unlike :meth:`header_encode`, the input charset to output charset automatically. Unlike
there are no issues with byte boundaries and multibyte charsets in email bodies, :meth:`header_encode`, there are no issues with byte boundaries and
so this is usually pretty safe. multibyte charsets in email bodies, so this is usually pretty safe.
The type of encoding (base64 or quoted-printable) will be based on the The type of encoding (base64 or quoted-printable) will be based on the
*body_encoding* attribute. *body_encoding* attribute.
The :class:`Charset` class also provides a number of methods to support standard The :class:`Charset` class also provides a number of methods to support
operations and built-in functions. standard operations and built-in functions.
.. method:: Charset.__str__() .. method:: __str__()
Returns *input_charset* as a string coerced to lower case. :meth:`__repr__` is Returns *input_charset* as a string coerced to lower
an alias for :meth:`__str__`. case. :meth:`__repr__` is an alias for :meth:`__str__`.
.. method:: Charset.__eq__(other) .. method:: __eq__(other)
This method allows you to compare two :class:`Charset` instances for equality. This method allows you to compare two :class:`Charset` instances for
equality.
.. method:: Header.__ne__(other) .. method:: __ne__(other)
This method allows you to compare two :class:`Charset` instances for inequality. This method allows you to compare two :class:`Charset` instances for
inequality.
The :mod:`email.charset` module also provides the following functions for adding The :mod:`email.charset` module also provides the following functions for adding
new entries to the global character set, alias, and codec registries: new entries to the global character set, alias, and codec registries:
......
...@@ -44,35 +44,34 @@ Here are the public methods of the :class:`Generator` class, imported from the ...@@ -44,35 +44,34 @@ Here are the public methods of the :class:`Generator` class, imported from the
:mod:`email.header.Header` class. Set to zero to disable header wrapping. The :mod:`email.header.Header` class. Set to zero to disable header wrapping. The
default is 78, as recommended (but not required) by :rfc:`2822`. default is 78, as recommended (but not required) by :rfc:`2822`.
The other public :class:`Generator` methods are: The other public :class:`Generator` methods are:
.. method:: Generator.flatten(msg[, unixfrom]) .. method:: flatten(msg[, unixfrom])
Print the textual representation of the message object structure rooted at *msg* Print the textual representation of the message object structure rooted at
to the output file specified when the :class:`Generator` instance was created. *msg* to the output file specified when the :class:`Generator` instance
Subparts are visited depth-first and the resulting text will be properly MIME was created. Subparts are visited depth-first and the resulting text will
encoded. be properly MIME encoded.
Optional *unixfrom* is a flag that forces the printing of the envelope header Optional *unixfrom* is a flag that forces the printing of the envelope
delimiter before the first :rfc:`2822` header of the root message object. If header delimiter before the first :rfc:`2822` header of the root message
the root object has no envelope header, a standard one is crafted. By default, object. If the root object has no envelope header, a standard one is
this is set to ``False`` to inhibit the printing of the envelope delimiter. crafted. By default, this is set to ``False`` to inhibit the printing of
the envelope delimiter.
Note that for subparts, no envelope header is ever printed. Note that for subparts, no envelope header is ever printed.
.. method:: clone(fp)
.. method:: Generator.clone(fp) Return an independent clone of this :class:`Generator` instance with the
exact same options.
Return an independent clone of this :class:`Generator` instance with the exact .. method:: write(s)
same options.
.. method:: Generator.write(s)
Write the string *s* to the underlying file object, i.e. *outfp* passed to Write the string *s* to the underlying file object, i.e. *outfp* passed to
:class:`Generator`'s constructor. This provides just enough file-like API for :class:`Generator`'s constructor. This provides just enough file-like API
:class:`Generator` instances to be used in the :func:`print` function. for :class:`Generator` instances to be used in the :func:`print` function.
As a convenience, see the methods :meth:`Message.as_string` and As a convenience, see the methods :meth:`Message.as_string` and
``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation
......
...@@ -74,65 +74,66 @@ Here is the :class:`Header` class description: ...@@ -74,65 +74,66 @@ Here is the :class:`Header` class description:
and is usually either a space or a hard tab character. This character will be and is usually either a space or a hard tab character. This character will be
prepended to continuation lines. prepended to continuation lines.
Optional *errors* is passed straight through to the :meth:`append` method. Optional *errors* is passed straight through to the :meth:`append` method.
.. method:: Header.append(s[, charset[, errors]]) .. method:: append(s[, charset[, errors]])
Append the string *s* to the MIME header. Append the string *s* to the MIME header.
Optional *charset*, if given, should be a :class:`Charset` instance (see Optional *charset*, if given, should be a :class:`Charset` instance (see
:mod:`email.charset`) or the name of a character set, which will be converted to :mod:`email.charset`) or the name of a character set, which will be
a :class:`Charset` instance. A value of ``None`` (the default) means that the converted to a :class:`Charset` instance. A value of ``None`` (the
*charset* given in the constructor is used. default) means that the *charset* given in the constructor is used.
*s* may be an instance of :class:`bytes` or :class:`str`. If it is an instance *s* may be an instance of :class:`bytes` or :class:`str`. If it is an
of :class:`bytes`, then *charset* is the encoding of that byte string, and a instance of :class:`bytes`, then *charset* is the encoding of that byte
:exc:`UnicodeError` will be raised if the string cannot be decoded with that string, and a :exc:`UnicodeError` will be raised if the string cannot be
character set. decoded with that character set.
If *s* is an instance of :class:`str`, then *charset* is a hint specifying the If *s* is an instance of :class:`str`, then *charset* is a hint specifying
character set of the characters in the string. In this case, when producing an the character set of the characters in the string. In this case, when
:rfc:`2822`\ -compliant header using :rfc:`2047` rules, the Unicode string will producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the
be encoded using the following charsets in order: ``us-ascii``, the *charset* Unicode string will be encoded using the following charsets in order:
hint, ``utf-8``. The first character set to not provoke a :exc:`UnicodeError` ``us-ascii``, the *charset* hint, ``utf-8``. The first character set to
is used. not provoke a :exc:`UnicodeError` is used.
Optional *errors* is passed through to any :func:`encode` or Optional *errors* is passed through to any :func:`encode` or
:func:`ustr.encode` call, and defaults to "strict". :func:`ustr.encode` call, and defaults to "strict".
.. method:: Header.encode([splitchars]) .. method:: encode([splitchars])
Encode a message header into an RFC-compliant format, possibly wrapping long Encode a message header into an RFC-compliant format, possibly wrapping
lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings. long lines and encapsulating non-ASCII parts in base64 or quoted-printable
Optional *splitchars* is a string containing characters to split long ASCII encodings. Optional *splitchars* is a string containing characters to
lines on, in rough support of :rfc:`2822`'s *highest level syntactic breaks*. split long ASCII lines on, in rough support of :rfc:`2822`'s *highest
This doesn't affect :rfc:`2047` encoded lines. level syntactic breaks*. This doesn't affect :rfc:`2047` encoded lines.
The :class:`Header` class also provides a number of methods to support standard The :class:`Header` class also provides a number of methods to support
operators and built-in functions. standard operators and built-in functions.
.. method:: Header.__str__() .. method:: __str__()
A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``.
.. method:: Header.__unicode__() .. method:: __unicode__()
A helper for :class:`str`'s :func:`encode` method. Returns the header as a A helper for :class:`str`'s :func:`encode` method. Returns the header as
Unicode string. a Unicode string.
.. method:: __eq__(other)
.. method:: Header.__eq__(other) This method allows you to compare two :class:`Header` instances for
equality.
This method allows you to compare two :class:`Header` instances for equality.
.. method:: __ne__(other)
.. method:: Header.__ne__(other) This method allows you to compare two :class:`Header` instances for
inequality.
This method allows you to compare two :class:`Header` instances for inequality.
The :mod:`email.header` module also provides the following convenient functions. The :mod:`email.header` module also provides the following convenient functions.
......
...@@ -36,16 +36,17 @@ Here are the methods of the :class:`Message` class: ...@@ -36,16 +36,17 @@ Here are the methods of the :class:`Message` class:
The constructor takes no arguments. The constructor takes no arguments.
.. method:: Message.as_string([unixfrom]) .. method:: as_string([unixfrom])
Return the entire message flattened as a string. When optional *unixfrom* is Return the entire message flattened as a string. When optional *unixfrom*
``True``, the envelope header is included in the returned string. *unixfrom* is ``True``, the envelope header is included in the returned string.
defaults to ``False``. *unixfrom* defaults to ``False``.
Note that this method is provided as a convenience and may not always format the Note that this method is provided as a convenience and may not always
message the way you want. For example, by default it mangles lines that begin format the message the way you want. For example, by default it mangles
with ``From``. For more flexibility, instantiate a :class:`Generator` instance lines that begin with ``From``. For more flexibility, instantiate a
and use its :meth:`flatten` method directly. For example:: :class:`Generator` instance and use its :meth:`flatten` method directly.
For example::
from cStringIO import StringIO from cStringIO import StringIO
from email.generator import Generator from email.generator import Generator
...@@ -55,136 +56,138 @@ Here are the methods of the :class:`Message` class: ...@@ -55,136 +56,138 @@ Here are the methods of the :class:`Message` class:
text = fp.getvalue() text = fp.getvalue()
.. method:: Message.__str__() .. method:: __str__()
Equivalent to ``as_string(unixfrom=True)``. Equivalent to ``as_string(unixfrom=True)``.
.. method:: Message.is_multipart() .. method:: is_multipart()
Return ``True`` if the message's payload is a list of sub-\ :class:`Message` Return ``True`` if the message's payload is a list of sub-\
objects, otherwise return ``False``. When :meth:`is_multipart` returns False, :class:`Message` objects, otherwise return ``False``. When
the payload should be a string object. :meth:`is_multipart` returns False, the payload should be a string object.
.. method:: Message.set_unixfrom(unixfrom) .. method:: set_unixfrom(unixfrom)
Set the message's envelope header to *unixfrom*, which should be a string. Set the message's envelope header to *unixfrom*, which should be a string.
.. method:: Message.get_unixfrom() .. method:: get_unixfrom()
Return the message's envelope header. Defaults to ``None`` if the envelope Return the message's envelope header. Defaults to ``None`` if the
header was never set. envelope header was never set.
.. method:: Message.attach(payload) .. method:: attach(payload)
Add the given *payload* to the current payload, which must be ``None`` or a list Add the given *payload* to the current payload, which must be ``None`` or
of :class:`Message` objects before the call. After the call, the payload will a list of :class:`Message` objects before the call. After the call, the
always be a list of :class:`Message` objects. If you want to set the payload to payload will always be a list of :class:`Message` objects. If you want to
a scalar object (e.g. a string), use :meth:`set_payload` instead. set the payload to a scalar object (e.g. a string), use
:meth:`set_payload` instead.
.. method:: Message.get_payload([i[, decode]]) .. method:: get_payload([i[, decode]])
Return a reference the current payload, which will be a list of :class:`Message` Return a reference the current payload, which will be a list of
objects when :meth:`is_multipart` is ``True``, or a string when :class:`Message` objects when :meth:`is_multipart` is ``True``, or a
:meth:`is_multipart` is ``False``. If the payload is a list and you mutate the string when :meth:`is_multipart` is ``False``. If the payload is a list
list object, you modify the message's payload in place. and you mutate the list object, you modify the message's payload in place.
With optional argument *i*, :meth:`get_payload` will return the *i*-th element With optional argument *i*, :meth:`get_payload` will return the *i*-th
of the payload, counting from zero, if :meth:`is_multipart` is ``True``. An element of the payload, counting from zero, if :meth:`is_multipart` is
:exc:`IndexError` will be raised if *i* is less than 0 or greater than or equal ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or
to the number of items in the payload. If the payload is a string (i.e. greater than or equal to the number of items in the payload. If the
:meth:`is_multipart` is ``False``) and *i* is given, a :exc:`TypeError` is payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is
raised. given, a :exc:`TypeError` is raised.
Optional *decode* is a flag indicating whether the payload should be decoded or Optional *decode* is a flag indicating whether the payload should be
not, according to the :mailheader:`Content-Transfer-Encoding` header. When decoded or not, according to the :mailheader:`Content-Transfer-Encoding`
``True`` and the message is not a multipart, the payload will be decoded if this header. When ``True`` and the message is not a multipart, the payload will
header's value is ``quoted-printable`` or ``base64``. If some other encoding is be decoded if this header's value is ``quoted-printable`` or ``base64``.
used, or :mailheader:`Content-Transfer-Encoding` header is missing, or if the If some other encoding is used, or :mailheader:`Content-Transfer-Encoding`
payload has bogus base64 data, the payload is returned as-is (undecoded). If header is missing, or if the payload has bogus base64 data, the payload is
the message is a multipart and the *decode* flag is ``True``, then ``None`` is returned as-is (undecoded). If the message is a multipart and the
returned. The default for *decode* is ``False``. *decode* flag is ``True``, then ``None`` is returned. The default for
*decode* is ``False``.
.. method:: Message.set_payload(payload[, charset]) .. method:: set_payload(payload[, charset])
Set the entire message object's payload to *payload*. It is the client's Set the entire message object's payload to *payload*. It is the client's
responsibility to ensure the payload invariants. Optional *charset* sets the responsibility to ensure the payload invariants. Optional *charset* sets
message's default character set; see :meth:`set_charset` for details. the message's default character set; see :meth:`set_charset` for details.
.. method:: set_charset(charset)
.. method:: Message.set_charset(charset)
Set the character set of the payload to *charset*, which can either be a Set the character set of the payload to *charset*, which can either be a
:class:`Charset` instance (see :mod:`email.charset`), a string naming a :class:`Charset` instance (see :mod:`email.charset`), a string naming a
character set, or ``None``. If it is a string, it will be converted to a character set, or ``None``. If it is a string, it will be converted to a
:class:`Charset` instance. If *charset* is ``None``, the ``charset`` parameter :class:`Charset` instance. If *charset* is ``None``, the ``charset``
will be removed from the :mailheader:`Content-Type` header. Anything else will parameter will be removed from the :mailheader:`Content-Type`
generate a :exc:`TypeError`. header. Anything else will generate a :exc:`TypeError`.
The message will be assumed to be of type :mimetype:`text/\*` encoded with The message will be assumed to be of type :mimetype:`text/\*` encoded with
*charset.input_charset*. It will be converted to *charset.output_charset* and *charset.input_charset*. It will be converted to *charset.output_charset*
encoded properly, if needed, when generating the plain text representation of and encoded properly, if needed, when generating the plain text
the message. MIME headers (:mailheader:`MIME-Version`, representation of the message. MIME headers (:mailheader:`MIME-Version`,
:mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will be :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will
added as needed. be added as needed.
.. method:: Message.get_charset() .. method:: get_charset()
Return the :class:`Charset` instance associated with the message's payload. Return the :class:`Charset` instance associated with the message's
payload.
The following methods implement a mapping-like interface for accessing the The following methods implement a mapping-like interface for accessing the
message's :rfc:`2822` headers. Note that there are some semantic differences message's :rfc:`2822` headers. Note that there are some semantic differences
between these methods and a normal mapping (i.e. dictionary) interface. For between these methods and a normal mapping (i.e. dictionary) interface. For
example, in a dictionary there are no duplicate keys, but here there may be example, in a dictionary there are no duplicate keys, but here there may be
duplicate message headers. Also, in dictionaries there is no guaranteed order duplicate message headers. Also, in dictionaries there is no guaranteed
to the keys returned by :meth:`keys`, but in a :class:`Message` object, headers order to the keys returned by :meth:`keys`, but in a :class:`Message` object,
are always returned in the order they appeared in the original message, or were headers are always returned in the order they appeared in the original
added to the message later. Any header deleted and then re-added are always message, or were added to the message later. Any header deleted and then
appended to the end of the header list. re-added are always appended to the end of the header list.
These semantic differences are intentional and are biased toward maximal These semantic differences are intentional and are biased toward maximal
convenience. convenience.
Note that in all cases, any envelope header present in the message is not Note that in all cases, any envelope header present in the message is not
included in the mapping interface. included in the mapping interface.
.. method:: Message.__len__() .. method:: __len__()
Return the total number of headers, including duplicates. Return the total number of headers, including duplicates.
.. method:: Message.__contains__(name) .. method:: __contains__(name)
Return true if the message object has a field named *name*. Matching is done Return true if the message object has a field named *name*. Matching is
case-insensitively and *name* should not include the trailing colon. Used for done case-insensitively and *name* should not include the trailing colon.
the ``in`` operator, e.g.:: Used for the ``in`` operator, e.g.::
if 'message-id' in myMessage: if 'message-id' in myMessage:
print('Message-ID:', myMessage['message-id']) print('Message-ID:', myMessage['message-id'])
.. method:: Message.__getitem__(name) .. method:: __getitem__(name)
Return the value of the named header field. *name* should not include the colon Return the value of the named header field. *name* should not include the
field separator. If the header is missing, ``None`` is returned; a colon field separator. If the header is missing, ``None`` is returned; a
:exc:`KeyError` is never raised. :exc:`KeyError` is never raised.
Note that if the named field appears more than once in the message's headers, Note that if the named field appears more than once in the message's
exactly which of those field values will be returned is undefined. Use the headers, exactly which of those field values will be returned is
:meth:`get_all` method to get the values of all the extant named headers. undefined. Use the :meth:`get_all` method to get the values of all the
extant named headers.
.. method:: Message.__setitem__(name, val) .. method:: __setitem__(name, val)
Add a header to the message with field name *name* and value *val*. The field Add a header to the message with field name *name* and value *val*. The
is appended to the end of the message's existing fields. field is appended to the end of the message's existing fields.
Note that this does *not* overwrite or delete any existing header with the same Note that this does *not* overwrite or delete any existing header with the same
name. If you want to ensure that the new header is the only one present in the name. If you want to ensure that the new header is the only one present in the
...@@ -194,59 +197,62 @@ included in the mapping interface. ...@@ -194,59 +197,62 @@ included in the mapping interface.
msg['subject'] = 'Python roolz!' msg['subject'] = 'Python roolz!'
.. method:: Message.__delitem__(name) .. method:: __delitem__(name)
Delete all occurrences of the field with name *name* from the message's headers. Delete all occurrences of the field with name *name* from the message's
No exception is raised if the named field isn't present in the headers. headers. No exception is raised if the named field isn't present in the headers.
.. method:: Message.__contains__(name) .. method:: Message.__contains__(name)
Return true if the message contains a header field named *name*, otherwise Return true if the message contains a header field named *name*, otherwise
return false. return false.
.. method:: Message.keys() .. method:: keys()
Return a list of all the message's header field names. Return a list of all the message's header field names.
.. method:: Message.values() .. method:: values()
Return a list of all the message's field values. Return a list of all the message's field values.
.. method:: Message.items() .. method:: items()
Return a list of 2-tuples containing all the message's field headers and values. Return a list of 2-tuples containing all the message's field headers and
values.
.. method:: Message.get(name[, failobj]) .. method:: get(name[, failobj])
Return the value of the named header field. This is identical to Return the value of the named header field. This is identical to
:meth:`__getitem__` except that optional *failobj* is returned if the named :meth:`__getitem__` except that optional *failobj* is returned if the
header is missing (defaults to ``None``). named header is missing (defaults to ``None``).
Here are some additional useful methods: Here are some additional useful methods:
.. method:: Message.get_all(name[, failobj]) .. method:: get_all(name[, failobj])
Return a list of all the values for the field named *name*. If there are no such Return a list of all the values for the field named *name*. If there are
named headers in the message, *failobj* is returned (defaults to ``None``). no such named headers in the message, *failobj* is returned (defaults to
``None``).
.. method:: Message.add_header(_name, _value, **_params) .. method:: add_header(_name, _value, **_params)
Extended header setting. This method is similar to :meth:`__setitem__` except Extended header setting. This method is similar to :meth:`__setitem__`
that additional header parameters can be provided as keyword arguments. *_name* except that additional header parameters can be provided as keyword
is the header field to add and *_value* is the *primary* value for the header. arguments. *_name* is the header field to add and *_value* is the
*primary* value for the header.
For each item in the keyword argument dictionary *_params*, the key is taken as For each item in the keyword argument dictionary *_params*, the key is
the parameter name, with underscores converted to dashes (since dashes are taken as the parameter name, with underscores converted to dashes (since
illegal in Python identifiers). Normally, the parameter will be added as dashes are illegal in Python identifiers). Normally, the parameter will
``key="value"`` unless the value is ``None``, in which case only the key will be be added as ``key="value"`` unless the value is ``None``, in which case
added. only the key will be added.
Here's an example:: Here's an example::
...@@ -257,174 +263,182 @@ Here are some additional useful methods: ...@@ -257,174 +263,182 @@ Here are some additional useful methods:
Content-Disposition: attachment; filename="bud.gif" Content-Disposition: attachment; filename="bud.gif"
.. method:: Message.replace_header(_name, _value) .. method:: replace_header(_name, _value)
Replace a header. Replace the first header found in the message that matches Replace a header. Replace the first header found in the message that
*_name*, retaining header order and field name case. If no matching header was matches *_name*, retaining header order and field name case. If no
found, a :exc:`KeyError` is raised. matching header was found, a :exc:`KeyError` is raised.
.. method:: Message.get_content_type() .. method:: get_content_type()
Return the message's content type. The returned string is coerced to lower case Return the message's content type. The returned string is coerced to
of the form :mimetype:`maintype/subtype`. If there was no lower case of the form :mimetype:`maintype/subtype`. If there was no
:mailheader:`Content-Type` header in the message the default type as given by :mailheader:`Content-Type` header in the message the default type as given
:meth:`get_default_type` will be returned. Since according to :rfc:`2045`, by :meth:`get_default_type` will be returned. Since according to
messages always have a default type, :meth:`get_content_type` will always return :rfc:`2045`, messages always have a default type, :meth:`get_content_type`
a value. will always return a value.
:rfc:`2045` defines a message's default type to be :mimetype:`text/plain` unless :rfc:`2045` defines a message's default type to be :mimetype:`text/plain`
it appears inside a :mimetype:`multipart/digest` container, in which case it unless it appears inside a :mimetype:`multipart/digest` container, in
would be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header which case it would be :mimetype:`message/rfc822`. If the
has an invalid type specification, :rfc:`2045` mandates that the default type be :mailheader:`Content-Type` header has an invalid type specification,
:mimetype:`text/plain`. :rfc:`2045` mandates that the default type be :mimetype:`text/plain`.
.. method:: Message.get_content_maintype() .. method:: get_content_maintype()
Return the message's main content type. This is the :mimetype:`maintype` part Return the message's main content type. This is the :mimetype:`maintype`
of the string returned by :meth:`get_content_type`. part of the string returned by :meth:`get_content_type`.
.. method:: Message.get_content_subtype() .. method:: get_content_subtype()
Return the message's sub-content type. This is the :mimetype:`subtype` part of Return the message's sub-content type. This is the :mimetype:`subtype`
the string returned by :meth:`get_content_type`. part of the string returned by :meth:`get_content_type`.
.. method:: Message.get_default_type() .. method:: get_default_type()
Return the default content type. Most messages have a default content type of Return the default content type. Most messages have a default content
:mimetype:`text/plain`, except for messages that are subparts of type of :mimetype:`text/plain`, except for messages that are subparts of
:mimetype:`multipart/digest` containers. Such subparts have a default content :mimetype:`multipart/digest` containers. Such subparts have a default
type of :mimetype:`message/rfc822`. content type of :mimetype:`message/rfc822`.
.. method:: Message.set_default_type(ctype) .. method:: set_default_type(ctype)
Set the default content type. *ctype* should either be :mimetype:`text/plain` Set the default content type. *ctype* should either be
or :mimetype:`message/rfc822`, although this is not enforced. The default :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not
content type is not stored in the :mailheader:`Content-Type` header. enforced. The default content type is not stored in the
:mailheader:`Content-Type` header.
.. method:: Message.get_params([failobj[, header[, unquote]]]) .. method:: get_params([failobj[, header[, unquote]]])
Return the message's :mailheader:`Content-Type` parameters, as a list. The Return the message's :mailheader:`Content-Type` parameters, as a list.
elements of the returned list are 2-tuples of key/value pairs, as split on the The elements of the returned list are 2-tuples of key/value pairs, as
``'='`` sign. The left hand side of the ``'='`` is the key, while the right split on the ``'='`` sign. The left hand side of the ``'='`` is the key,
hand side is the value. If there is no ``'='`` sign in the parameter the value while the right hand side is the value. If there is no ``'='`` sign in
is the empty string, otherwise the value is as described in :meth:`get_param` the parameter the value is the empty string, otherwise the value is as
and is unquoted if optional *unquote* is ``True`` (the default). described in :meth:`get_param` and is unquoted if optional *unquote* is
``True`` (the default).
Optional *failobj* is the object to return if there is no Optional *failobj* is the object to return if there is no
:mailheader:`Content-Type` header. Optional *header* is the header to search :mailheader:`Content-Type` header. Optional *header* is the header to
instead of :mailheader:`Content-Type`. search instead of :mailheader:`Content-Type`.
.. method:: Message.get_param(param[, failobj[, header[, unquote]]]) .. method:: get_param(param[, failobj[, header[, unquote]]])
Return the value of the :mailheader:`Content-Type` header's parameter *param* as Return the value of the :mailheader:`Content-Type` header's parameter
a string. If the message has no :mailheader:`Content-Type` header or if there *param* as a string. If the message has no :mailheader:`Content-Type`
is no such parameter, then *failobj* is returned (defaults to ``None``). header or if there is no such parameter, then *failobj* is returned
(defaults to ``None``).
Optional *header* if given, specifies the message header to use instead of Optional *header* if given, specifies the message header to use instead of
:mailheader:`Content-Type`. :mailheader:`Content-Type`.
Parameter keys are always compared case insensitively. The return value can Parameter keys are always compared case insensitively. The return value
either be a string, or a 3-tuple if the parameter was :rfc:`2231` encoded. When can either be a string, or a 3-tuple if the parameter was :rfc:`2231`
it's a 3-tuple, the elements of the value are of the form ``(CHARSET, LANGUAGE, encoded. When it's a 3-tuple, the elements of the value are of the form
VALUE)``. Note that both ``CHARSET`` and ``LANGUAGE`` can be ``None``, in which ``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and
case you should consider ``VALUE`` to be encoded in the ``us-ascii`` charset. ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE``
You can usually ignore ``LANGUAGE``. to be encoded in the ``us-ascii`` charset. You can usually ignore
``LANGUAGE``.
If your application doesn't care whether the parameter was encoded as in If your application doesn't care whether the parameter was encoded as in
:rfc:`2231`, you can collapse the parameter value by calling :rfc:`2231`, you can collapse the parameter value by calling
:func:`email.Utils.collapse_rfc2231_value`, passing in the return value from :func:`email.Utils.collapse_rfc2231_value`, passing in the return value
:meth:`get_param`. This will return a suitably decoded Unicode string whn the from :meth:`get_param`. This will return a suitably decoded Unicode
value is a tuple, or the original string unquoted if it isn't. For example:: string whn the value is a tuple, or the original string unquoted if it
isn't. For example::
rawparam = msg.get_param('foo') rawparam = msg.get_param('foo')
param = email.Utils.collapse_rfc2231_value(rawparam) param = email.Utils.collapse_rfc2231_value(rawparam)
In any case, the parameter value (either the returned string, or the ``VALUE`` In any case, the parameter value (either the returned string, or the
item in the 3-tuple) is always unquoted, unless *unquote* is set to ``False``. ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set
to ``False``.
.. method:: Message.set_param(param, value[, header[, requote[, charset[, language]]]]) .. method:: set_param(param, value[, header[, requote[, charset[, language]]]])
Set a parameter in the :mailheader:`Content-Type` header. If the parameter Set a parameter in the :mailheader:`Content-Type` header. If the
already exists in the header, its value will be replaced with *value*. If the parameter already exists in the header, its value will be replaced with
:mailheader:`Content-Type` header as not yet been defined for this message, it *value*. If the :mailheader:`Content-Type` header as not yet been defined
will be set to :mimetype:`text/plain` and the new parameter value will be for this message, it will be set to :mimetype:`text/plain` and the new
appended as per :rfc:`2045`. parameter value will be appended as per :rfc:`2045`.
Optional *header* specifies an alternative header to :mailheader:`Content-Type`, Optional *header* specifies an alternative header to
and all parameters will be quoted as necessary unless optional *requote* is :mailheader:`Content-Type`, and all parameters will be quoted as necessary
``False`` (the default is ``True``). unless optional *requote* is ``False`` (the default is ``True``).
If optional *charset* is specified, the parameter will be encoded according to If optional *charset* is specified, the parameter will be encoded
:rfc:`2231`. Optional *language* specifies the RFC 2231 language, defaulting to according to :rfc:`2231`. Optional *language* specifies the RFC 2231
the empty string. Both *charset* and *language* should be strings. language, defaulting to the empty string. Both *charset* and *language*
should be strings.
.. method:: Message.del_param(param[, header[, requote]]) .. method:: del_param(param[, header[, requote]])
Remove the given parameter completely from the :mailheader:`Content-Type` Remove the given parameter completely from the :mailheader:`Content-Type`
header. The header will be re-written in place without the parameter or its header. The header will be re-written in place without the parameter or
value. All values will be quoted as necessary unless *requote* is ``False`` its value. All values will be quoted as necessary unless *requote* is
(the default is ``True``). Optional *header* specifies an alternative to ``False`` (the default is ``True``). Optional *header* specifies an
:mailheader:`Content-Type`. alternative to :mailheader:`Content-Type`.
.. method:: Message.set_type(type[, header][, requote]) .. method:: set_type(type[, header][, requote])
Set the main type and subtype for the :mailheader:`Content-Type` header. *type* Set the main type and subtype for the :mailheader:`Content-Type`
must be a string in the form :mimetype:`maintype/subtype`, otherwise a header. *type* must be a string in the form :mimetype:`maintype/subtype`,
:exc:`ValueError` is raised. otherwise a :exc:`ValueError` is raised.
This method replaces the :mailheader:`Content-Type` header, keeping all the This method replaces the :mailheader:`Content-Type` header, keeping all
parameters in place. If *requote* is ``False``, this leaves the existing the parameters in place. If *requote* is ``False``, this leaves the
header's quoting as is, otherwise the parameters will be quoted (the default). existing header's quoting as is, otherwise the parameters will be quoted
(the default).
An alternative header can be specified in the *header* argument. When the An alternative header can be specified in the *header* argument. When the
:mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` header is :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
also added. header is also added.
.. method:: Message.get_filename([failobj]) .. method:: get_filename([failobj])
Return the value of the ``filename`` parameter of the Return the value of the ``filename`` parameter of the
:mailheader:`Content-Disposition` header of the message. If the header does not :mailheader:`Content-Disposition` header of the message. If the header
have a ``filename`` parameter, this method falls back to looking for the does not have a ``filename`` parameter, this method falls back to looking
``name`` parameter. If neither is found, or the header is missing, then for the ``name`` parameter. If neither is found, or the header is
*failobj* is returned. The returned string will always be unquoted as per missing, then *failobj* is returned. The returned string will always be
:meth:`Utils.unquote`. unquoted as per :meth:`Utils.unquote`.
.. method:: Message.get_boundary([failobj]) .. method:: get_boundary([failobj])
Return the value of the ``boundary`` parameter of the :mailheader:`Content-Type` Return the value of the ``boundary`` parameter of the
header of the message, or *failobj* if either the header is missing, or has no :mailheader:`Content-Type` header of the message, or *failobj* if either
``boundary`` parameter. The returned string will always be unquoted as per the header is missing, or has no ``boundary`` parameter. The returned
:meth:`Utils.unquote`. string will always be unquoted as per :meth:`Utils.unquote`.
.. method:: Message.set_boundary(boundary) .. method:: set_boundary(boundary)
Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to
*boundary*. :meth:`set_boundary` will always quote *boundary* if necessary. A *boundary*. :meth:`set_boundary` will always quote *boundary* if
:exc:`HeaderParseError` is raised if the message object has no necessary. A :exc:`HeaderParseError` is raised if the message object has
:mailheader:`Content-Type` header. no :mailheader:`Content-Type` header.
Note that using this method is subtly different than deleting the old Note that using this method is subtly different than deleting the old
:mailheader:`Content-Type` header and adding a new one with the new boundary via :mailheader:`Content-Type` header and adding a new one with the new
:meth:`add_header`, because :meth:`set_boundary` preserves the order of the boundary via :meth:`add_header`, because :meth:`set_boundary` preserves
:mailheader:`Content-Type` header in the list of headers. However, it does *not* the order of the :mailheader:`Content-Type` header in the list of
preserve any continuation lines which may have been present in the original headers. However, it does *not* preserve any continuation lines which may
:mailheader:`Content-Type` header. have been present in the original :mailheader:`Content-Type` header.
.. method:: Message.get_content_charset([failobj]) .. method:: get_content_charset([failobj])
Return the ``charset`` parameter of the :mailheader:`Content-Type` header, Return the ``charset`` parameter of the :mailheader:`Content-Type` header,
coerced to lower case. If there is no :mailheader:`Content-Type` header, or if coerced to lower case. If there is no :mailheader:`Content-Type` header, or if
...@@ -434,28 +448,29 @@ Here are some additional useful methods: ...@@ -434,28 +448,29 @@ Here are some additional useful methods:
:class:`Charset` instance for the default encoding of the message body. :class:`Charset` instance for the default encoding of the message body.
.. method:: Message.get_charsets([failobj]) .. method:: get_charsets([failobj])
Return a list containing the character set names in the message. If the message Return a list containing the character set names in the message. If the
is a :mimetype:`multipart`, then the list will contain one element for each message is a :mimetype:`multipart`, then the list will contain one element
subpart in the payload, otherwise, it will be a list of length 1. for each subpart in the payload, otherwise, it will be a list of length 1.
Each item in the list will be a string which is the value of the ``charset`` Each item in the list will be a string which is the value of the
parameter in the :mailheader:`Content-Type` header for the represented subpart. ``charset`` parameter in the :mailheader:`Content-Type` header for the
However, if the subpart has no :mailheader:`Content-Type` header, no ``charset`` represented subpart. However, if the subpart has no
parameter, or is not of the :mimetype:`text` main MIME type, then that item in :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of
the returned list will be *failobj*. the :mimetype:`text` main MIME type, then that item in the returned list
will be *failobj*.
.. method:: Message.walk() .. method:: walk()
The :meth:`walk` method is an all-purpose generator which can be used to iterate The :meth:`walk` method is an all-purpose generator which can be used to
over all the parts and subparts of a message object tree, in depth-first iterate over all the parts and subparts of a message object tree, in
traversal order. You will typically use :meth:`walk` as the iterator in a depth-first traversal order. You will typically use :meth:`walk` as the
``for`` loop; each iteration returns the next subpart. iterator in a ``for`` loop; each iteration returns the next subpart.
Here's an example that prints the MIME type of every part of a multipart message Here's an example that prints the MIME type of every part of a multipart
structure:: message structure::
>>> for part in msg.walk(): >>> for part in msg.walk():
... print(part.get_content_type()) ... print(part.get_content_type())
...@@ -466,42 +481,44 @@ Here are some additional useful methods: ...@@ -466,42 +481,44 @@ Here are some additional useful methods:
text/plain text/plain
message/rfc822 message/rfc822
:class:`Message` objects can also optionally contain two instance attributes, :class:`Message` objects can also optionally contain two instance attributes,
which can be used when generating the plain text of a MIME message. which can be used when generating the plain text of a MIME message.
.. data:: preamble .. attribute:: preamble
The format of a MIME document allows for some text between the blank line The format of a MIME document allows for some text between the blank line
following the headers, and the first multipart boundary string. Normally, this following the headers, and the first multipart boundary string. Normally,
text is never visible in a MIME-aware mail reader because it falls outside the this text is never visible in a MIME-aware mail reader because it falls
standard MIME armor. However, when viewing the raw text of the message, or when outside the standard MIME armor. However, when viewing the raw text of
viewing the message in a non-MIME aware reader, this text can become visible. the message, or when viewing the message in a non-MIME aware reader, this
text can become visible.
The *preamble* attribute contains this leading extra-armor text for MIME The *preamble* attribute contains this leading extra-armor text for MIME
documents. When the :class:`Parser` discovers some text after the headers but documents. When the :class:`Parser` discovers some text after the headers
before the first boundary string, it assigns this text to the message's but before the first boundary string, it assigns this text to the
*preamble* attribute. When the :class:`Generator` is writing out the plain text message's *preamble* attribute. When the :class:`Generator` is writing
representation of a MIME message, and it finds the message has a *preamble* out the plain text representation of a MIME message, and it finds the
attribute, it will write this text in the area between the headers and the first message has a *preamble* attribute, it will write this text in the area
boundary. See :mod:`email.parser` and :mod:`email.generator` for details. between the headers and the first boundary. See :mod:`email.parser` and
:mod:`email.generator` for details.
Note that if the message object has no preamble, the *preamble* attribute will Note that if the message object has no preamble, the *preamble* attribute
be ``None``. will be ``None``.
.. data:: epilogue .. attribute:: epilogue
The *epilogue* attribute acts the same way as the *preamble* attribute, except The *epilogue* attribute acts the same way as the *preamble* attribute,
that it contains text that appears between the last boundary and the end of the except that it contains text that appears between the last boundary and
message. the end of the message.
You do not need to set the epilogue to the empty string in order for the You do not need to set the epilogue to the empty string in order for the
:class:`Generator` to print a newline at the end of the file. :class:`Generator` to print a newline at the end of the file.
.. data:: defects .. attribute:: defects
The *defects* attribute contains a list of all the problems found when parsing The *defects* attribute contains a list of all the problems found when
this message. See :mod:`email.errors` for a detailed description of the parsing this message. See :mod:`email.errors` for a detailed description
possible parsing defects. of the possible parsing defects.
...@@ -65,20 +65,21 @@ Here is the API for the :class:`FeedParser`: ...@@ -65,20 +65,21 @@ Here is the API for the :class:`FeedParser`:
defaults to the :class:`email.message.Message` class. defaults to the :class:`email.message.Message` class.
.. method:: FeedParser.feed(data) .. method:: feed(data)
Feed the :class:`FeedParser` some more data. *data* should be a string Feed the :class:`FeedParser` some more data. *data* should be a string
containing one or more lines. The lines can be partial and the containing one or more lines. The lines can be partial and the
:class:`FeedParser` will stitch such partial lines together properly. The lines :class:`FeedParser` will stitch such partial lines together properly. The
in the string can have any of the common three line endings, carriage return, lines in the string can have any of the common three line endings,
newline, or carriage return and newline (they can even be mixed). carriage return, newline, or carriage return and newline (they can even be
mixed).
.. method:: FeedParser.close() .. method:: close()
Closing a :class:`FeedParser` completes the parsing of all previously fed data, Closing a :class:`FeedParser` completes the parsing of all previously fed
and returns the root message object. It is undefined what happens if you feed data, and returns the root message object. It is undefined what happens
more data to a closed :class:`FeedParser`. if you feed more data to a closed :class:`FeedParser`.
Parser class API Parser class API
...@@ -111,33 +112,33 @@ class. ...@@ -111,33 +112,33 @@ class.
effectively non-strict. You should simply stop passing a *strict* flag to effectively non-strict. You should simply stop passing a *strict* flag to
the :class:`Parser` constructor. the :class:`Parser` constructor.
The other public :class:`Parser` methods are: The other public :class:`Parser` methods are:
.. method:: Parser.parse(fp[, headersonly]) .. method:: parse(fp[, headersonly])
Read all the data from the file-like object *fp*, parse the resulting text, and Read all the data from the file-like object *fp*, parse the resulting
return the root message object. *fp* must support both the :meth:`readline` and text, and return the root message object. *fp* must support both the
the :meth:`read` methods on file-like objects. :meth:`readline` and the :meth:`read` methods on file-like objects.
The text contained in *fp* must be formatted as a block of :rfc:`2822` style The text contained in *fp* must be formatted as a block of :rfc:`2822`
headers and header continuation lines, optionally preceded by a envelope style headers and header continuation lines, optionally preceded by a
header. The header block is terminated either by the end of the data or by a envelope header. The header block is terminated either by the end of the
blank line. Following the header block is the body of the message (which may data or by a blank line. Following the header block is the body of the
contain MIME-encoded subparts). message (which may contain MIME-encoded subparts).
Optional *headersonly* is as with the :meth:`parse` method. Optional *headersonly* is as with the :meth:`parse` method.
.. method:: parsestr(text[, headersonly])
.. method:: Parser.parsestr(text[, headersonly]) Similar to the :meth:`parse` method, except it takes a string object
instead of a file-like object. Calling this method on a string is exactly
Similar to the :meth:`parse` method, except it takes a string object instead of equivalent to wrapping *text* in a :class:`StringIO` instance first and
a file-like object. Calling this method on a string is exactly equivalent to calling :meth:`parse`.
wrapping *text* in a :class:`StringIO` instance first and calling :meth:`parse`.
Optional *headersonly* is a flag specifying whether to stop parsing after Optional *headersonly* is a flag specifying whether to stop parsing after
reading the headers or not. The default is ``False``, meaning it parses the reading the headers or not. The default is ``False``, meaning it parses
entire contents of the file. the entire contents of the file.
Since creating a message object structure from a string or a file object is such Since creating a message object structure from a string or a file object is such
......
...@@ -66,88 +66,91 @@ The :class:`dircmp` class ...@@ -66,88 +66,91 @@ The :class:`dircmp` class
'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir, 'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir,
os.pardir]``. os.pardir]``.
The :class:`dircmp` class provides the following methods: The :class:`dircmp` class provides the following methods:
.. method:: dircmp.report() .. method:: report()
Print (to ``sys.stdout``) a comparison between *a* and *b*. Print (to ``sys.stdout``) a comparison between *a* and *b*.
.. method:: dircmp.report_partial_closure() .. method:: report_partial_closure()
Print a comparison between *a* and *b* and common immediate subdirectories. Print a comparison between *a* and *b* and common immediate
subdirectories.
.. method:: dircmp.report_full_closure() .. method:: report_full_closure()
Print a comparison between *a* and *b* and common subdirectories (recursively). Print a comparison between *a* and *b* and common subdirectories
(recursively).
The :class:`dircmp` offers a number of interesting attributes that may be used The :class:`dircmp` offers a number of interesting attributes that may be
to get various bits of information about the directory trees being compared. used to get various bits of information about the directory trees being
compared.
Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, so Note that via :meth:`__getattr__` hooks, all attributes are computed lazily,
there is no speed penalty if only those attributes which are lightweight to so there is no speed penalty if only those attributes which are lightweight
compute are used. to compute are used.
.. attribute:: dircmp.left_list .. attribute:: left_list
Files and subdirectories in *a*, filtered by *hide* and *ignore*. Files and subdirectories in *a*, filtered by *hide* and *ignore*.
.. attribute:: dircmp.right_list .. attribute:: right_list
Files and subdirectories in *b*, filtered by *hide* and *ignore*. Files and subdirectories in *b*, filtered by *hide* and *ignore*.
.. attribute:: dircmp.common .. attribute:: common
Files and subdirectories in both *a* and *b*. Files and subdirectories in both *a* and *b*.
.. attribute:: dircmp.left_only .. attribute:: left_only
Files and subdirectories only in *a*. Files and subdirectories only in *a*.
.. attribute:: dircmp.right_only .. attribute:: right_only
Files and subdirectories only in *b*. Files and subdirectories only in *b*.
.. attribute:: dircmp.common_dirs .. attribute:: common_dirs
Subdirectories in both *a* and *b*. Subdirectories in both *a* and *b*.
.. attribute:: dircmp.common_files .. attribute:: common_files
Files in both *a* and *b* Files in both *a* and *b*
.. attribute:: dircmp.common_funny .. attribute:: common_funny
Names in both *a* and *b*, such that the type differs between the directories, Names in both *a* and *b*, such that the type differs between the
or names for which :func:`os.stat` reports an error. directories, or names for which :func:`os.stat` reports an error.
.. attribute:: dircmp.same_files .. attribute:: same_files
Files which are identical in both *a* and *b*. Files which are identical in both *a* and *b*.
.. attribute:: dircmp.diff_files .. attribute:: diff_files
Files which are in both *a* and *b*, whose contents differ. Files which are in both *a* and *b*, whose contents differ.
.. attribute:: dircmp.funny_files .. attribute:: funny_files
Files which are in both *a* and *b*, but could not be compared. Files which are in both *a* and *b*, but could not be compared.
.. attribute:: dircmp.subdirs .. attribute:: subdirs
A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects.
...@@ -30,26 +30,24 @@ Rational number class. ...@@ -30,26 +30,24 @@ Rational number class.
:class:`numbers.Rational` and is immutable and hashable. :class:`numbers.Rational` and is immutable and hashable.
.. method:: Fraction.from_float(flt) .. method:: from_float(flt)
This classmethod constructs a :class:`Fraction` representing the This classmethod constructs a :class:`Fraction` representing the exact
exact value of *flt*, which must be a :class:`float`. Beware that value of *flt*, which must be a :class:`float`. Beware that
``Fraction.from_float(0.3)`` is not the same value as ``Rational(3, ``Fraction.from_float(0.3)`` is not the same value as ``Rational(3, 10)``
10)``
.. method:: Fraction.from_decimal(dec) .. method:: from_decimal(dec)
This classmethod constructs a :class:`Fraction` representing the This classmethod constructs a :class:`Fraction` representing the exact
exact value of *dec*, which must be a value of *dec*, which must be a :class:`decimal.Decimal`.
:class:`decimal.Decimal`.
.. method:: Fraction.limit_denominator(max_denominator=1000000) .. method:: limit_denominator(max_denominator=1000000)
Finds and returns the closest :class:`Fraction` to ``self`` that Finds and returns the closest :class:`Fraction` to ``self`` that has
has denominator at most max_denominator. This method is useful for denominator at most max_denominator. This method is useful for finding
finding rational approximations to a given floating-point number: rational approximations to a given floating-point number:
>>> from fractions import Fraction >>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000) >>> Fraction('3.1415926535897932').limit_denominator(1000)
...@@ -64,26 +62,26 @@ Rational number class. ...@@ -64,26 +62,26 @@ Rational number class.
Fraction(1L, 2L) Fraction(1L, 2L)
.. method:: Fraction.__floor__() .. method:: __floor__()
Returns the greatest :class:`int` ``<= self``. Will be accessible Returns the greatest :class:`int` ``<= self``. Will be accessible through
through :func:`math.floor` in Py3k. :func:`math.floor` in Py3k.
.. method:: Fraction.__ceil__() .. method:: __ceil__()
Returns the least :class:`int` ``>= self``. Will be accessible Returns the least :class:`int` ``>= self``. Will be accessible through
through :func:`math.ceil` in Py3k. :func:`math.ceil` in Py3k.
.. method:: Fraction.__round__() .. method:: __round__()
Fraction.__round__(ndigits) __round__(ndigits)
The first version returns the nearest :class:`int` to ``self``, The first version returns the nearest :class:`int` to ``self``, rounding
rounding half to even. The second version rounds ``self`` to the half to even. The second version rounds ``self`` to the nearest multiple
nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if of ``Fraction(1, 10**ndigits)`` (logically, if ``ndigits`` is negative),
``ndigits`` is negative), again rounding half toward even. Will be again rounding half toward even. Will be accessible through :func:`round`
accessible through :func:`round` in Py3k. in Py3k.
.. seealso:: .. seealso::
......
...@@ -47,33 +47,34 @@ The module defines the following items: ...@@ -47,33 +47,34 @@ The module defines the following items:
or passed as None, the global default timeout setting will be used). or passed as None, the global default timeout setting will be used).
.. data:: all_errors .. attribute:: all_errors
The set of all exceptions (as a tuple) that methods of :class:`FTP` instances The set of all exceptions (as a tuple) that methods of :class:`FTP`
may raise as a result of problems with the FTP connection (as opposed to instances may raise as a result of problems with the FTP connection (as
programming errors made by the caller). This set includes the four exceptions opposed to programming errors made by the caller). This set includes the
listed below as well as :exc:`socket.error` and :exc:`IOError`. four exceptions listed below as well as :exc:`socket.error` and
:exc:`IOError`.
.. exception:: error_reply .. exception:: error_reply
Exception raised when an unexpected reply is received from the server. Exception raised when an unexpected reply is received from the server.
.. exception:: error_temp .. exception:: error_temp
Exception raised when an error code in the range 400--499 is received. Exception raised when an error code in the range 400--499 is received.
.. exception:: error_perm .. exception:: error_perm
Exception raised when an error code in the range 500--599 is received. Exception raised when an error code in the range 500--599 is received.
.. exception:: error_proto .. exception:: error_proto
Exception raised when a reply is received from the server that does not begin Exception raised when a reply is received from the server that does not
with a digit in the range 1--5. begin with a digit in the range 1--5.
.. seealso:: .. seealso::
......
...@@ -218,7 +218,7 @@ interface you can use to write your own specialized translation classes. Here ...@@ -218,7 +218,7 @@ interface you can use to write your own specialized translation classes. Here
are the methods of :class:`NullTranslations`: are the methods of :class:`NullTranslations`:
.. method:: NullTranslations.__init__([fp]) .. class:: NullTranslations([fp])
Takes an optional file object *fp*, which is ignored by the base class. Takes an optional file object *fp*, which is ignored by the base class.
Initializes "protected" instance variables *_info* and *_charset* which are set Initializes "protected" instance variables *_info* and *_charset* which are set
...@@ -227,105 +227,107 @@ are the methods of :class:`NullTranslations`: ...@@ -227,105 +227,107 @@ are the methods of :class:`NullTranslations`:
``None``. ``None``.
.. method:: NullTranslations._parse(fp) .. method:: _parse(fp)
No-op'd in the base class, this method takes file object *fp*, and reads the No-op'd in the base class, this method takes file object *fp*, and reads
data from the file, initializing its message catalog. If you have an the data from the file, initializing its message catalog. If you have an
unsupported message catalog file format, you should override this method to unsupported message catalog file format, you should override this method
parse your format. to parse your format.
.. method:: NullTranslations.add_fallback(fallback) .. method:: add_fallback(fallback)
Add *fallback* as the fallback object for the current translation object. A Add *fallback* as the fallback object for the current translation
translation object should consult the fallback if it cannot provide a object. A translation object should consult the fallback if it cannot provide a
translation for a given message. translation for a given message.
.. method:: NullTranslations.gettext(message) .. method:: gettext(message)
If a fallback has been set, forward :meth:`gettext` to the fallback. Otherwise, If a fallback has been set, forward :meth:`gettext` to the
return the translated message. Overridden in derived classes. fallback. Otherwise, return the translated message. Overridden in derived
classes.
.. method:: NullTranslations.lgettext(message) .. method:: lgettext(message)
If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise, If a fallback has been set, forward :meth:`lgettext` to the
return the translated message. Overridden in derived classes. fallback. Otherwise, return the translated message. Overridden in derived
classes.
.. method:: ugettext(message)
.. method:: NullTranslations.ugettext(message) If a fallback has been set, forward :meth:`ugettext` to the
fallback. Otherwise, return the translated message as a string. Overridden
in derived classes.
If a fallback has been set, forward :meth:`ugettext` to the fallback. Otherwise,
return the translated message as a string. Overridden in derived classes.
.. method:: ngettext(singular, plural, n)
.. method:: NullTranslations.ngettext(singular, plural, n) If a fallback has been set, forward :meth:`ngettext` to the
fallback. Otherwise, return the translated message. Overridden in derived
classes.
If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, .. method:: lngettext(singular, plural, n)
return the translated message. Overridden in derived classes.
If a fallback has been set, forward :meth:`ngettext` to the
fallback. Otherwise, return the translated message. Overridden in derived
classes.
.. method:: NullTranslations.lngettext(singular, plural, n) .. method:: ungettext(singular, plural, n)
If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise,
return the translated message. Overridden in derived classes.
.. method:: NullTranslations.ungettext(singular, plural, n)
If a fallback has been set, forward :meth:`ungettext` to the fallback. If a fallback has been set, forward :meth:`ungettext` to the fallback.
Otherwise, return the translated message as a string. Overridden in Otherwise, return the translated message as a string. Overridden in
derived classes. derived classes.
.. method:: info()
.. method:: NullTranslations.info()
Return the "protected" :attr:`_info` variable. Return the "protected" :attr:`_info` variable.
.. method:: NullTranslations.charset() .. method:: charset()
Return the "protected" :attr:`_charset` variable. Return the "protected" :attr:`_charset` variable.
.. method:: NullTranslations.output_charset() .. method:: output_charset()
Return the "protected" :attr:`_output_charset` variable, which defines the Return the "protected" :attr:`_output_charset` variable, which defines the
encoding used to return translated messages. encoding used to return translated messages.
.. method:: NullTranslations.set_output_charset(charset) .. method:: set_output_charset(charset)
Change the "protected" :attr:`_output_charset` variable, which defines the Change the "protected" :attr:`_output_charset` variable, which defines the
encoding used to return translated messages. encoding used to return translated messages.
.. method:: NullTranslations.install([unicode [, names]]) .. method:: install([unicode [, names]])
If the *unicode* flag is false, this method installs :meth:`self.gettext` into If the *unicode* flag is false, this method installs :meth:`self.gettext`
the built-in namespace, binding it to ``_``. If *unicode* is true, it binds into the built-in namespace, binding it to ``_``. If *unicode* is true,
:meth:`self.ugettext` instead. By default, *unicode* is false. it binds :meth:`self.ugettext` instead. By default, *unicode* is false.
If the *names* parameter is given, it must be a sequence containing the names of If the *names* parameter is given, it must be a sequence containing the
functions you want to install in the builtin namespace in addition to :func:`_`. names of functions you want to install in the builtin namespace in
Supported names are ``'gettext'`` (bound to :meth:`self.gettext` or addition to :func:`_`. Supported names are ``'gettext'`` (bound to
:meth:`self.ugettext` according to the *unicode* flag), ``'ngettext'`` (bound to :meth:`self.gettext` or :meth:`self.ugettext` according to the *unicode*
:meth:`self.ngettext` or :meth:`self.ungettext` according to the *unicode* flag), ``'ngettext'`` (bound to :meth:`self.ngettext` or
flag), ``'lgettext'`` and ``'lngettext'``. :meth:`self.ungettext` according to the *unicode* flag), ``'lgettext'``
and ``'lngettext'``.
Note that this is only one way, albeit the most convenient way, to make the Note that this is only one way, albeit the most convenient way, to make
:func:`_` function available to your application. Because it affects the entire the :func:`_` function available to your application. Because it affects
application globally, and specifically the built-in namespace, localized modules the entire application globally, and specifically the built-in namespace,
should never install :func:`_`. Instead, they should use this code to make localized modules should never install :func:`_`. Instead, they should use
:func:`_` available to their module:: this code to make :func:`_` available to their module::
import gettext import gettext
t = gettext.translation('mymodule', ...) t = gettext.translation('mymodule', ...)
_ = t.gettext _ = t.gettext
This puts :func:`_` only in the module's global namespace and so only affects This puts :func:`_` only in the module's global namespace and so only
calls within this module. affects calls within this module.
The :class:`GNUTranslations` class The :class:`GNUTranslations` class
......
...@@ -1491,19 +1491,19 @@ and :meth:`flush` methods). ...@@ -1491,19 +1491,19 @@ and :meth:`flush` methods).
will be used. will be used.
.. method:: StreamHandler.emit(record) .. method:: emit(record)
If a formatter is specified, it is used to format the record. The record is then If a formatter is specified, it is used to format the record. The record
written to the stream with a trailing newline. If exception information is is then written to the stream with a trailing newline. If exception
present, it is formatted using :func:`traceback.print_exception` and appended to information is present, it is formatted using
the stream. :func:`traceback.print_exception` and appended to the stream.
.. method:: StreamHandler.flush() .. method:: flush()
Flushes the stream by calling its :meth:`flush` method. Note that the Flushes the stream by calling its :meth:`flush` method. Note that the
:meth:`close` method is inherited from :class:`Handler` and so does nothing, so :meth:`close` method is inherited from :class:`Handler` and so does
an explicit :meth:`flush` call may be needed at times. nothing, so an explicit :meth:`flush` call may be needed at times.
FileHandler FileHandler
...@@ -1523,12 +1523,12 @@ sends logging output to a disk file. It inherits the output functionality from ...@@ -1523,12 +1523,12 @@ sends logging output to a disk file. It inherits the output functionality from
first call to :meth:`emit`. By default, the file grows indefinitely. first call to :meth:`emit`. By default, the file grows indefinitely.
.. method:: FileHandler.close() .. method:: close()
Closes the file. Closes the file.
.. method:: FileHandler.emit(record) .. method:: emit(record)
Outputs the record to the file. Outputs the record to the file.
...@@ -1563,11 +1563,11 @@ this value. ...@@ -1563,11 +1563,11 @@ this value.
first call to :meth:`emit`. By default, the file grows indefinitely. first call to :meth:`emit`. By default, the file grows indefinitely.
.. method:: WatchedFileHandler.emit(record) .. method:: emit(record)
Outputs the record to the file, but first checks to see if the file has changed. Outputs the record to the file, but first checks to see if the file has
If it has, the existing stream is flushed and closed and the file opened again, changed. If it has, the existing stream is flushed and closed and the
before outputting the record to the file. file opened again, before outputting the record to the file.
RotatingFileHandler RotatingFileHandler
...@@ -1599,14 +1599,15 @@ module, supports rotation of disk log files. ...@@ -1599,14 +1599,15 @@ module, supports rotation of disk log files.
:file:`app.log.2`, :file:`app.log.3` etc. respectively. :file:`app.log.2`, :file:`app.log.3` etc. respectively.
.. method:: RotatingFileHandler.doRollover() .. method:: doRollover()
Does a rollover, as described above. Does a rollover, as described above.
.. method:: RotatingFileHandler.emit(record) .. method:: emit(record)
Outputs the record to the file, catering for rollover as described previously. Outputs the record to the file, catering for rollover as described
previously.
TimedRotatingFileHandler TimedRotatingFileHandler
...@@ -1652,12 +1653,12 @@ timed intervals. ...@@ -1652,12 +1653,12 @@ timed intervals.
files to delete, so changing the interval may leave old files lying around. files to delete, so changing the interval may leave old files lying around.
.. method:: TimedRotatingFileHandler.doRollover() .. method:: doRollover()
Does a rollover, as described above. Does a rollover, as described above.
.. method:: TimedRotatingFileHandler.emit(record) .. method:: emit(record)
Outputs the record to the file, catering for rollover as described above. Outputs the record to the file, catering for rollover as described above.
...@@ -1675,43 +1676,44 @@ sends logging output to a network socket. The base class uses a TCP socket. ...@@ -1675,43 +1676,44 @@ sends logging output to a network socket. The base class uses a TCP socket.
communicate with a remote machine whose address is given by *host* and *port*. communicate with a remote machine whose address is given by *host* and *port*.
.. method:: SocketHandler.close() .. method:: close()
Closes the socket. Closes the socket.
.. method:: SocketHandler.emit() .. method:: emit()
Pickles the record's attribute dictionary and writes it to the socket in binary Pickles the record's attribute dictionary and writes it to the socket in
format. If there is an error with the socket, silently drops the packet. If the binary format. If there is an error with the socket, silently drops the
connection was previously lost, re-establishes the connection. To unpickle the packet. If the connection was previously lost, re-establishes the
record at the receiving end into a :class:`LogRecord`, use the connection. To unpickle the record at the receiving end into a
:func:`makeLogRecord` function. :class:`LogRecord`, use the :func:`makeLogRecord` function.
.. method:: SocketHandler.handleError() .. method:: handleError()
Handles an error which has occurred during :meth:`emit`. The most likely cause Handles an error which has occurred during :meth:`emit`. The most likely
is a lost connection. Closes the socket so that we can retry on the next event. cause is a lost connection. Closes the socket so that we can retry on the
next event.
.. method:: SocketHandler.makeSocket() .. method:: makeSocket()
This is a factory method which allows subclasses to define the precise type of This is a factory method which allows subclasses to define the precise
socket they want. The default implementation creates a TCP socket type of socket they want. The default implementation creates a TCP socket
(:const:`socket.SOCK_STREAM`). (:const:`socket.SOCK_STREAM`).
.. method:: SocketHandler.makePickle(record) .. method:: makePickle(record)
Pickles the record's attribute dictionary in binary format with a length prefix, Pickles the record's attribute dictionary in binary format with a length
and returns it ready for transmission across the socket. prefix, and returns it ready for transmission across the socket.
.. method:: SocketHandler.send(packet) .. method:: send(packet)
Send a pickled string *packet* to the socket. This function allows for partial Send a pickled string *packet* to the socket. This function allows for
sends which can happen when the network is busy. partial sends which can happen when the network is busy.
DatagramHandler DatagramHandler
...@@ -1728,21 +1730,21 @@ over UDP sockets. ...@@ -1728,21 +1730,21 @@ over UDP sockets.
communicate with a remote machine whose address is given by *host* and *port*. communicate with a remote machine whose address is given by *host* and *port*.
.. method:: DatagramHandler.emit() .. method:: emit()
Pickles the record's attribute dictionary and writes it to the socket in binary Pickles the record's attribute dictionary and writes it to the socket in
format. If there is an error with the socket, silently drops the packet. To binary format. If there is an error with the socket, silently drops the
unpickle the record at the receiving end into a :class:`LogRecord`, use the packet. To unpickle the record at the receiving end into a
:func:`makeLogRecord` function. :class:`LogRecord`, use the :func:`makeLogRecord` function.
.. method:: DatagramHandler.makeSocket() .. method:: makeSocket()
The factory method of :class:`SocketHandler` is here overridden to create a UDP The factory method of :class:`SocketHandler` is here overridden to create
socket (:const:`socket.SOCK_DGRAM`). a UDP socket (:const:`socket.SOCK_DGRAM`).
.. method:: DatagramHandler.send(s) .. method:: send(s)
Send a pickled string to a socket. Send a pickled string to a socket.
...@@ -1766,22 +1768,22 @@ supports sending logging messages to a remote or local Unix syslog. ...@@ -1766,22 +1768,22 @@ supports sending logging messages to a remote or local Unix syslog.
:const:`LOG_USER` is used. :const:`LOG_USER` is used.
.. method:: SysLogHandler.close() .. method:: close()
Closes the socket to the remote host. Closes the socket to the remote host.
.. method:: SysLogHandler.emit(record) .. method:: emit(record)
The record is formatted, and then sent to the syslog server. If exception The record is formatted, and then sent to the syslog server. If exception
information is present, it is *not* sent to the server. information is present, it is *not* sent to the server.
.. method:: SysLogHandler.encodePriority(facility, priority) .. method:: encodePriority(facility, priority)
Encodes the facility and priority into an integer. You can pass in strings or Encodes the facility and priority into an integer. You can pass in strings
integers - if strings are passed, internal mapping dictionaries are used to or integers - if strings are passed, internal mapping dictionaries are
convert them to integers. used to convert them to integers.
NTEventLogHandler NTEventLogHandler
...@@ -1809,45 +1811,45 @@ extensions for Python installed. ...@@ -1809,45 +1811,45 @@ extensions for Python installed.
defaults to ``'Application'``. defaults to ``'Application'``.
.. method:: NTEventLogHandler.close() .. method:: close()
At this point, you can remove the application name from the registry as a source At this point, you can remove the application name from the registry as a
of event log entries. However, if you do this, you will not be able to see the source of event log entries. However, if you do this, you will not be able
events as you intended in the Event Log Viewer - it needs to be able to access to see the events as you intended in the Event Log Viewer - it needs to be
the registry to get the .dll name. The current version does not do this (in fact able to access the registry to get the .dll name. The current version does
it doesn't do anything). not do this (in fact it doesn't do anything).
.. method:: NTEventLogHandler.emit(record) .. method:: emit(record)
Determines the message ID, event category and event type, and then logs the Determines the message ID, event category and event type, and then logs
message in the NT event log. the message in the NT event log.
.. method:: NTEventLogHandler.getEventCategory(record) .. method:: getEventCategory(record)
Returns the event category for the record. Override this if you want to specify Returns the event category for the record. Override this if you want to
your own categories. This version returns 0. specify your own categories. This version returns 0.
.. method:: NTEventLogHandler.getEventType(record) .. method:: getEventType(record)
Returns the event type for the record. Override this if you want to specify your Returns the event type for the record. Override this if you want to
own types. This version does a mapping using the handler's typemap attribute, specify your own types. This version does a mapping using the handler's
which is set up in :meth:`__init__` to a dictionary which contains mappings for typemap attribute, which is set up in :meth:`__init__` to a dictionary
:const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and which contains mappings for :const:`DEBUG`, :const:`INFO`,
:const:`CRITICAL`. If you are using your own levels, you will either need to :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
override this method or place a suitable dictionary in the handler's *typemap* your own levels, you will either need to override this method or place a
attribute. suitable dictionary in the handler's *typemap* attribute.
.. method:: NTEventLogHandler.getMessageID(record) .. method:: getMessageID(record)
Returns the message ID for the record. If you are using your own messages, you Returns the message ID for the record. If you are using your own messages,
could do this by having the *msg* passed to the logger being an ID rather than a you could do this by having the *msg* passed to the logger being an ID
format string. Then, in here, you could use a dictionary lookup to get the rather than a format string. Then, in here, you could use a dictionary
message ID. This version returns 1, which is the base message ID in lookup to get the message ID. This version returns 1, which is the base
:file:`win32service.pyd`. message ID in :file:`win32service.pyd`.
SMTPHandler SMTPHandler
...@@ -1867,15 +1869,15 @@ supports sending logging messages to an email address via SMTP. ...@@ -1867,15 +1869,15 @@ supports sending logging messages to an email address via SMTP.
can specify a (username, password) tuple for the *credentials* argument. can specify a (username, password) tuple for the *credentials* argument.
.. method:: SMTPHandler.emit(record) .. method:: emit(record)
Formats the record and sends it to the specified addressees. Formats the record and sends it to the specified addressees.
.. method:: SMTPHandler.getSubject(record) .. method:: getSubject(record)
If you want to specify a subject line which is record-dependent, override this If you want to specify a subject line which is record-dependent, override
method. this method.
MemoryHandler MemoryHandler
...@@ -1898,22 +1900,22 @@ should, then :meth:`flush` is expected to do the needful. ...@@ -1898,22 +1900,22 @@ should, then :meth:`flush` is expected to do the needful.
Initializes the handler with a buffer of the specified capacity. Initializes the handler with a buffer of the specified capacity.
.. method:: BufferingHandler.emit(record) .. method:: emit(record)
Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls Appends the record to the buffer. If :meth:`shouldFlush` returns true,
:meth:`flush` to process the buffer. calls :meth:`flush` to process the buffer.
.. method:: BufferingHandler.flush() .. method:: flush()
You can override this to implement custom flushing behavior. This version just You can override this to implement custom flushing behavior. This version
zaps the buffer to empty. just zaps the buffer to empty.
.. method:: BufferingHandler.shouldFlush(record) .. method:: shouldFlush(record)
Returns true if the buffer is up to capacity. This method can be overridden to Returns true if the buffer is up to capacity. This method can be
implement custom flushing strategies. overridden to implement custom flushing strategies.
.. class:: MemoryHandler(capacity[, flushLevel [, target]]) .. class:: MemoryHandler(capacity[, flushLevel [, target]])
...@@ -1924,23 +1926,25 @@ should, then :meth:`flush` is expected to do the needful. ...@@ -1924,23 +1926,25 @@ should, then :meth:`flush` is expected to do the needful.
set using :meth:`setTarget` before this handler does anything useful. set using :meth:`setTarget` before this handler does anything useful.
.. method:: MemoryHandler.close() .. method:: close()
Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer. Calls :meth:`flush`, sets the target to :const:`None` and clears the
buffer.
.. method:: MemoryHandler.flush() .. method:: flush()
For a :class:`MemoryHandler`, flushing means just sending the buffered records For a :class:`MemoryHandler`, flushing means just sending the buffered
to the target, if there is one. Override if you want different behavior. records to the target, if there is one. Override if you want different
behavior.
.. method:: MemoryHandler.setTarget(target) .. method:: setTarget(target)
Sets the target handler for this handler. Sets the target handler for this handler.
.. method:: MemoryHandler.shouldFlush(record) .. method:: shouldFlush(record)
Checks for buffer full or a record at the *flushLevel* or higher. Checks for buffer full or a record at the *flushLevel* or higher.
...@@ -1961,7 +1965,7 @@ supports sending logging messages to a Web server, using either ``GET`` or ...@@ -1961,7 +1965,7 @@ supports sending logging messages to a Web server, using either ``GET`` or
*method* is specified, ``GET`` is used. *method* is specified, ``GET`` is used.
.. method:: HTTPHandler.emit(record) .. method:: emit(record)
Sends the record to the Web server as an URL-encoded dictionary. Sends the record to the Web server as an URL-encoded dictionary.
...@@ -2048,38 +2052,42 @@ Currently, the useful mapping keys in a :class:`LogRecord` are: ...@@ -2048,38 +2052,42 @@ Currently, the useful mapping keys in a :class:`LogRecord` are:
is used. is used.
.. method:: Formatter.format(record) .. method:: format(record)
The record's attribute dictionary is used as the operand to a string formatting The record's attribute dictionary is used as the operand to a string
operation. Returns the resulting string. Before formatting the dictionary, a formatting operation. Returns the resulting string. Before formatting the
couple of preparatory steps are carried out. The *message* attribute of the dictionary, a couple of preparatory steps are carried out. The *message*
record is computed using *msg* % *args*. If the formatting string contains attribute of the record is computed using *msg* % *args*. If the
``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
is exception information, it is formatted using :meth:`formatException` and to format the event time. If there is exception information, it is
appended to the message. Note that the formatted exception information is cached formatted using :meth:`formatException` and appended to the message. Note
in attribute *exc_text*. This is useful because the exception information can that the formatted exception information is cached in attribute
be pickled and sent across the wire, but you should be careful if you have more *exc_text*. This is useful because the exception information can be
than one :class:`Formatter` subclass which customizes the formatting of exception pickled and sent across the wire, but you should be careful if you have
information. In this case, you will have to clear the cached value after a more than one :class:`Formatter` subclass which customizes the formatting
formatter has done its formatting, so that the next formatter to handle the event of exception information. In this case, you will have to clear the cached
doesn't use the cached value but recalculates it afresh. value after a formatter has done its formatting, so that the next
formatter to handle the event doesn't use the cached value but
recalculates it afresh.
.. method:: Formatter.formatTime(record[, datefmt]) .. method:: formatTime(record[, datefmt])
This method should be called from :meth:`format` by a formatter which wants to This method should be called from :meth:`format` by a formatter which
make use of a formatted time. This method can be overridden in formatters to wants to make use of a formatted time. This method can be overridden in
provide for any specific requirement, but the basic behavior is as follows: if formatters to provide for any specific requirement, but the basic behavior
*datefmt* (a string) is specified, it is used with :func:`time.strftime` to is as follows: if *datefmt* (a string) is specified, it is used with
format the creation time of the record. Otherwise, the ISO8601 format is used. :func:`time.strftime` to format the creation time of the
The resulting string is returned. record. Otherwise, the ISO8601 format is used. The resulting string is
returned.
.. method:: Formatter.formatException(exc_info) .. method:: formatException(exc_info)
Formats the specified exception information (a standard exception tuple as Formats the specified exception information (a standard exception tuple as
returned by :func:`sys.exc_info`) as a string. This default implementation just returned by :func:`sys.exc_info`) as a string. This default implementation
uses :func:`traceback.print_exception`. The resulting string is returned. just uses :func:`traceback.print_exception`. The resulting string is
returned.
Filter Objects Filter Objects
...@@ -2100,10 +2108,11 @@ initialized with the empty string, all events are passed. ...@@ -2100,10 +2108,11 @@ initialized with the empty string, all events are passed.
through the filter. If no name is specified, allows every event. through the filter. If no name is specified, allows every event.
.. method:: Filter.filter(record) .. method:: filter(record)
Is the specified record to be logged? Returns zero for no, nonzero for yes. If Is the specified record to be logged? Returns zero for no, nonzero for
deemed appropriate, the record may be modified in-place by this method. yes. If deemed appropriate, the record may be modified in-place by this
method.
LogRecord Objects LogRecord Objects
...@@ -2131,11 +2140,12 @@ made, and any exception information to be logged. ...@@ -2131,11 +2140,12 @@ made, and any exception information to be logged.
specified, it defaults to ``None``. specified, it defaults to ``None``.
.. method:: LogRecord.getMessage() .. method:: getMessage()
Returns the message for this :class:`LogRecord` instance after merging any Returns the message for this :class:`LogRecord` instance after merging any
user-supplied arguments with the message. user-supplied arguments with the message.
LoggerAdapter Objects LoggerAdapter Objects
--------------------- ---------------------
...@@ -2150,12 +2160,12 @@ __ context-info_ ...@@ -2150,12 +2160,12 @@ __ context-info_
Returns an instance of :class:`LoggerAdapter` initialized with an Returns an instance of :class:`LoggerAdapter` initialized with an
underlying :class:`Logger` instance and a dict-like object. underlying :class:`Logger` instance and a dict-like object.
.. method:: LoggerAdapter.process(msg, kwargs) .. method:: process(msg, kwargs)
Modifies the message and/or keyword arguments passed to a logging call in Modifies the message and/or keyword arguments passed to a logging call in
order to insert contextual information. This implementation takes the order to insert contextual information. This implementation takes the object
object passed as *extra* to the constructor and adds it to *kwargs* using passed as *extra* to the constructor and adds it to *kwargs* using key
key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
(possibly modified) versions of the arguments passed in. (possibly modified) versions of the arguments passed in.
In addition to the above, :class:`LoggerAdapter` supports all the logging In addition to the above, :class:`LoggerAdapter` supports all the logging
......
...@@ -32,237 +32,243 @@ Maildir, mbox, MH, Babyl, and MMDF. ...@@ -32,237 +32,243 @@ Maildir, mbox, MH, Babyl, and MMDF.
A mailbox, which may be inspected and modified. A mailbox, which may be inspected and modified.
The :class:`Mailbox` class defines an interface and is not intended to be The :class:`Mailbox` class defines an interface and is not intended to be
instantiated. Instead, format-specific subclasses should inherit from instantiated. Instead, format-specific subclasses should inherit from
:class:`Mailbox` and your code should instantiate a particular subclass. :class:`Mailbox` and your code should instantiate a particular subclass.
The :class:`Mailbox` interface is dictionary-like, with small keys
corresponding to messages. Keys are issued by the :class:`Mailbox` instance
with which they will be used and are only meaningful to that :class:`Mailbox`
instance. A key continues to identify a message even if the corresponding
message is modified, such as by replacing it with another message.
Messages may be added to a :class:`Mailbox` instance using the set-like
method :meth:`add` and removed using a ``del`` statement or the set-like
methods :meth:`remove` and :meth:`discard`.
:class:`Mailbox` interface semantics differ from dictionary semantics in some
noteworthy ways. Each time a message is requested, a new representation
(typically a :class:`Message` instance) is generated based upon the current
state of the mailbox. Similarly, when a message is added to a
:class:`Mailbox` instance, the provided message representation's contents are
copied. In neither case is a reference to the message representation kept by
the :class:`Mailbox` instance.
The default :class:`Mailbox` iterator iterates over message representations,
not keys as the default dictionary iterator does. Moreover, modification of a
mailbox during iteration is safe and well-defined. Messages added to the
mailbox after an iterator is created will not be seen by the
iterator. Messages removed from the mailbox before the iterator yields them
will be silently skipped, though using a key from an iterator may result in a
:exc:`KeyError` exception if the corresponding message is subsequently
removed.
The :class:`Mailbox` interface is dictionary-like, with small keys corresponding .. warning::
to messages. Keys are issued by the :class:`Mailbox` instance with which they
will be used and are only meaningful to that :class:`Mailbox` instance. A key
continues to identify a message even if the corresponding message is modified,
such as by replacing it with another message.
Messages may be added to a :class:`Mailbox` instance using the set-like method
:meth:`add` and removed using a ``del`` statement or the set-like methods
:meth:`remove` and :meth:`discard`.
:class:`Mailbox` interface semantics differ from dictionary semantics in some
noteworthy ways. Each time a message is requested, a new representation
(typically a :class:`Message` instance) is generated based upon the current
state of the mailbox. Similarly, when a message is added to a :class:`Mailbox`
instance, the provided message representation's contents are copied. In neither
case is a reference to the message representation kept by the :class:`Mailbox`
instance.
The default :class:`Mailbox` iterator iterates over message representations, not
keys as the default dictionary iterator does. Moreover, modification of a
mailbox during iteration is safe and well-defined. Messages added to the mailbox
after an iterator is created will not be seen by the iterator. Messages removed
from the mailbox before the iterator yields them will be silently skipped,
though using a key from an iterator may result in a :exc:`KeyError` exception if
the corresponding message is subsequently removed.
.. warning::
Be very cautious when modifying mailboxes that might be simultaneously changed Be very cautious when modifying mailboxes that might be simultaneously
by some other process. The safest mailbox format to use for such tasks is changed by some other process. The safest mailbox format to use for such
Maildir; try to avoid using single-file formats such as mbox for concurrent tasks is Maildir; try to avoid using single-file formats such as mbox for
writing. If you're modifying a mailbox, you *must* lock it by calling the concurrent writing. If you're modifying a mailbox, you *must* lock it by
:meth:`lock` and :meth:`unlock` methods *before* reading any messages in the calling the :meth:`lock` and :meth:`unlock` methods *before* reading any
file or making any changes by adding or deleting a message. Failing to lock the messages in the file or making any changes by adding or deleting a
mailbox runs the risk of losing messages or corrupting the entire mailbox. message. Failing to lock the mailbox runs the risk of losing messages or
corrupting the entire mailbox.
:class:`Mailbox` instances have the following methods: :class:`Mailbox` instances have the following methods:
.. method:: Mailbox.add(message) .. method:: add(message)
Add *message* to the mailbox and return the key that has been assigned to it. Add *message* to the mailbox and return the key that has been assigned to
it.
Parameter *message* may be a :class:`Message` instance, an Parameter *message* may be a :class:`Message` instance, an
:class:`email.Message.Message` instance, a string, or a file-like object (which :class:`email.Message.Message` instance, a string, or a file-like object
should be open in text mode). If *message* is an instance of the appropriate (which should be open in text mode). If *message* is an instance of the
format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` appropriate format-specific :class:`Message` subclass (e.g., if it's an
instance and this is an :class:`mbox` instance), its format-specific information :class:`mboxMessage` instance and this is an :class:`mbox` instance), its
is used. Otherwise, reasonable defaults for format-specific information are format-specific information is used. Otherwise, reasonable defaults for
used. format-specific information are used.
.. method:: Mailbox.remove(key) .. method:: remove(key)
Mailbox.__delitem__(key) __delitem__(key)
Mailbox.discard(key) discard(key)
Delete the message corresponding to *key* from the mailbox. Delete the message corresponding to *key* from the mailbox.
If no such message exists, a :exc:`KeyError` exception is raised if the method If no such message exists, a :exc:`KeyError` exception is raised if the
was called as :meth:`remove` or :meth:`__delitem__` but no exception is raised method was called as :meth:`remove` or :meth:`__delitem__` but no
if the method was called as :meth:`discard`. The behavior of :meth:`discard` may exception is raised if the method was called as :meth:`discard`. The
be preferred if the underlying mailbox format supports concurrent modification behavior of :meth:`discard` may be preferred if the underlying mailbox
by other processes. format supports concurrent modification by other processes.
.. method:: Mailbox.__setitem__(key, message) .. method:: __setitem__(key, message)
Replace the message corresponding to *key* with *message*. Raise a Replace the message corresponding to *key* with *message*. Raise a
:exc:`KeyError` exception if no message already corresponds to *key*. :exc:`KeyError` exception if no message already corresponds to *key*.
As with :meth:`add`, parameter *message* may be a :class:`Message` instance, an As with :meth:`add`, parameter *message* may be a :class:`Message`
:class:`email.Message.Message` instance, a string, or a file-like object (which instance, an :class:`email.Message.Message` instance, a string, or a
should be open in text mode). If *message* is an instance of the appropriate file-like object (which should be open in text mode). If *message* is an
format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` instance of the appropriate format-specific :class:`Message` subclass
instance and this is an :class:`mbox` instance), its format-specific information (e.g., if it's an :class:`mboxMessage` instance and this is an
is used. Otherwise, the format-specific information of the message that :class:`mbox` instance), its format-specific information is
used. Otherwise, the format-specific information of the message that
currently corresponds to *key* is left unchanged. currently corresponds to *key* is left unchanged.
.. method:: Mailbox.iterkeys() .. method:: iterkeys()
Mailbox.keys() keys()
Return an iterator over all keys if called as :meth:`iterkeys` or return a list Return an iterator over all keys if called as :meth:`iterkeys` or return a
of keys if called as :meth:`keys`. list of keys if called as :meth:`keys`.
.. method:: Mailbox.itervalues() .. method:: itervalues()
Mailbox.__iter__() __iter__()
Mailbox.values() values()
Return an iterator over representations of all messages if called as Return an iterator over representations of all messages if called as
:meth:`itervalues` or :meth:`__iter__` or return a list of such representations :meth:`itervalues` or :meth:`__iter__` or return a list of such
if called as :meth:`values`. The messages are represented as instances of the representations if called as :meth:`values`. The messages are represented
appropriate format-specific :class:`Message` subclass unless a custom message as instances of the appropriate format-specific :class:`Message` subclass
factory was specified when the :class:`Mailbox` instance was initialized. unless a custom message factory was specified when the :class:`Mailbox`
instance was initialized.
.. note:: .. note::
The behavior of :meth:`__iter__` is unlike that of dictionaries, which iterate The behavior of :meth:`__iter__` is unlike that of dictionaries, which
over keys. iterate over keys.
.. method:: Mailbox.iteritems() .. method:: iteritems()
Mailbox.items() items()
Return an iterator over (*key*, *message*) pairs, where *key* is a key and Return an iterator over (*key*, *message*) pairs, where *key* is a key and
*message* is a message representation, if called as :meth:`iteritems` or return *message* is a message representation, if called as :meth:`iteritems` or
a list of such pairs if called as :meth:`items`. The messages are represented as return a list of such pairs if called as :meth:`items`. The messages are
instances of the appropriate format-specific :class:`Message` subclass unless a represented as instances of the appropriate format-specific
custom message factory was specified when the :class:`Mailbox` instance was :class:`Message` subclass unless a custom message factory was specified
initialized. when the :class:`Mailbox` instance was initialized.
.. method:: Mailbox.get(key[, default=None]) .. method:: get(key[, default=None])
Mailbox.__getitem__(key) __getitem__(key)
Return a representation of the message corresponding to *key*. If no such Return a representation of the message corresponding to *key*. If no such
message exists, *default* is returned if the method was called as :meth:`get` message exists, *default* is returned if the method was called as
and a :exc:`KeyError` exception is raised if the method was called as :meth:`get` and a :exc:`KeyError` exception is raised if the method was
:meth:`__getitem__`. The message is represented as an instance of the called as :meth:`__getitem__`. The message is represented as an instance
appropriate format-specific :class:`Message` subclass unless a custom message of the appropriate format-specific :class:`Message` subclass unless a
factory was specified when the :class:`Mailbox` instance was initialized. custom message factory was specified when the :class:`Mailbox` instance
was initialized.
.. method:: Mailbox.get_message(key) .. method:: get_message(key)
Return a representation of the message corresponding to *key* as an instance of Return a representation of the message corresponding to *key* as an
the appropriate format-specific :class:`Message` subclass, or raise a instance of the appropriate format-specific :class:`Message` subclass, or
:exc:`KeyError` exception if no such message exists. raise a :exc:`KeyError` exception if no such message exists.
.. method:: Mailbox.get_string(key) .. method:: get_string(key)
Return a string representation of the message corresponding to *key*, or raise a Return a string representation of the message corresponding to *key*, or
:exc:`KeyError` exception if no such message exists. raise a :exc:`KeyError` exception if no such message exists.
.. method:: Mailbox.get_file(key) .. method:: get_file(key)
Return a file-like representation of the message corresponding to *key*, or Return a file-like representation of the message corresponding to *key*,
raise a :exc:`KeyError` exception if no such message exists. The file-like or raise a :exc:`KeyError` exception if no such message exists. The
object behaves as if open in binary mode. This file should be closed once it is file-like object behaves as if open in binary mode. This file should be
no longer needed. closed once it is no longer needed.
.. note:: .. note::
Unlike other representations of messages, file-like representations are not Unlike other representations of messages, file-like representations are
necessarily independent of the :class:`Mailbox` instance that created them or of not necessarily independent of the :class:`Mailbox` instance that
the underlying mailbox. More specific documentation is provided by each created them or of the underlying mailbox. More specific documentation
subclass. is provided by each subclass.
.. method:: Mailbox.__contains__(key) .. method:: __contains__(key)
Return ``True`` if *key* corresponds to a message, ``False`` otherwise. Return ``True`` if *key* corresponds to a message, ``False`` otherwise.
.. method:: Mailbox.__len__() .. method:: __len__()
Return a count of messages in the mailbox. Return a count of messages in the mailbox.
.. method:: Mailbox.clear() .. method:: clear()
Delete all messages from the mailbox. Delete all messages from the mailbox.
.. method:: Mailbox.pop(key[, default]) .. method:: pop(key[, default])
Return a representation of the message corresponding to *key* and delete the Return a representation of the message corresponding to *key* and delete
message. If no such message exists, return *default* if it was supplied or else the message. If no such message exists, return *default* if it was
raise a :exc:`KeyError` exception. The message is represented as an instance of supplied or else raise a :exc:`KeyError` exception. The message is
the appropriate format-specific :class:`Message` subclass unless a custom represented as an instance of the appropriate format-specific
message factory was specified when the :class:`Mailbox` instance was :class:`Message` subclass unless a custom message factory was specified
initialized. when the :class:`Mailbox` instance was initialized.
.. method:: Mailbox.popitem() .. method:: popitem()
Return an arbitrary (*key*, *message*) pair, where *key* is a key and *message* Return an arbitrary (*key*, *message*) pair, where *key* is a key and
is a message representation, and delete the corresponding message. If the *message* is a message representation, and delete the corresponding
mailbox is empty, raise a :exc:`KeyError` exception. The message is represented message. If the mailbox is empty, raise a :exc:`KeyError` exception. The
as an instance of the appropriate format-specific :class:`Message` subclass message is represented as an instance of the appropriate format-specific
unless a custom message factory was specified when the :class:`Mailbox` instance :class:`Message` subclass unless a custom message factory was specified
was initialized. when the :class:`Mailbox` instance was initialized.
.. method:: Mailbox.update(arg) .. method:: update(arg)
Parameter *arg* should be a *key*-to-*message* mapping or an iterable of (*key*, Parameter *arg* should be a *key*-to-*message* mapping or an iterable of
*message*) pairs. Updates the mailbox so that, for each given *key* and (*key*, *message*) pairs. Updates the mailbox so that, for each given
*message*, the message corresponding to *key* is set to *message* as if by using *key* and *message*, the message corresponding to *key* is set to
:meth:`__setitem__`. As with :meth:`__setitem__`, each *key* must already *message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`,
correspond to a message in the mailbox or else a :exc:`KeyError` exception will each *key* must already correspond to a message in the mailbox or else a
be raised, so in general it is incorrect for *arg* to be a :class:`Mailbox` :exc:`KeyError` exception will be raised, so in general it is incorrect
instance. for *arg* to be a :class:`Mailbox` instance.
.. note:: .. note::
Unlike with dictionaries, keyword arguments are not supported. Unlike with dictionaries, keyword arguments are not supported.
.. method:: Mailbox.flush() .. method:: flush()
Write any pending changes to the filesystem. For some :class:`Mailbox` Write any pending changes to the filesystem. For some :class:`Mailbox`
subclasses, changes are always written immediately and :meth:`flush` does subclasses, changes are always written immediately and :meth:`flush` does
nothing, but you should still make a habit of calling this method. nothing, but you should still make a habit of calling this method.
.. method:: Mailbox.lock() .. method:: lock()
Acquire an exclusive advisory lock on the mailbox so that other processes know Acquire an exclusive advisory lock on the mailbox so that other processes
not to modify it. An :exc:`ExternalClashError` is raised if the lock is not know not to modify it. An :exc:`ExternalClashError` is raised if the lock
available. The particular locking mechanisms used depend upon the mailbox is not available. The particular locking mechanisms used depend upon the
format. You should *always* lock the mailbox before making any modifications mailbox format. You should *always* lock the mailbox before making any
to its contents. modifications to its contents.
.. method:: Mailbox.unlock() .. method:: unlock()
Release the lock on the mailbox, if any. Release the lock on the mailbox, if any.
.. method:: Mailbox.close() .. method:: close()
Flush the mailbox, unlock it if necessary, and close any open files. For some Flush the mailbox, unlock it if necessary, and close any open files. For
:class:`Mailbox` subclasses, this method does nothing. some :class:`Mailbox` subclasses, this method does nothing.
.. _mailbox-maildir: .. _mailbox-maildir:
...@@ -285,113 +291,115 @@ the corresponding message is subsequently removed. ...@@ -285,113 +291,115 @@ the corresponding message is subsequently removed.
instance that behaves like instances of other :class:`Mailbox` subclasses, set instance that behaves like instances of other :class:`Mailbox` subclasses, set
*factory* to ``None``. *factory* to ``None``.
Maildir is a directory-based mailbox format invented for the qmail mail transfer Maildir is a directory-based mailbox format invented for the qmail mail
agent and now widely supported by other programs. Messages in a Maildir mailbox transfer agent and now widely supported by other programs. Messages in a
are stored in separate files within a common directory structure. This design Maildir mailbox are stored in separate files within a common directory
allows Maildir mailboxes to be accessed and modified by multiple unrelated structure. This design allows Maildir mailboxes to be accessed and modified
programs without data corruption, so file locking is unnecessary. by multiple unrelated programs without data corruption, so file locking is
unnecessary.
Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
:file:`new`, and :file:`cur`. Messages are created momentarily in the Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to :file:`new`, and :file:`cur`. Messages are created momentarily in the
finalize delivery. A mail user agent may subsequently move the message to the :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to
:file:`cur` subdirectory and store information about the state of the message in finalize delivery. A mail user agent may subsequently move the message to the
a special "info" section appended to its file name. :file:`cur` subdirectory and store information about the state of the message
in a special "info" section appended to its file name.
Folders of the style introduced by the Courier mail transfer agent are also
supported. Any subdirectory of the main mailbox is considered a folder if
``'.'`` is the first character in its name. Folder names are represented by
:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
mailbox but should not contain other folders. Instead, a logical nesting is
indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
Folders of the style introduced by the Courier mail transfer agent are also .. note::
supported. Any subdirectory of the main mailbox is considered a folder if
``'.'`` is the first character in its name. Folder names are represented by
:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
mailbox but should not contain other folders. Instead, a logical nesting is
indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".
.. note::
The Maildir specification requires the use of a colon (``':'``) in certain The Maildir specification requires the use of a colon (``':'``) in certain
message file names. However, some operating systems do not permit this character message file names. However, some operating systems do not permit this
in file names, If you wish to use a Maildir-like format on such an operating character in file names, If you wish to use a Maildir-like format on such
system, you should specify another character to use instead. The exclamation an operating system, you should specify another character to use
point (``'!'``) is a popular choice. For example:: instead. The exclamation point (``'!'``) is a popular choice. For
example::
import mailbox import mailbox
mailbox.Maildir.colon = '!' mailbox.Maildir.colon = '!'
The :attr:`colon` attribute may also be set on a per-instance basis. The :attr:`colon` attribute may also be set on a per-instance basis.
:class:`Maildir` instances have all of the methods of :class:`Mailbox` in :class:`Maildir` instances have all of the methods of :class:`Mailbox` in
addition to the following: addition to the following:
.. method:: Maildir.list_folders() .. method:: list_folders()
Return a list of the names of all folders. Return a list of the names of all folders.
.. method:: Maildir.get_folder(folder) .. method:: .et_folder(folder)
Return a :class:`Maildir` instance representing the folder whose name is Return a :class:`Maildir` instance representing the folder whose name is
*folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder does not *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
exist. does not exist.
.. method:: Maildir.add_folder(folder) .. method:: add_folder(folder)
Create a folder whose name is *folder* and return a :class:`Maildir` instance Create a folder whose name is *folder* and return a :class:`Maildir`
representing it. instance representing it.
.. method:: Maildir.remove_folder(folder) .. method:: remove_folder(folder)
Delete the folder whose name is *folder*. If the folder contains any messages, a Delete the folder whose name is *folder*. If the folder contains any
:exc:`NotEmptyError` exception will be raised and the folder will not be messages, a :exc:`NotEmptyError` exception will be raised and the folder
deleted. will not be deleted.
.. method:: Maildir.clean() .. method:: clean()
Delete temporary files from the mailbox that have not been accessed in the last Delete temporary files from the mailbox that have not been accessed in the
36 hours. The Maildir specification says that mail-reading programs should do last 36 hours. The Maildir specification says that mail-reading programs
this occasionally. should do this occasionally.
Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
remarks: remarks:
.. method:: Maildir.add(message) .. method:: add(message)
Maildir.__setitem__(key, message) __setitem__(key, message)
Maildir.update(arg) update(arg)
.. warning:: .. warning::
These methods generate unique file names based upon the current process ID. When These methods generate unique file names based upon the current process
using multiple threads, undetected name clashes may occur and cause corruption ID. When using multiple threads, undetected name clashes may occur and
of the mailbox unless threads are coordinated to avoid using these methods to cause corruption of the mailbox unless threads are coordinated to avoid
manipulate the same mailbox simultaneously. using these methods to manipulate the same mailbox simultaneously.
.. method:: Maildir.flush() .. method:: flush()
All changes to Maildir mailboxes are immediately applied, so this method does All changes to Maildir mailboxes are immediately applied, so this method
nothing. does nothing.
.. method:: Maildir.lock() .. method:: lock()
Maildir.unlock() unlock()
Maildir mailboxes do not support (or require) locking, so these methods do Maildir mailboxes do not support (or require) locking, so these methods do
nothing. nothing.
.. method:: Maildir.close() .. method:: close()
:class:`Maildir` instances do not keep any open files and the underlying :class:`Maildir` instances do not keep any open files and the underlying
mailboxes do not support locking, so this method does nothing. mailboxes do not support locking, so this method does nothing.
.. method:: Maildir.get_file(key) .. method:: get_file(key)
Depending upon the host platform, it may not be possible to modify or remove the Depending upon the host platform, it may not be possible to modify or
underlying message while the returned file remains open. remove the underlying message while the returned file remains open.
.. seealso:: .. seealso::
...@@ -423,30 +431,31 @@ remarks: ...@@ -423,30 +431,31 @@ remarks:
representation. If *create* is ``True``, the mailbox is created if it does not representation. If *create* is ``True``, the mailbox is created if it does not
exist. exist.
The mbox format is the classic format for storing mail on Unix systems. All The mbox format is the classic format for storing mail on Unix systems. All
messages in an mbox mailbox are stored in a single file with the beginning of messages in an mbox mailbox are stored in a single file with the beginning of
each message indicated by a line whose first five characters are "From ". each message indicated by a line whose first five characters are "From ".
Several variations of the mbox format exist to address perceived shortcomings in Several variations of the mbox format exist to address perceived shortcomings in
the original. In the interest of compatibility, :class:`mbox` implements the the original. In the interest of compatibility, :class:`mbox` implements the
original format, which is sometimes referred to as :dfn:`mboxo`. This means that original format, which is sometimes referred to as :dfn:`mboxo`. This means that
the :mailheader:`Content-Length` header, if present, is ignored and that any the :mailheader:`Content-Length` header, if present, is ignored and that any
occurrences of "From " at the beginning of a line in a message body are occurrences of "From " at the beginning of a line in a message body are
transformed to ">From " when storing the message, although occurrences of ">From transformed to ">From " when storing the message, although occurrences of ">From
" are not transformed to "From " when reading the message. " are not transformed to "From " when reading the message.
Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
remarks: remarks:
.. method:: mbox.get_file(key) .. method:: get_file(key)
Using the file after calling :meth:`flush` or :meth:`close` on the :class:`mbox` Using the file after calling :meth:`flush` or :meth:`close` on the
instance may yield unpredictable results or raise an exception. :class:`mbox` instance may yield unpredictable results or raise an
exception.
.. method:: mbox.lock() .. method:: lock()
mbox.unlock() unlock()
Three locking mechanisms are used---dot locking and, if available, the Three locking mechanisms are used---dot locking and, if available, the
:cfunc:`flock` and :cfunc:`lockf` system calls. :cfunc:`flock` and :cfunc:`lockf` system calls.
...@@ -482,106 +491,109 @@ remarks: ...@@ -482,106 +491,109 @@ remarks:
representation. If *create* is ``True``, the mailbox is created if it does not representation. If *create* is ``True``, the mailbox is created if it does not
exist. exist.
MH is a directory-based mailbox format invented for the MH Message Handling MH is a directory-based mailbox format invented for the MH Message Handling
System, a mail user agent. Each message in an MH mailbox resides in its own System, a mail user agent. Each message in an MH mailbox resides in its own
file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in
addition to messages. Folders may be nested indefinitely. MH mailboxes also addition to messages. Folders may be nested indefinitely. MH mailboxes also
support :dfn:`sequences`, which are named lists used to logically group messages support :dfn:`sequences`, which are named lists used to logically group
without moving them to sub-folders. Sequences are defined in a file called messages without moving them to sub-folders. Sequences are defined in a file
:file:`.mh_sequences` in each folder. called :file:`.mh_sequences` in each folder.
The :class:`MH` class manipulates MH mailboxes, but it does not attempt to The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
emulate all of :program:`mh`'s behaviors. In particular, it does not modify and emulate all of :program:`mh`'s behaviors. In particular, it does not modify
is not affected by the :file:`context` or :file:`.mh_profile` files that are and is not affected by the :file:`context` or :file:`.mh_profile` files that
used by :program:`mh` to store its state and configuration. are used by :program:`mh` to store its state and configuration.
:class:`MH` instances have all of the methods of :class:`Mailbox` in addition to :class:`MH` instances have all of the methods of :class:`Mailbox` in addition
the following: to the following:
.. method:: MH.list_folders() .. method:: list_folders()
Return a list of the names of all folders. Return a list of the names of all folders.
.. method:: MH.get_folder(folder) .. method:: get_folder(folder)
Return an :class:`MH` instance representing the folder whose name is *folder*. A Return an :class:`MH` instance representing the folder whose name is
:exc:`NoSuchMailboxError` exception is raised if the folder does not exist. *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
does not exist.
.. method:: MH.add_folder(folder) .. method:: add_folder(folder)
Create a folder whose name is *folder* and return an :class:`MH` instance Create a folder whose name is *folder* and return an :class:`MH` instance
representing it. representing it.
.. method:: MH.remove_folder(folder) .. method:: remove_folder(folder)
Delete the folder whose name is *folder*. If the folder contains any messages, a Delete the folder whose name is *folder*. If the folder contains any
:exc:`NotEmptyError` exception will be raised and the folder will not be messages, a :exc:`NotEmptyError` exception will be raised and the folder
deleted. will not be deleted.
.. method:: MH.get_sequences() .. method:: get_sequences()
Return a dictionary of sequence names mapped to key lists. If there are no Return a dictionary of sequence names mapped to key lists. If there are no
sequences, the empty dictionary is returned. sequences, the empty dictionary is returned.
.. method:: MH.set_sequences(sequences) .. method:: set_sequences(sequences)
Re-define the sequences that exist in the mailbox based upon *sequences*, a Re-define the sequences that exist in the mailbox based upon *sequences*,
dictionary of names mapped to key lists, like returned by :meth:`get_sequences`. a dictionary of names mapped to key lists, like returned by
:meth:`get_sequences`.
.. method:: MH.pack() .. method:: pack()
Rename messages in the mailbox as necessary to eliminate gaps in numbering. Rename messages in the mailbox as necessary to eliminate gaps in
Entries in the sequences list are updated correspondingly. numbering. Entries in the sequences list are updated correspondingly.
.. note:: .. note::
Already-issued keys are invalidated by this operation and should not be Already-issued keys are invalidated by this operation and should not be
subsequently used. subsequently used.
Some :class:`Mailbox` methods implemented by :class:`MH` deserve special Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
remarks: remarks:
.. method:: MH.remove(key) .. method:: remove(key)
MH.__delitem__(key) __delitem__(key)
MH.discard(key) discard(key)
These methods immediately delete the message. The MH convention of marking a These methods immediately delete the message. The MH convention of marking
message for deletion by prepending a comma to its name is not used. a message for deletion by prepending a comma to its name is not used.
.. method:: MH.lock() .. method:: lock()
MH.unlock() unlock()
Three locking mechanisms are used---dot locking and, if available, the Three locking mechanisms are used---dot locking and, if available, the
:cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking the :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking
mailbox means locking the :file:`.mh_sequences` file and, only for the duration the mailbox means locking the :file:`.mh_sequences` file and, only for the
of any operations that affect them, locking individual message files. duration of any operations that affect them, locking individual message
files.
.. method:: MH.get_file(key) .. method:: get_file(key)
Depending upon the host platform, it may not be possible to remove the Depending upon the host platform, it may not be possible to remove the
underlying message while the returned file remains open. underlying message while the returned file remains open.
.. method:: MH.flush() .. method:: flush()
All changes to MH mailboxes are immediately applied, so this method does All changes to MH mailboxes are immediately applied, so this method does
nothing. nothing.
.. method:: MH.close() .. method:: close()
:class:`MH` instances do not keep any open files, so this method is equivalent :class:`MH` instances do not keep any open files, so this method is
to :meth:`unlock`. equivalent to :meth:`unlock`.
.. seealso:: .. seealso::
...@@ -609,51 +621,53 @@ remarks: ...@@ -609,51 +621,53 @@ remarks:
representation. If *create* is ``True``, the mailbox is created if it does not representation. If *create* is ``True``, the mailbox is created if it does not
exist. exist.
Babyl is a single-file mailbox format used by the Rmail mail user agent included Babyl is a single-file mailbox format used by the Rmail mail user agent
with Emacs. The beginning of a message is indicated by a line containing the two included with Emacs. The beginning of a message is indicated by a line
characters Control-Underscore (``'\037'``) and Control-L (``'\014'``). The end containing the two characters Control-Underscore (``'\037'``) and Control-L
of a message is indicated by the start of the next message or, in the case of (``'\014'``). The end of a message is indicated by the start of the next
the last message, a line containing a Control-Underscore (``'\037'``) message or, in the case of the last message, a line containing a
character. Control-Underscore (``'\037'``) character.
Messages in a Babyl mailbox have two sets of headers, original headers and Messages in a Babyl mailbox have two sets of headers, original headers and
so-called visible headers. Visible headers are typically a subset of the so-called visible headers. Visible headers are typically a subset of the
original headers that have been reformatted or abridged to be more original headers that have been reformatted or abridged to be more
attractive. Each message in a Babyl mailbox also has an accompanying list of attractive. Each message in a Babyl mailbox also has an accompanying list of
:dfn:`labels`, or short strings that record extra information about the message, :dfn:`labels`, or short strings that record extra information about the
and a list of all user-defined labels found in the mailbox is kept in the Babyl message, and a list of all user-defined labels found in the mailbox is kept
options section. in the Babyl options section.
:class:`Babyl` instances have all of the methods of :class:`Mailbox` in addition :class:`Babyl` instances have all of the methods of :class:`Mailbox` in
to the following: addition to the following:
.. method:: Babyl.get_labels() .. method:: get_labels()
Return a list of the names of all user-defined labels used in the mailbox. Return a list of the names of all user-defined labels used in the mailbox.
.. note:: .. note::
The actual messages are inspected to determine which labels exist in the mailbox The actual messages are inspected to determine which labels exist in
rather than consulting the list of labels in the Babyl options section, but the the mailbox rather than consulting the list of labels in the Babyl
Babyl section is updated whenever the mailbox is modified. options section, but the Babyl section is updated whenever the mailbox
is modified.
Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
remarks: remarks:
.. method:: Babyl.get_file(key) .. method:: get_file(key)
In Babyl mailboxes, the headers of a message are not stored contiguously with In Babyl mailboxes, the headers of a message are not stored contiguously
the body of the message. To generate a file-like representation, the headers and with the body of the message. To generate a file-like representation, the
body are copied together into a :class:`StringIO` instance (from the headers and body are copied together into a :class:`StringIO` instance
:mod:`StringIO` module), which has an API identical to that of a file. As a (from the :mod:`StringIO` module), which has an API identical to that of a
result, the file-like object is truly independent of the underlying mailbox but file. As a result, the file-like object is truly independent of the
does not save memory compared to a string representation. underlying mailbox but does not save memory compared to a string
representation.
.. method:: Babyl.lock() .. method:: lock()
Babyl.unlock() unlock()
Three locking mechanisms are used---dot locking and, if available, the Three locking mechanisms are used---dot locking and, if available, the
:cfunc:`flock` and :cfunc:`lockf` system calls. :cfunc:`flock` and :cfunc:`lockf` system calls.
...@@ -683,27 +697,28 @@ remarks: ...@@ -683,27 +697,28 @@ remarks:
representation. If *create* is ``True``, the mailbox is created if it does not representation. If *create* is ``True``, the mailbox is created if it does not
exist. exist.
MMDF is a single-file mailbox format invented for the Multichannel Memorandum MMDF is a single-file mailbox format invented for the Multichannel Memorandum
Distribution Facility, a mail transfer agent. Each message is in the same form Distribution Facility, a mail transfer agent. Each message is in the same
as an mbox message but is bracketed before and after by lines containing four form as an mbox message but is bracketed before and after by lines containing
Control-A (``'\001'``) characters. As with the mbox format, the beginning of four Control-A (``'\001'``) characters. As with the mbox format, the
each message is indicated by a line whose first five characters are "From ", but beginning of each message is indicated by a line whose first five characters
additional occurrences of "From " are not transformed to ">From " when storing are "From ", but additional occurrences of "From " are not transformed to
messages because the extra message separator lines prevent mistaking such ">From " when storing messages because the extra message separator lines
occurrences for the starts of subsequent messages. prevent mistaking such occurrences for the starts of subsequent messages.
Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
remarks: remarks:
.. method:: MMDF.get_file(key) .. method:: get_file(key)
Using the file after calling :meth:`flush` or :meth:`close` on the :class:`MMDF` Using the file after calling :meth:`flush` or :meth:`close` on the
instance may yield unpredictable results or raise an exception. :class:`MMDF` instance may yield unpredictable results or raise an
exception.
.. method:: MMDF.lock() .. method:: lock()
MMDF.unlock() unlock()
Three locking mechanisms are used---dot locking and, if available, the Three locking mechanisms are used---dot locking and, if available, the
:cfunc:`flock` and :cfunc:`lockf` system calls. :cfunc:`flock` and :cfunc:`lockf` system calls.
...@@ -737,21 +752,21 @@ remarks: ...@@ -737,21 +752,21 @@ remarks:
or a file, it should contain an :rfc:`2822`\ -compliant message, which is read or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
and parsed. and parsed.
The format-specific state and behaviors offered by subclasses vary, but in The format-specific state and behaviors offered by subclasses vary, but in
general it is only the properties that are not specific to a particular mailbox general it is only the properties that are not specific to a particular
that are supported (although presumably the properties are specific to a mailbox that are supported (although presumably the properties are specific
particular mailbox format). For example, file offsets for single-file mailbox to a particular mailbox format). For example, file offsets for single-file
formats and file names for directory-based mailbox formats are not retained, mailbox formats and file names for directory-based mailbox formats are not
because they are only applicable to the original mailbox. But state such as retained, because they are only applicable to the original mailbox. But state
whether a message has been read by the user or marked as important is retained, such as whether a message has been read by the user or marked as important is
because it applies to the message itself. retained, because it applies to the message itself.
There is no requirement that :class:`Message` instances be used to represent There is no requirement that :class:`Message` instances be used to represent
messages retrieved using :class:`Mailbox` instances. In some situations, the messages retrieved using :class:`Mailbox` instances. In some situations, the
time and memory required to generate :class:`Message` representations might not time and memory required to generate :class:`Message` representations might
not acceptable. For such situations, :class:`Mailbox` instances also offer not not acceptable. For such situations, :class:`Mailbox` instances also
string and file-like representations, and a custom message factory may be offer string and file-like representations, and a custom message factory may
specified when a :class:`Mailbox` instance is initialized. be specified when a :class:`Mailbox` instance is initialized.
.. _mailbox-maildirmessage: .. _mailbox-maildirmessage:
...@@ -765,37 +780,37 @@ specified when a :class:`Mailbox` instance is initialized. ...@@ -765,37 +780,37 @@ specified when a :class:`Mailbox` instance is initialized.
A message with Maildir-specific behaviors. Parameter *message* has the same A message with Maildir-specific behaviors. Parameter *message* has the same
meaning as with the :class:`Message` constructor. meaning as with the :class:`Message` constructor.
Typically, a mail user agent application moves all of the messages in the Typically, a mail user agent application moves all of the messages in the
:file:`new` subdirectory to the :file:`cur` subdirectory after the first time :file:`new` subdirectory to the :file:`cur` subdirectory after the first time
the user opens and closes the mailbox, recording that the messages are old the user opens and closes the mailbox, recording that the messages are old
whether or not they've actually been read. Each message in :file:`cur` has an whether or not they've actually been read. Each message in :file:`cur` has an
"info" section added to its file name to store information about its state. "info" section added to its file name to store information about its state.
(Some mail readers may also add an "info" section to messages in :file:`new`.) (Some mail readers may also add an "info" section to messages in
The "info" section may take one of two forms: it may contain "2," followed by a :file:`new`.) The "info" section may take one of two forms: it may contain
list of standardized flags (e.g., "2,FR") or it may contain "1," followed by "2," followed by a list of standardized flags (e.g., "2,FR") or it may
so-called experimental information. Standard flags for Maildir messages are as contain "1," followed by so-called experimental information. Standard flags
follows: for Maildir messages are as follows:
+------+---------+--------------------------------+ +------+---------+--------------------------------+
| Flag | Meaning | Explanation | | Flag | Meaning | Explanation |
+======+=========+================================+ +======+=========+================================+
| D | Draft | Under composition | | D | Draft | Under composition |
+------+---------+--------------------------------+ +------+---------+--------------------------------+
| F | Flagged | Marked as important | | F | Flagged | Marked as important |
+------+---------+--------------------------------+ +------+---------+--------------------------------+
| P | Passed | Forwarded, resent, or bounced | | P | Passed | Forwarded, resent, or bounced |
+------+---------+--------------------------------+ +------+---------+--------------------------------+
| R | Replied | Replied to | | R | Replied | Replied to |
+------+---------+--------------------------------+ +------+---------+--------------------------------+
| S | Seen | Read | | S | Seen | Read |
+------+---------+--------------------------------+ +------+---------+--------------------------------+
| T | Trashed | Marked for subsequent deletion | | T | Trashed | Marked for subsequent deletion |
+------+---------+--------------------------------+ +------+---------+--------------------------------+
:class:`MaildirMessage` instances offer the following methods: :class:`MaildirMessage` instances offer the following methods:
.. method:: MaildirMessage.get_subdir() .. method:: get_subdir()
Return either "new" (if the message should be stored in the :file:`new` Return either "new" (if the message should be stored in the :file:`new`
subdirectory) or "cur" (if the message should be stored in the :file:`cur` subdirectory) or "cur" (if the message should be stored in the :file:`cur`
...@@ -803,66 +818,69 @@ follows: ...@@ -803,66 +818,69 @@ follows:
.. note:: .. note::
A message is typically moved from :file:`new` to :file:`cur` after its mailbox A message is typically moved from :file:`new` to :file:`cur` after its
has been accessed, whether or not the message is has been read. A message mailbox has been accessed, whether or not the message is has been
``msg`` has been read if ``"S" in msg.get_flags()`` is ``True``. read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is
``True``.
.. method:: MaildirMessage.set_subdir(subdir) .. method:: set_subdir(subdir)
Set the subdirectory the message should be stored in. Parameter *subdir* must be Set the subdirectory the message should be stored in. Parameter *subdir*
either "new" or "cur". must be either "new" or "cur".
.. method:: MaildirMessage.get_flags() .. method:: get_flags()
Return a string specifying the flags that are currently set. If the message Return a string specifying the flags that are currently set. If the
complies with the standard Maildir format, the result is the concatenation in message complies with the standard Maildir format, the result is the
alphabetical order of zero or one occurrence of each of ``'D'``, ``'F'``, concatenation in alphabetical order of zero or one occurrence of each of
``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string is returned if no flags ``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string
are set or if "info" contains experimental semantics. is returned if no flags are set or if "info" contains experimental
semantics.
.. method:: MaildirMessage.set_flags(flags) .. method:: set_flags(flags)
Set the flags specified by *flags* and unset all others. Set the flags specified by *flags* and unset all others.
.. method:: MaildirMessage.add_flag(flag) .. method:: add_flag(flag)
Set the flag(s) specified by *flag* without changing other flags. To add more Set the flag(s) specified by *flag* without changing other flags. To add
than one flag at a time, *flag* may be a string of more than one character. The more than one flag at a time, *flag* may be a string of more than one
current "info" is overwritten whether or not it contains experimental character. The current "info" is overwritten whether or not it contains
information rather than flags. experimental information rather than flags.
.. method:: MaildirMessage.remove_flag(flag) .. method:: remove_flag(flag)
Unset the flag(s) specified by *flag* without changing other flags. To remove Unset the flag(s) specified by *flag* without changing other flags. To
more than one flag at a time, *flag* maybe a string of more than one character. remove more than one flag at a time, *flag* maybe a string of more than
If "info" contains experimental information rather than flags, the current one character. If "info" contains experimental information rather than
"info" is not modified. flags, the current "info" is not modified.
.. method:: MaildirMessage.get_date() .. method:: get_date()
Return the delivery date of the message as a floating-point number representing Return the delivery date of the message as a floating-point number
seconds since the epoch. representing seconds since the epoch.
.. method:: MaildirMessage.set_date(date) .. method:: set_date(date)
Set the delivery date of the message to *date*, a floating-point number Set the delivery date of the message to *date*, a floating-point number
representing seconds since the epoch. representing seconds since the epoch.
.. method:: MaildirMessage.get_info() .. method:: get_info()
Return a string containing the "info" for a message. This is useful for Return a string containing the "info" for a message. This is useful for
accessing and modifying "info" that is experimental (i.e., not a list of flags). accessing and modifying "info" that is experimental (i.e., not a list of
flags).
.. method:: MaildirMessage.set_info(info) .. method:: set_info(info)
Set "info" to *info*, which should be a string. Set "info" to *info*, which should be a string.
...@@ -930,78 +948,81 @@ When a :class:`MaildirMessage` instance is created based upon a ...@@ -930,78 +948,81 @@ When a :class:`MaildirMessage` instance is created based upon a
A message with mbox-specific behaviors. Parameter *message* has the same meaning A message with mbox-specific behaviors. Parameter *message* has the same meaning
as with the :class:`Message` constructor. as with the :class:`Message` constructor.
Messages in an mbox mailbox are stored together in a single file. The sender's Messages in an mbox mailbox are stored together in a single file. The
envelope address and the time of delivery are typically stored in a line sender's envelope address and the time of delivery are typically stored in a
beginning with "From " that is used to indicate the start of a message, though line beginning with "From " that is used to indicate the start of a message,
there is considerable variation in the exact format of this data among mbox though there is considerable variation in the exact format of this data among
implementations. Flags that indicate the state of the message, such as whether mbox implementations. Flags that indicate the state of the message, such as
it has been read or marked as important, are typically stored in whether it has been read or marked as important, are typically stored in
:mailheader:`Status` and :mailheader:`X-Status` headers. :mailheader:`Status` and :mailheader:`X-Status` headers.
Conventional flags for mbox messages are as follows: Conventional flags for mbox messages are as follows:
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| Flag | Meaning | Explanation | | Flag | Meaning | Explanation |
+======+==========+================================+ +======+==========+================================+
| R | Read | Read | | R | Read | Read |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| O | Old | Previously detected by MUA | | O | Old | Previously detected by MUA |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| D | Deleted | Marked for subsequent deletion | | D | Deleted | Marked for subsequent deletion |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| F | Flagged | Marked as important | | F | Flagged | Marked as important |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| A | Answered | Replied to | | A | Answered | Replied to |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
The "R" and "O" flags are stored in the :mailheader:`Status` header, and the The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
flags and headers typically appear in the order mentioned. flags and headers typically appear in the order mentioned.
:class:`mboxMessage` instances offer the following methods: :class:`mboxMessage` instances offer the following methods:
.. method:: mboxMessage.get_from() .. method:: get_from()
Return a string representing the "From " line that marks the start of the Return a string representing the "From " line that marks the start of the
message in an mbox mailbox. The leading "From " and the trailing newline are message in an mbox mailbox. The leading "From " and the trailing newline
excluded. are excluded.
.. method:: mboxMessage.set_from(from_[, time_=None]) .. method:: set_from(from_[, time_=None])
Set the "From " line to *from_*, which should be specified without a leading Set the "From " line to *from_*, which should be specified without a
"From " or trailing newline. For convenience, *time_* may be specified and will leading "From " or trailing newline. For convenience, *time_* may be
be formatted appropriately and appended to *from_*. If *time_* is specified, it specified and will be formatted appropriately and appended to *from_*. If
should be a :class:`struct_time` instance, a tuple suitable for passing to *time_* is specified, it should be a :class:`struct_time` instance, a
:meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
:meth:`time.gmtime`).
.. method:: mboxMessage.get_flags() .. method:: get_flags()
Return a string specifying the flags that are currently set. If the message Return a string specifying the flags that are currently set. If the
complies with the conventional format, the result is the concatenation in the message complies with the conventional format, the result is the
following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, concatenation in the following order of zero or one occurrence of each of
``'F'``, and ``'A'``. ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
.. method:: mboxMessage.set_flags(flags) .. method:: set_flags(flags)
Set the flags specified by *flags* and unset all others. Parameter *flags* Set the flags specified by *flags* and unset all others. Parameter *flags*
should be the concatenation in any order of zero or more occurrences of each of should be the concatenation in any order of zero or more occurrences of
``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
.. method:: mboxMessage.add_flag(flag) .. method:: add_flag(flag)
Set the flag(s) specified by *flag* without changing other flags. To add more Set the flag(s) specified by *flag* without changing other flags. To add
than one flag at a time, *flag* may be a string of more than one character. more than one flag at a time, *flag* may be a string of more than one
character.
.. method:: mboxMessage.remove_flag(flag) .. method:: remove_flag(flag)
Unset the flag(s) specified by *flag* without changing other flags. To remove Unset the flag(s) specified by *flag* without changing other flags. To
more than one flag at a time, *flag* maybe a string of more than one character. remove more than one flag at a time, *flag* maybe a string of more than
one character.
When an :class:`mboxMessage` instance is created based upon a When an :class:`mboxMessage` instance is created based upon a
:class:`MaildirMessage` instance, a "From " line is generated based upon the :class:`MaildirMessage` instance, a "From " line is generated based upon the
...@@ -1081,41 +1102,41 @@ instance, the "From " line is copied and all flags directly correspond: ...@@ -1081,41 +1102,41 @@ instance, the "From " line is copied and all flags directly correspond:
A message with MH-specific behaviors. Parameter *message* has the same meaning A message with MH-specific behaviors. Parameter *message* has the same meaning
as with the :class:`Message` constructor. as with the :class:`Message` constructor.
MH messages do not support marks or flags in the traditional sense, but they do MH messages do not support marks or flags in the traditional sense, but they
support sequences, which are logical groupings of arbitrary messages. Some mail do support sequences, which are logical groupings of arbitrary messages. Some
reading programs (although not the standard :program:`mh` and :program:`nmh`) mail reading programs (although not the standard :program:`mh` and
use sequences in much the same way flags are used with other formats, as :program:`nmh`) use sequences in much the same way flags are used with other
follows: formats, as follows:
+----------+------------------------------------------+ +----------+------------------------------------------+
| Sequence | Explanation | | Sequence | Explanation |
+==========+==========================================+ +==========+==========================================+
| unseen | Not read, but previously detected by MUA | | unseen | Not read, but previously detected by MUA |
+----------+------------------------------------------+ +----------+------------------------------------------+
| replied | Replied to | | replied | Replied to |
+----------+------------------------------------------+ +----------+------------------------------------------+
| flagged | Marked as important | | flagged | Marked as important |
+----------+------------------------------------------+ +----------+------------------------------------------+
:class:`MHMessage` instances offer the following methods: :class:`MHMessage` instances offer the following methods:
.. method:: MHMessage.get_sequences() .. method:: get_sequences()
Return a list of the names of sequences that include this message. Return a list of the names of sequences that include this message.
.. method:: MHMessage.set_sequences(sequences) .. method:: set_sequences(sequences)
Set the list of sequences that include this message. Set the list of sequences that include this message.
.. method:: MHMessage.add_sequence(sequence) .. method:: add_sequence(sequence)
Add *sequence* to the list of sequences that include this message. Add *sequence* to the list of sequences that include this message.
.. method:: MHMessage.remove_sequence(sequence) .. method:: remove_sequence(sequence)
Remove *sequence* from the list of sequences that include this message. Remove *sequence* from the list of sequences that include this message.
...@@ -1171,79 +1192,79 @@ When an :class:`MHMessage` instance is created based upon a ...@@ -1171,79 +1192,79 @@ When an :class:`MHMessage` instance is created based upon a
A message with Babyl-specific behaviors. Parameter *message* has the same A message with Babyl-specific behaviors. Parameter *message* has the same
meaning as with the :class:`Message` constructor. meaning as with the :class:`Message` constructor.
Certain message labels, called :dfn:`attributes`, are defined by convention to Certain message labels, called :dfn:`attributes`, are defined by convention
have special meanings. The attributes are as follows: to have special meanings. The attributes are as follows:
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| Label | Explanation | | Label | Explanation |
+===========+==========================================+ +===========+==========================================+
| unseen | Not read, but previously detected by MUA | | unseen | Not read, but previously detected by MUA |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| deleted | Marked for subsequent deletion | | deleted | Marked for subsequent deletion |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| filed | Copied to another file or mailbox | | filed | Copied to another file or mailbox |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| answered | Replied to | | answered | Replied to |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| forwarded | Forwarded | | forwarded | Forwarded |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| edited | Modified by the user | | edited | Modified by the user |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
| resent | Resent | | resent | Resent |
+-----------+------------------------------------------+ +-----------+------------------------------------------+
By default, Rmail displays only visible headers. The :class:`BabylMessage` By default, Rmail displays only visible headers. The :class:`BabylMessage`
class, though, uses the original headers because they are more complete. Visible class, though, uses the original headers because they are more
headers may be accessed explicitly if desired. complete. Visible headers may be accessed explicitly if desired.
:class:`BabylMessage` instances offer the following methods: :class:`BabylMessage` instances offer the following methods:
.. method:: BabylMessage.get_labels() .. method:: get_labels()
Return a list of labels on the message. Return a list of labels on the message.
.. method:: BabylMessage.set_labels(labels) .. method:: set_labels(labels)
Set the list of labels on the message to *labels*. Set the list of labels on the message to *labels*.
.. method:: BabylMessage.add_label(label) .. method:: add_label(label)
Add *label* to the list of labels on the message. Add *label* to the list of labels on the message.
.. method:: BabylMessage.remove_label(label) .. method:: remove_label(label)
Remove *label* from the list of labels on the message. Remove *label* from the list of labels on the message.
.. method:: BabylMessage.get_visible() .. method:: get_visible()
Return an :class:`Message` instance whose headers are the message's visible Return an :class:`Message` instance whose headers are the message's
headers and whose body is empty. visible headers and whose body is empty.
.. method:: BabylMessage.set_visible(visible) .. method:: set_visible(visible)
Set the message's visible headers to be the same as the headers in *message*. Set the message's visible headers to be the same as the headers in
Parameter *visible* should be a :class:`Message` instance, an *message*. Parameter *visible* should be a :class:`Message` instance, an
:class:`email.Message.Message` instance, a string, or a file-like object (which :class:`email.Message.Message` instance, a string, or a file-like object
should be open in text mode). (which should be open in text mode).
.. method:: BabylMessage.update_visible() .. method:: update_visible()
When a :class:`BabylMessage` instance's original headers are modified, the When a :class:`BabylMessage` instance's original headers are modified, the
visible headers are not automatically modified to correspond. This method visible headers are not automatically modified to correspond. This method
updates the visible headers as follows: each visible header with a corresponding updates the visible headers as follows: each visible header with a
original header is set to the value of the original header, each visible header corresponding original header is set to the value of the original header,
without a corresponding original header is removed, and any of each visible header without a corresponding original header is removed,
:mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`,
:mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are present :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are
in the original headers but not the visible headers are added to the visible present in the original headers but not the visible headers are added to
headers. the visible headers.
When a :class:`BabylMessage` instance is created based upon a When a :class:`BabylMessage` instance is created based upon a
:class:`MaildirMessage` instance, the following conversions take place: :class:`MaildirMessage` instance, the following conversions take place:
...@@ -1299,77 +1320,80 @@ When a :class:`BabylMessage` instance is created based upon an ...@@ -1299,77 +1320,80 @@ When a :class:`BabylMessage` instance is created based upon an
A message with MMDF-specific behaviors. Parameter *message* has the same meaning A message with MMDF-specific behaviors. Parameter *message* has the same meaning
as with the :class:`Message` constructor. as with the :class:`Message` constructor.
As with message in an mbox mailbox, MMDF messages are stored with the sender's As with message in an mbox mailbox, MMDF messages are stored with the
address and the delivery date in an initial line beginning with "From ". sender's address and the delivery date in an initial line beginning with
Likewise, flags that indicate the state of the message are typically stored in "From ". Likewise, flags that indicate the state of the message are
:mailheader:`Status` and :mailheader:`X-Status` headers. typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers.
Conventional flags for MMDF messages are identical to those of mbox message and Conventional flags for MMDF messages are identical to those of mbox message
are as follows: and are as follows:
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| Flag | Meaning | Explanation | | Flag | Meaning | Explanation |
+======+==========+================================+ +======+==========+================================+
| R | Read | Read | | R | Read | Read |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| O | Old | Previously detected by MUA | | O | Old | Previously detected by MUA |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| D | Deleted | Marked for subsequent deletion | | D | Deleted | Marked for subsequent deletion |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| F | Flagged | Marked as important | | F | Flagged | Marked as important |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
| A | Answered | Replied to | | A | Answered | Replied to |
+------+----------+--------------------------------+ +------+----------+--------------------------------+
The "R" and "O" flags are stored in the :mailheader:`Status` header, and the The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
flags and headers typically appear in the order mentioned. flags and headers typically appear in the order mentioned.
:class:`MMDFMessage` instances offer the following methods, which are identical :class:`MMDFMessage` instances offer the following methods, which are
to those offered by :class:`mboxMessage`: identical to those offered by :class:`mboxMessage`:
.. method:: MMDFMessage.get_from() .. method:: get_from()
Return a string representing the "From " line that marks the start of the Return a string representing the "From " line that marks the start of the
message in an mbox mailbox. The leading "From " and the trailing newline are message in an mbox mailbox. The leading "From " and the trailing newline
excluded. are excluded.
.. method:: MMDFMessage.set_from(from_[, time_=None]) .. method:: set_from(from_[, time_=None])
Set the "From " line to *from_*, which should be specified without a leading Set the "From " line to *from_*, which should be specified without a
"From " or trailing newline. For convenience, *time_* may be specified and will leading "From " or trailing newline. For convenience, *time_* may be
be formatted appropriately and appended to *from_*. If *time_* is specified, it specified and will be formatted appropriately and appended to *from_*. If
should be a :class:`struct_time` instance, a tuple suitable for passing to *time_* is specified, it should be a :class:`struct_time` instance, a
:meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
:meth:`time.gmtime`).
.. method:: MMDFMessage.get_flags() .. method:: get_flags()
Return a string specifying the flags that are currently set. If the message Return a string specifying the flags that are currently set. If the
complies with the conventional format, the result is the concatenation in the message complies with the conventional format, the result is the
following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, concatenation in the following order of zero or one occurrence of each of
``'F'``, and ``'A'``. ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
.. method:: MMDFMessage.set_flags(flags) .. method:: set_flags(flags)
Set the flags specified by *flags* and unset all others. Parameter *flags* Set the flags specified by *flags* and unset all others. Parameter *flags*
should be the concatenation in any order of zero or more occurrences of each of should be the concatenation in any order of zero or more occurrences of
``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.
.. method:: MMDFMessage.add_flag(flag) .. method:: add_flag(flag)
Set the flag(s) specified by *flag* without changing other flags. To add more Set the flag(s) specified by *flag* without changing other flags. To add
than one flag at a time, *flag* may be a string of more than one character. more than one flag at a time, *flag* may be a string of more than one
character.
.. method:: MMDFMessage.remove_flag(flag) .. method:: remove_flag(flag)
Unset the flag(s) specified by *flag* without changing other flags. To remove Unset the flag(s) specified by *flag* without changing other flags. To
more than one flag at a time, *flag* maybe a string of more than one character. remove more than one flag at a time, *flag* maybe a string of more than
one character.
When an :class:`MMDFMessage` instance is created based upon a When an :class:`MMDFMessage` instance is created based upon a
:class:`MaildirMessage` instance, a "From " line is generated based upon the :class:`MaildirMessage` instance, a "From " line is generated based upon the
...@@ -1445,25 +1469,25 @@ Exceptions ...@@ -1445,25 +1469,25 @@ Exceptions
The following exception classes are defined in the :mod:`mailbox` module: The following exception classes are defined in the :mod:`mailbox` module:
.. class:: Error() .. exception:: Error()
The based class for all other module-specific exceptions. The based class for all other module-specific exceptions.
.. class:: NoSuchMailboxError() .. exception:: NoSuchMailboxError()
Raised when a mailbox is expected but is not found, such as when instantiating a Raised when a mailbox is expected but is not found, such as when instantiating a
:class:`Mailbox` subclass with a path that does not exist (and with the *create* :class:`Mailbox` subclass with a path that does not exist (and with the *create*
parameter set to ``False``), or when opening a folder that does not exist. parameter set to ``False``), or when opening a folder that does not exist.
.. class:: NotEmptyErrorError() .. exception:: NotEmptyErrorError()
Raised when a mailbox is not empty but is expected to be, such as when deleting Raised when a mailbox is not empty but is expected to be, such as when deleting
a folder that contains messages. a folder that contains messages.
.. class:: ExternalClashError() .. exception:: ExternalClashError()
Raised when some mailbox-related condition beyond the control of the program Raised when some mailbox-related condition beyond the control of the program
causes it to be unable to proceed, such as when failing to acquire a lock that causes it to be unable to proceed, such as when failing to acquire a lock that
...@@ -1471,7 +1495,7 @@ The following exception classes are defined in the :mod:`mailbox` module: ...@@ -1471,7 +1495,7 @@ The following exception classes are defined in the :mod:`mailbox` module:
already exists. already exists.
.. class:: FormatError() .. exception:: FormatError()
Raised when the data in a file cannot be parsed, such as when an :class:`MH` Raised when the data in a file cannot be parsed, such as when an :class:`MH`
instance attempts to read a corrupted :file:`.mh_sequences` file. instance attempts to read a corrupted :file:`.mh_sequences` file.
......
...@@ -131,16 +131,16 @@ To map anonymous memory, -1 should be passed as the fileno along with the length ...@@ -131,16 +131,16 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
map.close() map.close()
Memory-mapped file objects support the following methods: Memory-mapped file objects support the following methods:
.. method:: mmap.close() .. method:: close()
Close the file. Subsequent calls to other methods of the object will Close the file. Subsequent calls to other methods of the object will
result in an exception being raised. result in an exception being raised.
.. method:: mmap.find(string[, start[, end]]) .. method:: find(string[, start[, end]])
Returns the lowest index in the object where the substring *string* is Returns the lowest index in the object where the substring *string* is
found, such that *string* is contained in the range [*start*, *end*]. found, such that *string* is contained in the range [*start*, *end*].
...@@ -148,7 +148,7 @@ Memory-mapped file objects support the following methods: ...@@ -148,7 +148,7 @@ Memory-mapped file objects support the following methods:
Returns ``-1`` on failure. Returns ``-1`` on failure.
.. method:: mmap.flush([offset, size]) .. method:: flush([offset, size])
Flushes changes made to the in-memory copy of a file back to disk. Without Flushes changes made to the in-memory copy of a file back to disk. Without
use of this call there is no guarantee that changes are written back before use of this call there is no guarantee that changes are written back before
...@@ -163,40 +163,40 @@ Memory-mapped file objects support the following methods: ...@@ -163,40 +163,40 @@ Memory-mapped file objects support the following methods:
exception is raised when the call failed. exception is raised when the call failed.
.. method:: mmap.move(dest, src, count) .. method:: move(dest, src, count)
Copy the *count* bytes starting at offset *src* to the destination index Copy the *count* bytes starting at offset *src* to the destination index
*dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
move will throw a :exc:`TypeError` exception. move will throw a :exc:`TypeError` exception.
.. method:: mmap.read(num) .. method:: read(num)
Return a string containing up to *num* bytes starting from the current file Return a string containing up to *num* bytes starting from the current
position; the file position is updated to point after the bytes that were file position; the file position is updated to point after the bytes that
returned. were returned.
.. method:: mmap.read_byte() .. method:: read_byte()
Returns a string of length 1 containing the character at the current file Returns a string of length 1 containing the character at the current file
position, and advances the file position by 1. position, and advances the file position by 1.
.. method:: mmap.readline() .. method:: readline()
Returns a single line, starting at the current file position and up to the Returns a single line, starting at the current file position and up to the
next newline. next newline.
.. method:: mmap.resize(newsize) .. method:: resize(newsize)
Resizes the map and the underlying file, if any. If the mmap was created Resizes the map and the underlying file, if any. If the mmap was created
with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
throw a :exc:`TypeError` exception. throw a :exc:`TypeError` exception.
.. method:: mmap.rfind(string[, start[, end]]) .. method:: rfind(string[, start[, end]])
Returns the highest index in the object where the substring *string* is Returns the highest index in the object where the substring *string* is
found, such that *string* is contained in the range [*start*, *end*]. found, such that *string* is contained in the range [*start*, *end*].
...@@ -204,34 +204,34 @@ Memory-mapped file objects support the following methods: ...@@ -204,34 +204,34 @@ Memory-mapped file objects support the following methods:
Returns ``-1`` on failure. Returns ``-1`` on failure.
.. method:: mmap.seek(pos[, whence]) .. method:: seek(pos[, whence])
Set the file's current position. *whence* argument is optional and Set the file's current position. *whence* argument is optional and
defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
.. method:: mmap.size() .. method:: size()
Return the length of the file, which can be larger than the size of the Return the length of the file, which can be larger than the size of the
memory-mapped area. memory-mapped area.
.. method:: mmap.tell() .. method:: tell()
Returns the current position of the file pointer. Returns the current position of the file pointer.
.. method:: mmap.write(string) .. method:: write(string)
Write the bytes in *string* into memory at the current position of the file Write the bytes in *string* into memory at the current position of the
pointer; the file position is updated to point after the bytes that were file pointer; the file position is updated to point after the bytes that
written. If the mmap was created with :const:`ACCESS_READ`, then writing to were written. If the mmap was created with :const:`ACCESS_READ`, then
it will throw a :exc:`TypeError` exception. writing to it will throw a :exc:`TypeError` exception.
.. method:: mmap.write_byte(byte) .. method:: write_byte(byte)
Write the single-character string *byte* into memory at the current Write the single-character string *byte* into memory at the current
position of the file pointer; the file position is advanced by ``1``. If position of the file pointer; the file position is advanced by ``1``. If
......
...@@ -38,19 +38,21 @@ report of the imported modules will be printed. ...@@ -38,19 +38,21 @@ report of the imported modules will be printed.
be replaced in module paths. be replaced in module paths.
.. method:: ModuleFinder.report() .. method:: report()
Print a report to standard output that lists the modules imported by the script Print a report to standard output that lists the modules imported by the
and their paths, as well as modules that are missing or seem to be missing. script and their paths, as well as modules that are missing or seem to be
missing.
.. method:: run_script(pathname)
.. method:: ModuleFinder.run_script(pathname) Analyze the contents of the *pathname* file, which must contain Python
code.
Analyze the contents of the *pathname* file, which must contain Python code. .. attribute:: modules
.. attribute:: ModuleFinder.modules A dictionary mapping module names to modules. See
:ref:`modulefinder-example`
A dictionary mapping module names to modules. See :ref:`modulefinder-example`
.. _modulefinder-example: .. _modulefinder-example:
......
...@@ -318,16 +318,17 @@ CAB Objects ...@@ -318,16 +318,17 @@ CAB Objects
*name* is the name of the CAB file in the MSI file. *name* is the name of the CAB file in the MSI file.
.. method:: CAB.append(full, file, logical) .. method:: append(full, file, logical)
Add the file with the pathname *full* to the CAB file, under the name *logical*. Add the file with the pathname *full* to the CAB file, under the name
If there is already a file named *logical*, a new file name is created. *logical*. If there is already a file named *logical*, a new file name is
created.
Return the index of the file in the CAB file, and the new name of the file Return the index of the file in the CAB file, and the new name of the file
inside the CAB file. inside the CAB file.
.. method:: CAB.commit(database) .. method:: commit(database)
Generate a CAB file, add it as a stream to the MSI file, put it into the Generate a CAB file, add it as a stream to the MSI file, put it into the
``Media`` table, and remove the generated file from the disk. ``Media`` table, and remove the generated file from the disk.
...@@ -351,31 +352,31 @@ Directory Objects ...@@ -351,31 +352,31 @@ Directory Objects
the default flags that new components get. the default flags that new components get.
.. method:: Directory.start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) .. method:: start_component([component[, feature[, flags[, keyfile[, uuid]]]]])
Add an entry to the Component table, and make this component the current Add an entry to the Component table, and make this component the current
component for this directory. If no component name is given, the directory name component for this directory. If no component name is given, the directory
is used. If no *feature* is given, the current feature is used. If no *flags* name is used. If no *feature* is given, the current feature is used. If no
are given, the directory's default flags are used. If no *keyfile* is given, the *flags* are given, the directory's default flags are used. If no *keyfile*
KeyPath is left null in the Component table. is given, the KeyPath is left null in the Component table.
.. method:: Directory.add_file(file[, src[, version[, language]]]) .. method:: add_file(file[, src[, version[, language]]])
Add a file to the current component of the directory, starting a new one if Add a file to the current component of the directory, starting a new one
there is no current component. By default, the file name in the source and the if there is no current component. By default, the file name in the source
file table will be identical. If the *src* file is specified, it is interpreted and the file table will be identical. If the *src* file is specified, it
relative to the current directory. Optionally, a *version* and a *language* can is interpreted relative to the current directory. Optionally, a *version*
be specified for the entry in the File table. and a *language* can be specified for the entry in the File table.
.. method:: Directory.glob(pattern[, exclude]) .. method:: glob(pattern[, exclude])
Add a list of files to the current component as specified in the glob pattern. Add a list of files to the current component as specified in the glob
Individual files can be excluded in the *exclude* list. pattern. Individual files can be excluded in the *exclude* list.
.. method:: Directory.remove_pyc() .. method:: remove_pyc()
Remove ``.pyc``/``.pyo`` files on uninstall. Remove ``.pyc``/``.pyo`` files on uninstall.
...@@ -401,7 +402,7 @@ Features ...@@ -401,7 +402,7 @@ Features
:class:`Directory`. :class:`Directory`.
.. method:: Feature.set_current() .. method:: set_current()
Make this feature the current feature of :mod:`msilib`. New components are Make this feature the current feature of :mod:`msilib`. New components are
automatically added to the default feature, unless a feature is explicitly automatically added to the default feature, unless a feature is explicitly
...@@ -428,17 +429,17 @@ to create MSI files with a user-interface for installing Python packages. ...@@ -428,17 +429,17 @@ to create MSI files with a user-interface for installing Python packages.
belongs to, and *name* is the control's name. belongs to, and *name* is the control's name.
.. method:: Control.event(event, argument[, condition=1[, ordering]]) .. method:: event(event, argument[, condition=1[, ordering]])
Make an entry into the ``ControlEvent`` table for this control. Make an entry into the ``ControlEvent`` table for this control.
.. method:: Control.mapping(event, attribute) .. method:: mapping(event, attribute)
Make an entry into the ``EventMapping`` table for this control. Make an entry into the ``EventMapping`` table for this control.
.. method:: Control.condition(action, condition) .. method:: condition(action, condition)
Make an entry into the ``ControlCondition`` table for this control. Make an entry into the ``ControlCondition`` table for this control.
...@@ -449,11 +450,11 @@ to create MSI files with a user-interface for installing Python packages. ...@@ -449,11 +450,11 @@ to create MSI files with a user-interface for installing Python packages.
that gets set when a radio button is selected. that gets set when a radio button is selected.
.. method:: RadioButtonGroup.add(name, x, y, width, height, text [, value]) .. method:: add(name, x, y, width, height, text [, value])
Add a radio button named *name* to the group, at the coordinates *x*, *y*, Add a radio button named *name* to the group, at the coordinates *x*, *y*,
*width*, *height*, and with the label *text*. If *value* is omitted, it defaults *width*, *height*, and with the label *text*. If *value* is omitted, it
to *name*. defaults to *name*.
.. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel) .. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel)
...@@ -463,40 +464,41 @@ to create MSI files with a user-interface for installing Python packages. ...@@ -463,40 +464,41 @@ to create MSI files with a user-interface for installing Python packages.
default, and cancel controls. default, and cancel controls.
.. method:: Dialog.control(name, type, x, y, width, height, attributes, property, text, control_next, help) .. method:: control(name, type, x, y, width, height, attributes, property, text, control_next, help)
Return a new :class:`Control` object. An entry in the ``Control`` table is made Return a new :class:`Control` object. An entry in the ``Control`` table is
with the specified parameters. made with the specified parameters.
This is a generic method; for specific types, specialized methods are provided. This is a generic method; for specific types, specialized methods are
provided.
.. method:: Dialog.text(name, x, y, width, height, attributes, text) .. method:: text(name, x, y, width, height, attributes, text)
Add and return a ``Text`` control. Add and return a ``Text`` control.
.. method:: Dialog.bitmap(name, x, y, width, height, text) .. method:: bitmap(name, x, y, width, height, text)
Add and return a ``Bitmap`` control. Add and return a ``Bitmap`` control.
.. method:: Dialog.line(name, x, y, width, height) .. method:: line(name, x, y, width, height)
Add and return a ``Line`` control. Add and return a ``Line`` control.
.. method:: Dialog.pushbutton(name, x, y, width, height, attributes, text, next_control) .. method:: pushbutton(name, x, y, width, height, attributes, text, next_control)
Add and return a ``PushButton`` control. Add and return a ``PushButton`` control.
.. method:: Dialog.radiogroup(name, x, y, width, height, attributes, property, text, next_control) .. method:: radiogroup(name, x, y, width, height, attributes, property, text, next_control)
Add and return a ``RadioButtonGroup`` control. Add and return a ``RadioButtonGroup`` control.
.. method:: Dialog.checkbox(name, x, y, width, height, attributes, property, text, next_control) .. method:: checkbox(name, x, y, width, height, attributes, property, text, next_control)
Add and return a ``CheckBox`` control. Add and return a ``CheckBox`` control.
......
...@@ -27,18 +27,18 @@ The numeric tower ...@@ -27,18 +27,18 @@ The numeric tower
``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
except ``-`` and ``!=`` are abstract. except ``-`` and ``!=`` are abstract.
.. attribute:: Complex.real .. attribute:: real
Abstract. Retrieves the :class:`Real` component of this number. Abstract. Retrieves the :class:`Real` component of this number.
.. attribute:: Complex.imag .. attribute:: imag
Abstract. Retrieves the :class:`Real` component of this number. Abstract. Retrieves the :class:`Real` component of this number.
.. method:: Complex.conjugate() .. method:: conjugate()
Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() == Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate()
(1-3j)``. == (1-3j)``.
.. class:: Real .. class:: Real
...@@ -60,11 +60,11 @@ The numeric tower ...@@ -60,11 +60,11 @@ The numeric tower
should be in lowest terms. With these, it provides a default for should be in lowest terms. With these, it provides a default for
:func:`float`. :func:`float`.
.. attribute:: Rational.numerator .. attribute:: numerator
Abstract. Abstract.
.. attribute:: Rational.denominator .. attribute:: denominator
Abstract. Abstract.
......
...@@ -245,17 +245,17 @@ The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and ...@@ -245,17 +245,17 @@ The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
It can thus be an open file object, a :mod:`StringIO` object, or any other It can thus be an open file object, a :mod:`StringIO` object, or any other
custom object that meets this interface. custom object that meets this interface.
:class:`Pickler` objects define one (or two) public methods: :class:`Pickler` objects define one (or two) public methods:
.. method:: Pickler.dump(obj) .. method:: dump(obj)
Write a pickled representation of *obj* to the open file object given in the Write a pickled representation of *obj* to the open file object given in the
constructor. Either the binary or ASCII format will be used, depending on the constructor. Either the binary or ASCII format will be used, depending on the
value of the *protocol* argument passed to the constructor. value of the *protocol* argument passed to the constructor.
.. method:: Pickler.clear_memo() .. method:: clear_memo()
Clears the pickler's "memo". The memo is the data structure that remembers Clears the pickler's "memo". The memo is the data structure that remembers
which objects the pickler has already seen, so that shared or recursive objects which objects the pickler has already seen, so that shared or recursive objects
...@@ -296,23 +296,24 @@ instance. If the same object is pickled by multiple :meth:`dump` calls, the ...@@ -296,23 +296,24 @@ instance. If the same object is pickled by multiple :meth:`dump` calls, the
reading, a :mod:`StringIO` object, or any other custom object that meets this reading, a :mod:`StringIO` object, or any other custom object that meets this
interface. interface.
:class:`Unpickler` objects have one (or two) public methods: :class:`Unpickler` objects have one (or two) public methods:
.. method:: Unpickler.load() .. method:: load()
Read a pickled object representation from the open file object given in the Read a pickled object representation from the open file object given in
constructor, and return the reconstituted object hierarchy specified therein. the constructor, and return the reconstituted object hierarchy specified
therein.
This method automatically determines whether the data stream was written in This method automatically determines whether the data stream was written
binary mode or not. in binary mode or not.
.. method:: Unpickler.noload() .. method:: noload()
This is just like :meth:`load` except that it doesn't actually create any This is just like :meth:`load` except that it doesn't actually create any
objects. This is useful primarily for finding what's called "persistent ids" objects. This is useful primarily for finding what's called "persistent
that may be referenced in a pickle data stream. See section ids" that may be referenced in a pickle data stream. See section
:ref:`pickle-protocol` below for more details. :ref:`pickle-protocol` below for more details.
**Note:** the :meth:`noload` method is currently only available on **Note:** the :meth:`noload` method is currently only available on
......
...@@ -25,35 +25,35 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html. ...@@ -25,35 +25,35 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
single :file:`robots.txt` file. single :file:`robots.txt` file.
.. method:: RobotFileParser.set_url(url) .. method:: set_url(url)
Sets the URL referring to a :file:`robots.txt` file. Sets the URL referring to a :file:`robots.txt` file.
.. method:: RobotFileParser.read() .. method:: read()
Reads the :file:`robots.txt` URL and feeds it to the parser. Reads the :file:`robots.txt` URL and feeds it to the parser.
.. method:: RobotFileParser.parse(lines) .. method:: parse(lines)
Parses the lines argument. Parses the lines argument.
.. method:: RobotFileParser.can_fetch(useragent, url) .. method:: can_fetch(useragent, url)
Returns ``True`` if the *useragent* is allowed to fetch the *url* according to Returns ``True`` if the *useragent* is allowed to fetch the *url* according to
the rules contained in the parsed :file:`robots.txt` file. the rules contained in the parsed :file:`robots.txt` file.
.. method:: RobotFileParser.mtime() .. method:: mtime()
Returns the time the ``robots.txt`` file was last fetched. This is useful for Returns the time the ``robots.txt`` file was last fetched. This is useful for
long-running web spiders that need to check for new ``robots.txt`` files long-running web spiders that need to check for new ``robots.txt`` files
periodically. periodically.
.. method:: RobotFileParser.modified() .. method:: modified()
Sets the time the ``robots.txt`` file was last fetched to the current time. Sets the time the ``robots.txt`` file was last fetched to the current time.
......
...@@ -23,55 +23,57 @@ The :mod:`SimpleHTTPServer` module defines the following class: ...@@ -23,55 +23,57 @@ The :mod:`SimpleHTTPServer` module defines the following class:
:class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the :class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the
:func:`do_GET` and :func:`do_HEAD` functions. :func:`do_GET` and :func:`do_HEAD` functions.
The :class:`SimpleHTTPRequestHandler` defines the following member variables: The :class:`SimpleHTTPRequestHandler` defines the following member variables:
.. attribute:: SimpleHTTPRequestHandler.server_version .. attribute:: server_version
This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is defined This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
in the module. defined in the module.
.. attribute:: SimpleHTTPRequestHandler.extensions_map .. attribute:: extensions_map
A dictionary mapping suffixes into MIME types. The default is signified by an A dictionary mapping suffixes into MIME types. The default is signified by
empty string, and is considered to be ``application/octet-stream``. The mapping an empty string, and is considered to be ``application/octet-stream``. The
is used case-insensitively, and so should contain only lower-cased keys. mapping is used case-insensitively, and so should contain only lower-cased
keys.
The :class:`SimpleHTTPRequestHandler` defines the following methods: The :class:`SimpleHTTPRequestHandler` defines the following methods:
.. method:: SimpleHTTPRequestHandler.do_HEAD() .. method:: do_HEAD()
This method serves the ``'HEAD'`` request type: it sends the headers it would This method serves the ``'HEAD'`` request type: it sends the headers it
send for the equivalent ``GET`` request. See the :meth:`do_GET` method for a would send for the equivalent ``GET`` request. See the :meth:`do_GET`
more complete explanation of the possible headers. method for a more complete explanation of the possible headers.
.. method:: SimpleHTTPRequestHandler.do_GET() .. method:: do_GET()
The request is mapped to a local file by interpreting the request as a path The request is mapped to a local file by interpreting the request as a
relative to the current working directory. path relative to the current working directory.
If the request was mapped to a directory, the directory is checked for a file If the request was mapped to a directory, the directory is checked for a
named ``index.html`` or ``index.htm`` (in that order). If found, the file's file named ``index.html`` or ``index.htm`` (in that order). If found, the
contents are returned; otherwise a directory listing is generated by calling the file's contents are returned; otherwise a directory listing is generated
:meth:`list_directory` method. This method uses :func:`os.listdir` to scan the by calling the :meth:`list_directory` method. This method uses
directory, and returns a ``404`` error response if the :func:`listdir` fails. :func:`os.listdir` to scan the directory, and returns a ``404`` error
response if the :func:`listdir` fails.
If the request was mapped to a file, it is opened and the contents are returned. If the request was mapped to a file, it is opened and the contents are
Any :exc:`IOError` exception in opening the requested file is mapped to a returned. Any :exc:`IOError` exception in opening the requested file is
``404``, ``'File not found'`` error. Otherwise, the content type is guessed by mapped to a ``404``, ``'File not found'`` error. Otherwise, the content
calling the :meth:`guess_type` method, which in turn uses the *extensions_map* type is guessed by calling the :meth:`guess_type` method, which in turn
variable. uses the *extensions_map* variable.
A ``'Content-type:'`` header with the guessed content type is output, followed A ``'Content-type:'`` header with the guessed content type is output,
by a ``'Content-Length:'`` header with the file's size and a followed by a ``'Content-Length:'`` header with the file's size and a
``'Last-Modified:'`` header with the file's modification time. ``'Last-Modified:'`` header with the file's modification time.
Then follows a blank line signifying the end of the headers, and then the Then follows a blank line signifying the end of the headers, and then the
contents of the file are output. If the file's MIME type starts with ``text/`` contents of the file are output. If the file's MIME type starts with
the file is opened in text mode; otherwise binary mode is used. ``text/`` the file is opened in text mode; otherwise binary mode is used.
For example usage, see the implementation of the :func:`test` function. For example usage, see the implementation of the :func:`test` function.
......
...@@ -27,14 +27,15 @@ SMTPServer Objects ...@@ -27,14 +27,15 @@ SMTPServer Objects
:mod:`asyncore`'s event loop on instantiation. :mod:`asyncore`'s event loop on instantiation.
.. method:: SMTPServer.process_message(peer, mailfrom, rcpttos, data) .. method:: process_message(peer, mailfrom, rcpttos, data)
Raise :exc:`NotImplementedError` exception. Override this in subclasses to do Raise :exc:`NotImplementedError` exception. Override this in subclasses to
something useful with this message. Whatever was passed in the constructor as do something useful with this message. Whatever was passed in the
*remoteaddr* will be available as the :attr:`_remoteaddr` attribute. *peer* is constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
the remote host's address, *mailfrom* is the envelope originator, *rcpttos* are attribute. *peer* is the remote host's address, *mailfrom* is the envelope
the envelope recipients and *data* is a string containing the contents of the originator, *rcpttos* are the envelope recipients and *data* is a string
e-mail (which should be in :rfc:`2822` format). containing the contents of the e-mail (which should be in :rfc:`2822`
format).
DebuggingServer Objects DebuggingServer Objects
......
...@@ -452,29 +452,29 @@ these rules. The methods of :class:`Template` are: ...@@ -452,29 +452,29 @@ these rules. The methods of :class:`Template` are:
The constructor takes a single argument which is the template string. The constructor takes a single argument which is the template string.
.. method:: Template.substitute(mapping[, **kws]) .. method:: substitute(mapping[, **kws])
Performs the template substitution, returning a new string. *mapping* is any Performs the template substitution, returning a new string. *mapping* is
dictionary-like object with keys that match the placeholders in the template. any dictionary-like object with keys that match the placeholders in the
Alternatively, you can provide keyword arguments, where the keywords are the template. Alternatively, you can provide keyword arguments, where the
placeholders. When both *mapping* and *kws* are given and there are duplicates, keywords are the placeholders. When both *mapping* and *kws* are given
the placeholders from *kws* take precedence. and there are duplicates, the placeholders from *kws* take precedence.
.. method:: Template.safe_substitute(mapping[, **kws]) .. method:: safe_substitute(mapping[, **kws])
Like :meth:`substitute`, except that if placeholders are missing from *mapping* Like :meth:`substitute`, except that if placeholders are missing from
and *kws*, instead of raising a :exc:`KeyError` exception, the original *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
placeholder will appear in the resulting string intact. Also, unlike with original placeholder will appear in the resulting string intact. Also,
:meth:`substitute`, any other appearances of the ``$`` will simply return ``$`` unlike with :meth:`substitute`, any other appearances of the ``$`` will
instead of raising :exc:`ValueError`. simply return ``$`` instead of raising :exc:`ValueError`.
While other exceptions may still occur, this method is called "safe" because While other exceptions may still occur, this method is called "safe"
substitutions always tries to return a usable string instead of raising an because substitutions always tries to return a usable string instead of
exception. In another sense, :meth:`safe_substitute` may be anything other than raising an exception. In another sense, :meth:`safe_substitute` may be
safe, since it will silently ignore malformed templates containing dangling anything other than safe, since it will silently ignore malformed
delimiters, unmatched braces, or placeholders that are not valid Python templates containing dangling delimiters, unmatched braces, or
identifiers. placeholders that are not valid Python identifiers.
:class:`Template` instances also provide one public data attribute: :class:`Template` instances also provide one public data attribute:
......
...@@ -242,36 +242,36 @@ The :mod:`struct` module also defines the following type: ...@@ -242,36 +242,36 @@ The :mod:`struct` module also defines the following type:
since the format string only needs to be compiled once. since the format string only needs to be compiled once.
Compiled Struct objects support the following methods and attributes: Compiled Struct objects support the following methods and attributes:
.. method:: Struct.pack(v1, v2, ...) .. method:: pack(v1, v2, ...)
Identical to the :func:`pack` function, using the compiled format. Identical to the :func:`pack` function, using the compiled format.
(``len(result)`` will equal :attr:`self.size`.) (``len(result)`` will equal :attr:`self.size`.)
.. method:: Struct.pack_into(buffer, offset, v1, v2, ...) .. method:: pack_into(buffer, offset, v1, v2, ...)
Identical to the :func:`pack_into` function, using the compiled format. Identical to the :func:`pack_into` function, using the compiled format.
.. method:: Struct.unpack(string) .. method:: unpack(string)
Identical to the :func:`unpack` function, using the compiled format. Identical to the :func:`unpack` function, using the compiled format.
(``len(string)`` must equal :attr:`self.size`). (``len(string)`` must equal :attr:`self.size`).
.. method:: Struct.unpack_from(buffer[, offset=0]) .. method:: unpack_from(buffer[, offset=0])
Identical to the :func:`unpack_from` function, using the compiled format. Identical to the :func:`unpack_from` function, using the compiled format.
(``len(buffer[offset:])`` must be at least :attr:`self.size`). (``len(buffer[offset:])`` must be at least :attr:`self.size`).
.. attribute:: Struct.format .. attribute:: format
The format string used to construct this Struct object. The format string used to construct this Struct object.
.. attribute:: Struct.size .. attribute:: size
The calculated size of the struct (and hence of the string) corresponding The calculated size of the struct (and hence of the string) corresponding
to :attr:`format`. to :attr:`format`.
......
...@@ -85,25 +85,25 @@ indentation from strings that have unwanted whitespace to the left of the text. ...@@ -85,25 +85,25 @@ indentation from strings that have unwanted whitespace to the left of the text.
change any of its options through direct assignment to instance attributes change any of its options through direct assignment to instance attributes
between uses. between uses.
The :class:`TextWrapper` instance attributes (and keyword arguments to the The :class:`TextWrapper` instance attributes (and keyword arguments to the
constructor) are as follows: constructor) are as follows:
.. attribute:: TextWrapper.width .. attribute:: width
(default: ``70``) The maximum length of wrapped lines. As long as there are no (default: ``70``) The maximum length of wrapped lines. As long as there
individual words in the input text longer than :attr:`width`, are no individual words in the input text longer than :attr:`width`,
:class:`TextWrapper` guarantees that no output line will be longer than :class:`TextWrapper` guarantees that no output line will be longer than
:attr:`width` characters. :attr:`width` characters.
.. attribute:: TextWrapper.expand_tabs .. attribute:: expand_tabs
(default: ``True``) If true, then all tab characters in *text* will be expanded (default: ``True``) If true, then all tab characters in *text* will be
to spaces using the :meth:`expandtabs` method of *text*. expanded to spaces using the :meth:`expandtabs` method of *text*.
.. attribute:: TextWrapper.replace_whitespace .. attribute:: replace_whitespace
(default: ``True``) If true, each whitespace character (as defined by (default: ``True``) If true, each whitespace character (as defined by
``string.whitespace``) remaining after tab expansion will be replaced by a ``string.whitespace``) remaining after tab expansion will be replaced by a
...@@ -111,40 +111,41 @@ constructor) are as follows: ...@@ -111,40 +111,41 @@ constructor) are as follows:
.. note:: .. note::
If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, each tab If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true,
character will be replaced by a single space, which is *not* the same as tab each tab character will be replaced by a single space, which is *not*
expansion. the same as tab expansion.
.. attribute:: TextWrapper.drop_whitespace .. attribute:: drop_whitespace
(default: ``True``) If true, whitespace that, after wrapping, happens to end up (default: ``True``) If true, whitespace that, after wrapping, happens to
at the beginning or end of a line is dropped (leading whitespace in the first end up at the beginning or end of a line is dropped (leading whitespace in
line is always preserved, though). the first line is always preserved, though).
.. attribute:: TextWrapper.initial_indent .. attribute:: initial_indent
(default: ``''``) String that will be prepended to the first line of wrapped (default: ``''``) String that will be prepended to the first line of
output. Counts towards the length of the first line. wrapped output. Counts towards the length of the first line.
.. attribute:: TextWrapper.subsequent_indent .. attribute:: subsequent_indent
(default: ``''``) String that will be prepended to all lines of wrapped output (default: ``''``) String that will be prepended to all lines of wrapped
except the first. Counts towards the length of each line except the first. output except the first. Counts towards the length of each line except
the first.
.. attribute:: TextWrapper.fix_sentence_endings .. attribute:: fix_sentence_endings
(default: ``False``) If true, :class:`TextWrapper` attempts to detect sentence (default: ``False``) If true, :class:`TextWrapper` attempts to detect
endings and ensure that sentences are always separated by exactly two spaces. sentence endings and ensure that sentences are always separated by exactly
This is generally desired for text in a monospaced font. However, the sentence two spaces. This is generally desired for text in a monospaced font.
detection algorithm is imperfect: it assumes that a sentence ending consists of However, the sentence detection algorithm is imperfect: it assumes that a
a lowercase letter followed by one of ``'.'``, ``'!'``, or ``'?'``, possibly sentence ending consists of a lowercase letter followed by one of ``'.'``,
followed by one of ``'"'`` or ``"'"``, followed by a space. One problem with ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``,
this is algorithm is that it is unable to detect the difference between "Dr." in followed by a space. One problem with this is algorithm is that it is
:: unable to detect the difference between "Dr." in ::
[...] Dr. Frankenstein's monster [...] [...] Dr. Frankenstein's monster [...]
...@@ -154,34 +155,34 @@ constructor) are as follows: ...@@ -154,34 +155,34 @@ constructor) are as follows:
:attr:`fix_sentence_endings` is false by default. :attr:`fix_sentence_endings` is false by default.
Since the sentence detection algorithm relies on ``string.lowercase`` for the Since the sentence detection algorithm relies on ``string.lowercase`` for
definition of "lowercase letter," and a convention of using two spaces after the definition of "lowercase letter," and a convention of using two spaces
a period to separate sentences on the same line, it is specific to after a period to separate sentences on the same line, it is specific to
English-language texts. English-language texts.
.. attribute:: TextWrapper.break_long_words .. attribute:: break_long_words
(default: ``True``) If true, then words longer than :attr:`width` will be broken (default: ``True``) If true, then words longer than :attr:`width` will be
in order to ensure that no lines are longer than :attr:`width`. If it is false, broken in order to ensure that no lines are longer than :attr:`width`. If
long words will not be broken, and some lines may be longer than :attr:`width`. it is false, long words will not be broken, and some lines may be longer
(Long words will be put on a line by themselves, in order to minimize the amount than :attr:`width`. (Long words will be put on a line by themselves, in
by which :attr:`width` is exceeded.) order to minimize the amount by which :attr:`width` is exceeded.)
:class:`TextWrapper` also provides two public methods, analogous to the :class:`TextWrapper` also provides two public methods, analogous to the
module-level convenience functions: module-level convenience functions:
.. method:: TextWrapper.wrap(text) .. method:: wrap(text)
Wraps the single paragraph in *text* (a string) so every line is at most Wraps the single paragraph in *text* (a string) so every line is at most
:attr:`width` characters long. All wrapping options are taken from instance :attr:`width` characters long. All wrapping options are taken from
attributes of the :class:`TextWrapper` instance. Returns a list of output lines, instance attributes of the :class:`TextWrapper` instance. Returns a list
without final newlines. of output lines, without final newlines.
.. method:: TextWrapper.fill(text) .. method:: fill(text)
Wraps the single paragraph in *text*, and returns a single string containing the Wraps the single paragraph in *text*, and returns a single string
wrapped paragraph. containing the wrapped paragraph.
...@@ -304,61 +304,63 @@ ElementTree Objects ...@@ -304,61 +304,63 @@ ElementTree Objects
XML *file* if given. XML *file* if given.
.. method:: ElementTree._setroot(element) .. method:: _setroot(element)
Replaces the root element for this tree. This discards the current contents of Replaces the root element for this tree. This discards the current
the tree, and replaces it with the given element. Use with care. *element* is contents of the tree, and replaces it with the given element. Use with
an element instance. care. *element* is an element instance.
.. method:: ElementTree.find(path) .. method:: find(path)
Finds the first toplevel element with given tag. Same as getroot().find(path). Finds the first toplevel element with given tag. Same as
*path* is the element to look for. Returns the first matching element, or getroot().find(path). *path* is the element to look for. Returns the
``None`` if no element was found. first matching element, or ``None`` if no element was found.
.. method:: ElementTree.findall(path) .. method:: findall(path)
Finds all toplevel elements with the given tag. Same as getroot().findall(path). Finds all toplevel elements with the given tag. Same as
*path* is the element to look for. Returns a list or :term:`iterator` containing all getroot().findall(path). *path* is the element to look for. Returns a
matching elements, in document order. list or :term:`iterator` containing all matching elements, in document
order.
.. method:: ElementTree.findtext(path[, default]) .. method:: findtext(path[, default])
Finds the element text for the first toplevel element with given tag. Same as Finds the element text for the first toplevel element with given tag.
getroot().findtext(path). *path* is the toplevel element to look for. *default* Same as getroot().findtext(path). *path* is the toplevel element to look
is the value to return if the element was not found. Returns the text content of for. *default* is the value to return if the element was not
the first matching element, or the default value no element was found. Note found. Returns the text content of the first matching element, or the
that if the element has is found, but has no text content, this method returns default value no element was found. Note that if the element has is
an empty string. found, but has no text content, this method returns an empty string.
.. method:: ElementTree.getiterator([tag]) .. method:: getiterator([tag])
Creates and returns a tree iterator for the root element. The iterator loops Creates and returns a tree iterator for the root element. The iterator
over all elements in this tree, in section order. *tag* is the tag to look for loops over all elements in this tree, in section order. *tag* is the tag
(default is to return all elements) to look for (default is to return all elements)
.. method:: ElementTree.getroot() .. method:: getroot()
Returns the root element for this tree. Returns the root element for this tree.
.. method:: ElementTree.parse(source[, parser]) .. method:: parse(source[, parser])
Loads an external XML section into this element tree. *source* is a file name or Loads an external XML section into this element tree. *source* is a file
file object. *parser* is an optional parser instance. If not given, the name or file object. *parser* is an optional parser instance. If not
standard XMLTreeBuilder parser is used. Returns the section root element. given, the standard XMLTreeBuilder parser is used. Returns the section
root element.
.. method:: ElementTree.write(file[, encoding]) .. method:: write(file[, encoding])
Writes the element tree to a file, as XML. *file* is a file name, or a file Writes the element tree to a file, as XML. *file* is a file name, or a
object opened for writing. *encoding* [1]_ is the output encoding (default is file object opened for writing. *encoding* [1]_ is the output encoding
US-ASCII). (default is US-ASCII).
This is the XML file that is going to be manipulated:: This is the XML file that is going to be manipulated::
...@@ -419,25 +421,25 @@ TreeBuilder Objects ...@@ -419,25 +421,25 @@ TreeBuilder Objects
Element instances when given. Element instances when given.
.. method:: TreeBuilder.close() .. method:: close()
Flushes the parser buffers, and returns the toplevel document element. Returns an Flushes the parser buffers, and returns the toplevel document
Element instance. element. Returns an Element instance.
.. method:: TreeBuilder.data(data) .. method:: data(data)
Adds text to the current element. *data* is a string. This should be either an Adds text to the current element. *data* is a string. This should be
ASCII-only :class:`bytes` object or a :class:`str` object. either an ASCII-only :class:`bytes` object or a :class:`str` object.
.. method:: TreeBuilder.end(tag) .. method:: end(tag)
Closes the current element. *tag* is the element name. Returns the closed Closes the current element. *tag* is the element name. Returns the closed
element. element.
.. method:: TreeBuilder.start(tag, attrs) .. method:: start(tag, attrs)
Opens a new element. *tag* is the element name. *attrs* is a dictionary Opens a new element. *tag* is the element name. *attrs* is a dictionary
containing element attributes. Returns the opened element. containing element attributes. Returns the opened element.
...@@ -457,18 +459,18 @@ XMLTreeBuilder Objects ...@@ -457,18 +459,18 @@ XMLTreeBuilder Objects
instance of the standard TreeBuilder class. instance of the standard TreeBuilder class.
.. method:: XMLTreeBuilder.close() .. method:: close()
Finishes feeding data to the parser. Returns an element structure. Finishes feeding data to the parser. Returns an element structure.
.. method:: XMLTreeBuilder.doctype(name, pubid, system) .. method:: doctype(name, pubid, system)
Handles a doctype declaration. *name* is the doctype name. *pubid* is the public Handles a doctype declaration. *name* is the doctype name. *pubid* is the
identifier. *system* is the system identifier. public identifier. *system* is the system identifier.
.. method:: XMLTreeBuilder.feed(data) .. method:: feed(data)
Feeds data to the parser. *data* is encoded data. Feeds data to the parser. *data* is encoded data.
......
...@@ -70,52 +70,54 @@ zipimporter Objects ...@@ -70,52 +70,54 @@ zipimporter Objects
(provided that it exists). (provided that it exists).
.. method:: zipimporter.find_module(fullname[, path]) .. method:: find_module(fullname[, path])
Search for a module specified by *fullname*. *fullname* must be the fully Search for a module specified by *fullname*. *fullname* must be the fully
qualified (dotted) module name. It returns the zipimporter instance itself if qualified (dotted) module name. It returns the zipimporter instance itself
the module was found, or :const:`None` if it wasn't. The optional *path* if the module was found, or :const:`None` if it wasn't. The optional
argument is ignored---it's there for compatibility with the importer protocol. *path* argument is ignored---it's there for compatibility with the
importer protocol.
.. method:: zipimporter.get_code(fullname) .. method:: get_code(fullname)
Return the code object for the specified module. Raise :exc:`ZipImportError` if Return the code object for the specified module. Raise
the module couldn't be found. :exc:`ZipImportError` if the module couldn't be found.
.. method:: zipimporter.get_data(pathname) .. method:: get_data(pathname)
Return the data associated with *pathname*. Raise :exc:`IOError` if the file Return the data associated with *pathname*. Raise :exc:`IOError` if the
wasn't found. file wasn't found.
.. method:: zipimporter.get_source(fullname) .. method:: get_source(fullname)
Return the source code for the specified module. Raise :exc:`ZipImportError` if Return the source code for the specified module. Raise
the module couldn't be found, return :const:`None` if the archive does contain :exc:`ZipImportError` if the module couldn't be found, return
the module, but has no source for it. :const:`None` if the archive does contain the module, but has no source
for it.
.. method:: zipimporter.is_package(fullname) .. method:: is_package(fullname)
Return True if the module specified by *fullname* is a package. Raise Return True if the module specified by *fullname* is a package. Raise
:exc:`ZipImportError` if the module couldn't be found. :exc:`ZipImportError` if the module couldn't be found.
.. method:: zipimporter.load_module(fullname) .. method:: load_module(fullname)
Load the module specified by *fullname*. *fullname* must be the fully qualified Load the module specified by *fullname*. *fullname* must be the fully
(dotted) module name. It returns the imported module, or raises qualified (dotted) module name. It returns the imported module, or raises
:exc:`ZipImportError` if it wasn't found. :exc:`ZipImportError` if it wasn't found.
.. attribute:: zipimporter.archive .. attribute:: archive
The file name of the importer's associated ZIP file. The file name of the importer's associated ZIP file.
.. attribute:: zipimporter.prefix .. attribute:: prefix
The path within the ZIP file where modules are searched; see The path within the ZIP file where modules are searched; see
:class:`zipimporter` for details. :class:`zipimporter` for details.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment