reformat some documentation of classes so methods and attributes are under the class directive

This commit is contained in:
Benjamin Peterson 2008-04-25 01:29:10 +00:00
parent 1c596d5604
commit c7b05920d6
42 changed files with 3690 additions and 3562 deletions

View File

@ -197,10 +197,10 @@ asynchat - Auxiliary Classes and Functions
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
empty string.
Produces the next chunk of information from the producer, or returns the
empty string.
.. class:: fifo([list=None])
@ -212,26 +212,26 @@ asynchat - Auxiliary Classes and Functions
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
producer fifo.
Adds the given data (which may be a string or a producer object) to the
producer fifo.
.. method:: fifo.pop()
.. method:: pop()
If the fifo is not empty, returns ``True, first()``, deleting the popped
item. Returns ``False, None`` for an empty fifo.
If the fifo is not empty, returns ``True, first()``, deleting the popped
item. Returns ``False, None`` for an empty fifo.
The :mod:`asynchat` module also defines one utility function, which may be of
use in network and textual analysis operations.

View File

@ -95,132 +95,132 @@ 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
:cfunc:`poll`\ ed for read and write events.
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:
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:
.. method:: dispatcher.handle_read()
.. method:: handle_read()
Called when the asynchronous loop detects that a :meth:`read` call on the
channel's socket will succeed.
Called when the asynchronous loop detects that a :meth:`read` call on the
channel's socket will succeed.
.. method:: dispatcher.handle_write()
.. method:: handle_write()
Called when the asynchronous loop detects that a writable socket can be
written. Often this method will implement the necessary buffering for
performance. For example::
Called when the asynchronous loop detects that a writable socket can be
written. Often this method will implement the necessary buffering for
performance. For example::
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
def handle_write(self):
sent = self.send(self.buffer)
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
will almost never happen, as OOB is tenuously supported and rarely used.
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.
.. method:: dispatcher.handle_connect()
.. method:: handle_connect()
Called when the active opener's socket actually makes a connection. Might
send a "welcome" banner, or initiate a protocol negotiation with the remote
endpoint, for example.
Called when the active opener's socket actually makes a connection. Might
send a "welcome" banner, or initiate a protocol negotiation with the
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
version prints a condensed traceback.
Called when an exception is raised and not otherwise handled. The default
version prints a condensed traceback.
.. method:: dispatcher.handle_accept()
.. method:: handle_accept()
Called on listening channels (passive openers) when a connection can be
established with a new remote endpoint that has issued a :meth:`connect`
call for the local endpoint.
Called on listening channels (passive openers) when a connection can be
established with a new remote endpoint that has issued a :meth:`connect`
call for the local endpoint.
.. method:: dispatcher.readable()
.. method:: readable()
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
occur. The default method simply returns ``True``, indicating that by
default, all channels will be interested in read events.
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
occur. The default method simply returns ``True``, indicating that by
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
channel's socket should be added to the list on which write events can
occur. The default method simply returns ``True``, indicating that by
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.
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
occur. The default method simply returns ``True``, indicating that by
default, all channels will be interested in write events.
.. method:: dispatcher.create_socket(family, type)
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.
In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.
.. method:: dispatcher.connect(address)
.. method:: create_socket(family, type)
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.
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.
.. method:: dispatcher.send(data)
.. method:: connect(address)
Send *data* to the remote end-point of the socket.
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.
.. method:: dispatcher.recv(buffer_size)
.. method:: send(data)
Read at most *buffer_size* bytes from the socket's remote end-point.
An empty string implies that the channel has been closed from the other
end.
Send *data* to the remote end-point of the socket.
.. method:: dispatcher.listen(backlog)
.. method:: recv(buffer_size)
Listen for connections made to the socket. The *backlog* argument
specifies the maximum number of queued connections and should be at least
1; the maximum value is system-dependent (usually 5).
Read at most *buffer_size* bytes from the socket's remote end-point. An
empty string implies that the channel has been closed from the other end.
.. method:: dispatcher.bind(address)
.. method:: listen(backlog)
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
the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call
the :class:`dispatcher` object's :meth:`set_reuse_addr` method.
Listen for connections made to the socket. The *backlog* argument
specifies the maximum number of queued connections and should be at least
1; the maximum value is system-dependent (usually 5).
.. method:: dispatcher.accept()
.. method:: bind(address)
Accept a connection. The socket must be bound to an address and listening
for connections. The return value is a pair ``(conn, address)`` where
*conn* is a *new* socket object usable to send and receive data on the
connection, and *address* is the address bound to the socket on the other
end of the connection.
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
the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call
the :class:`dispatcher` object's :meth:`set_reuse_addr` method.
.. method:: dispatcher.close()
.. method:: accept()
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
flushed). Sockets are automatically closed when they are
garbage-collected.
Accept a connection. The socket must be bound to an address and listening
for connections. The return value is a pair ``(conn, address)`` where
*conn* is a *new* socket object usable to send and receive data on the
connection, and *address* is the address bound to the socket on the other
end of the connection.
.. method:: close()
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
flushed). Sockets are automatically closed when they are
garbage-collected.
.. _asyncore-example:

View File

@ -34,222 +34,230 @@ to a handler. Code to create and run the server looks like this::
.. class:: HTTPServer(server_address, RequestHandlerClass)
This class builds on the :class:`TCPServer` class by storing the server address
as instance variables named :attr:`server_name` and :attr:`server_port`. The
server is accessible by the handler, typically through the handler's
:attr:`server` instance variable.
This class builds on the :class:`TCPServer` class by storing the server
address as instance variables named :attr:`server_name` and
:attr:`server_port`. The server is accessible by the handler, typically
through the handler's :attr:`server` instance variable.
.. class:: BaseHTTPRequestHandler(request, client_address, server)
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
handle each request method (e.g. GET or POST). :class:`BaseHTTPRequestHandler`
provides a number of class and instance variables, and methods for use by
subclasses.
itself, it cannot respond to any actual HTTP requests; it must be subclassed
to handle each request method (e.g. GET or
POST). :class:`BaseHTTPRequestHandler` provides a number of class and
instance variables, and methods for use by subclasses.
The handler will parse the request and the headers, then call a method specific
to the request type. The method name is constructed from the request. For
example, for the request method ``SPAM``, the :meth:`do_SPAM` method will be
called with no arguments. All of the relevant information is stored in instance
variables of the handler. Subclasses should not need to override or extend the
:meth:`__init__` method.
The handler will parse the request and the headers, then call a method
specific to the request type. The method name is constructed from the
request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
method will be called with no arguments. All of the relevant information is
stored in instance variables of the handler. Subclasses should not need to
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
variable. This instance parses and manages the headers in the HTTP request.
Holds an instance of the class specified by the :attr:`MessageClass` class
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
adherence to the HTTP protocol must be used when writing to this stream.
Contains the output stream for writing a response back to the
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
Specifies the server software version. You may want to override this. The
format is multiple whitespace-separated strings, where each string is of the
form name[/version]. For example, ``'BaseHTTP/0.2'``.
.. attribute:: server_version
Specifies the server software version. You may want to override this. The
format is multiple whitespace-separated strings, where each string is of
the form name[/version]. For example, ``'BaseHTTP/0.2'``.
.. attribute:: BaseHTTPRequestHandler.sys_version
Contains the Python system version, in a form usable by the
:attr:`version_string` method and the :attr:`server_version` class variable. For
example, ``'Python/1.4'``.
.. attribute:: sys_version
Contains the Python system version, in a form usable by the
:attr:`version_string` method and the :attr:`server_version` class
variable. For example, ``'Python/1.4'``.
.. attribute:: BaseHTTPRequestHandler.error_message_format
Specifies a format string for building an error response to the client. It uses
parenthesized, keyed format specifiers, so the format operand must be a
dictionary. The *code* key should be an integer, specifying the numeric HTTP
error code value. *message* should be a string containing a (detailed) error
message of what occurred, and *explain* should be an explanation of the error
code number. Default *message* and *explain* values can found in the *responses*
class variable.
.. attribute:: error_message_format
Specifies a format string for building an error response to the client. It
uses parenthesized, keyed format specifiers, so the format operand must be
a dictionary. The *code* key should be an integer, specifying the numeric
HTTP error code value. *message* should be a string containing a
(detailed) error message of what occurred, and *explain* should be an
explanation of the error code number. Default *message* and *explain*
values can found in the *responses* class variable.
.. attribute:: BaseHTTPRequestHandler.error_content_type
Specifies the Content-Type HTTP header of error responses sent to the client.
The default value is ``'text/html'``.
.. attribute:: error_content_type
.. versionadded:: 2.6
Previously, the content type was always ``'text/html'``.
Specifies the Content-Type HTTP header of error responses sent to the
client. The default value is ``'text/html'``.
.. versionadded:: 2.6
Previously, the content type was always ``'text/html'``.
.. attribute:: BaseHTTPRequestHandler.protocol_version
This specifies the HTTP protocol version used in responses. If set to
``'HTTP/1.1'``, the server will permit HTTP persistent connections; however,
your server *must* then include an accurate ``Content-Length`` header (using
:meth:`send_header`) in all of its responses to clients. For backwards
compatibility, the setting defaults to ``'HTTP/1.0'``.
.. attribute:: protocol_version
This specifies the HTTP protocol version used in responses. If set to
``'HTTP/1.1'``, the server will permit HTTP persistent connections;
however, your server *must* then include an accurate ``Content-Length``
header (using :meth:`send_header`) in all of its responses to clients.
For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.
.. attribute:: BaseHTTPRequestHandler.MessageClass
.. index:: single: Message (in module mimetools)
.. attribute:: MessageClass
Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers.
Typically, this is not overridden, and it defaults to
:class:`mimetools.Message`.
.. index:: single: Message (in module mimetools)
Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers.
Typically, this is not overridden, and it defaults to
:class:`mimetools.Message`.
.. attribute:: BaseHTTPRequestHandler.responses
This variable contains a mapping of error code integers to two-element tuples
containing a short and long message. For example, ``{code: (shortmessage,
longmessage)}``. The *shortmessage* is usually used as the *message* key in an
error response, and *longmessage* as the *explain* key (see the
:attr:`error_message_format` class variable).
.. attribute:: responses
A :class:`BaseHTTPRequestHandler` instance has the following methods:
This variable contains a mapping of error code integers to two-element tuples
containing a short and long message. For example, ``{code: (shortmessage,
longmessage)}``. The *shortmessage* is usually used as the *message* key in an
error response, and *longmessage* as the *explain* key (see the
:attr:`error_message_format` class variable).
.. method:: BaseHTTPRequestHandler.handle()
A :class:`BaseHTTPRequestHandler` instance has the following methods:
Calls :meth:`handle_one_request` once (or, if persistent connections are
enabled, multiple times) to handle incoming HTTP requests. You should never need
to override it; instead, implement appropriate :meth:`do_\*` methods.
.. method:: handle()
.. method:: BaseHTTPRequestHandler.handle_one_request()
Calls :meth:`handle_one_request` once (or, if persistent connections are
enabled, multiple times) to handle incoming HTTP requests. You should
never need to override it; instead, implement appropriate :meth:`do_\*`
methods.
This method will parse and dispatch the request to the appropriate :meth:`do_\*`
method. You should never need to override it.
.. method:: handle_one_request()
.. method:: BaseHTTPRequestHandler.send_error(code[, message])
This method will parse and dispatch the request to the appropriate
:meth:`do_\*` method. You should never need to override it.
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
complete set of headers is sent, followed by text composed using the
:attr:`error_message_format` class variable.
.. method:: send_error(code[, message])
.. method:: BaseHTTPRequestHandler.send_response(code[, message])
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
complete set of headers is sent, followed by text composed using the
:attr:`error_message_format` class variable.
Sends a response header and logs the accepted request. The HTTP response line is
sent, followed by *Server* and *Date* headers. The values for these two headers
are picked up from the :meth:`version_string` and :meth:`date_time_string`
methods, respectively.
.. method:: send_response(code[, message])
.. method:: BaseHTTPRequestHandler.send_header(keyword, value)
Sends a response header and logs the accepted request. The HTTP response
line is sent, followed by *Server* and *Date* headers. The values for
these two headers are picked up from the :meth:`version_string` and
:meth:`date_time_string` methods, respectively.
Writes a specific HTTP header to the output stream. *keyword* should specify the
header keyword, with *value* specifying its value.
.. method:: send_header(keyword, value)
.. method:: BaseHTTPRequestHandler.end_headers()
Writes a specific HTTP header to the output stream. *keyword* should
specify the header keyword, with *value* specifying its value.
Sends a blank line, indicating the end of the HTTP headers in the response.
.. method:: end_headers()
.. method:: BaseHTTPRequestHandler.log_request([code[, size]])
Sends a blank line, indicating the end of the HTTP headers in the
response.
Logs an accepted (successful) request. *code* should specify the numeric HTTP
code associated with the response. If a size of the response is available, then
it should be passed as the *size* parameter.
.. method:: log_request([code[, size]])
.. method:: BaseHTTPRequestHandler.log_error(...)
Logs an accepted (successful) request. *code* should specify the numeric
HTTP code associated with the response. If a size of the response is
available, then it should be passed as the *size* parameter.
Logs an error when a request cannot be fulfilled. By default, it passes the
message to :meth:`log_message`, so it takes the same arguments (*format* and
additional values).
.. method:: log_error(...)
.. method:: BaseHTTPRequestHandler.log_message(format, ...)
Logs an error when a request cannot be fulfilled. By default, it passes
the message to :meth:`log_message`, so it takes the same arguments
(*format* and additional values).
Logs an arbitrary message to ``sys.stderr``. This is typically overridden to
create custom error logging mechanisms. The *format* argument is a standard
printf-style format string, where the additional arguments to
:meth:`log_message` are applied as inputs to the formatting. The client address
and current date and time are prefixed to every message logged.
.. method:: log_message(format, ...)
.. method:: BaseHTTPRequestHandler.version_string()
Logs an arbitrary message to ``sys.stderr``. This is typically overridden
to create custom error logging mechanisms. The *format* argument is a
standard printf-style format string, where the additional arguments to
:meth:`log_message` are applied as inputs to the formatting. The client
address and current date and time are prefixed to every message logged.
Returns the server software's version string. This is a combination of the
:attr:`server_version` and :attr:`sys_version` class variables.
.. method:: version_string()
.. method:: BaseHTTPRequestHandler.date_time_string([timestamp])
Returns the server software's version string. This is a combination of the
:attr:`server_version` and :attr:`sys_version` class variables.
Returns the date and time given by *timestamp* (which must be in the format
returned by :func:`time.time`), formatted for a message header. If *timestamp*
is omitted, it uses the current date and time.
The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
.. method:: date_time_string([timestamp])
.. versionadded:: 2.5
The *timestamp* parameter.
Returns the date and time given by *timestamp* (which must be in the
format returned by :func:`time.time`), formatted for a message header. If
*timestamp* is omitted, it uses the current date and time.
The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.
.. method:: BaseHTTPRequestHandler.log_date_time_string()
.. versionadded:: 2.5
The *timestamp* parameter.
Returns the current date and time, formatted for logging.
.. method:: log_date_time_string()
.. method:: BaseHTTPRequestHandler.address_string()
Returns the current date and time, formatted for logging.
Returns the client address, formatted for logging. A name lookup is performed on
the client's IP address.
.. method:: address_string()
Returns the client address, formatted for logging. A name lookup is
performed on the client's IP address.
.. seealso::

View File

@ -31,32 +31,35 @@ The :mod:`bdb` module also defines two classes:
first line of that function is executed. A conditional breakpoint always
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
last breakpoint in that position, it also deletes the entry for the
file/line.
Delete the breakpoint from the list associated to a file/line. If it is
the last breakpoint in that position, it also deletes the entry for the
file/line.
.. method:: Breakpoint.enable()
Mark the breakpoint as enabled.
.. method:: enable()
.. method:: Breakpoint.disable()
Mark the breakpoint as enabled.
Mark the breakpoint as disabled.
.. method:: Breakpoint.bpprint([out])
.. method:: disable()
Print all the information about the breakpoint:
Mark the breakpoint as disabled.
* The breakpoint number.
* If it is temporary or not.
* Its file,line position.
* The condition that causes a break.
* If it must be ignored the next N times.
* The breakpoint hit count.
.. method:: pprint([out])
Print all the information about the breakpoint:
* The breakpoint number.
* If it is temporary or not.
* Its file,line position.
* The condition that causes a break.
* If it must be ignored the next N times.
* The breakpoint hit count.
.. class:: Bdb()
@ -68,247 +71,246 @@ The :mod:`bdb` module also defines two classes:
(: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
case-normalized (on case-insensitive filesystems) absolute path, stripped
of surrounding angle brackets.
Auxiliary method for getting a filename in a canonical form, that is, as a
case-normalized (on case-insensitive filesystems) absolute path, stripped
of surrounding angle brackets.
.. method:: Bdb.reset()
.. method:: reset()
Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and
:attr:`quitting` attributes with values ready to start debugging.
Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and
: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
return value is the new trace function (in most cases, that is, itself).
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).
The default implementation decides how to dispatch a frame, depending on
the type of event (passed as a string) that is about to be executed.
*event* can be one of the following:
The default implementation decides how to dispatch a frame, depending on the
type of event (passed as a string) that is about to be executed. *event* can
be one of the following:
* ``"line"``: A new line of code is going to be executed.
* ``"call"``: A function is about to be called, or another code block
entered.
* ``"return"``: A function or other code block is about to return.
* ``"exception"``: An exception has occurred.
* ``"c_call"``: A C function is about to be called.
* ``"c_return"``: A C function has returned.
* ``"c_exception"``: A C function has thrown an exception.
* ``"line"``: A new line of code is going to be executed.
* ``"call"``: A function is about to be called, or another code block
entered.
* ``"return"``: A function or other code block is about to return.
* ``"exception"``: An exception has occurred.
* ``"c_call"``: A C function is about to be called.
* ``"c_return"``: A C function has returned.
* ``"c_exception"``: A C function has thrown an exception.
For the Python events, specialized functions (see below) are called. For
the C events, no action is taken.
For the Python events, specialized functions (see below) are called. For 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 information on code and frame objects, refer to :ref:`types`.
For more information on trace functions, see :ref:`debugger-hooks`. For more
information on code and frame objects, refer to :ref:`types`.
.. method:: dispatch_line(frame)
.. method:: Bdb.dispatch_line(frame)
If the debugger should stop on the current line, invoke the
:meth:`user_line` method (which should be overridden in subclasses).
Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
(which can be set from :meth:`user_line`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
If the debugger should stop on the current line, invoke the :meth:`user_line`
method (which should be overridden in subclasses). Raise a :exc:`BdbQuit`
exception if the :attr:`Bdb.quitting` flag is set (which can be set from
:meth:`user_line`). Return a reference to the :meth:`trace_dispatch` method
for further tracing in that scope.
.. method:: dispatch_call(frame, arg)
.. method:: Bdb.dispatch_call(frame, arg)
If the debugger should stop on this function call, invoke the
:meth:`user_call` method (which should be overridden in subclasses).
Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
(which can be set from :meth:`user_call`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
If the debugger should stop on this function call, invoke the
:meth:`user_call` method (which should be overridden in subclasses). Raise a
:exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can
be set from :meth:`user_call`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
.. method:: dispatch_return(frame, arg)
.. method:: Bdb.dispatch_return(frame, arg)
If the debugger should stop on this function return, invoke the
:meth:`user_return` method (which should be overridden in subclasses).
Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
(which can be set from :meth:`user_return`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
If the debugger should stop on this function return, invoke the
:meth:`user_return` method (which should be overridden in subclasses). Raise
a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can
be set from :meth:`user_return`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
.. method:: dispatch_exception(frame, arg)
.. method:: Bdb.dispatch_exception(frame, arg)
If the debugger should stop at this exception, invokes the
:meth:`user_exception` method (which should be overridden in subclasses).
Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
(which can be set from :meth:`user_exception`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
If the debugger should stop at this exception, invokes the
:meth:`user_exception` method (which should be overridden in subclasses).
Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
(which can be set from :meth:`user_exception`). Return a reference to the
:meth:`trace_dispatch` method for further tracing in that scope.
Normally derived classes don't override the following methods, but they may
if they want to redefine the definition of stopping and breakpoints.
Normally derived classes don't override the following methods, but they may if
they want to redefine the definition of stopping and breakpoints.
.. method:: stop_here(frame)
.. method:: Bdb.stop_here(frame)
This method checks if the *frame* is somewhere below :attr:`botframe` in
the call stack. :attr:`botframe` is the frame in which debugging started.
This method checks if the *frame* is somewhere below :attr:`botframe` in the
call stack. :attr:`botframe` is the frame in which debugging started.
.. method:: break_here(frame)
.. method:: Bdb.break_here(frame)
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
breakpoint is a temporary one, this method deletes it.
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
breakpoint is a temporary one, this method deletes it.
.. method:: break_anywhere(frame)
.. method:: Bdb.break_anywhere(frame)
This method checks if there is a breakpoint in the filename of the current
frame.
This method checks if there is a breakpoint in the filename of the current
frame.
Derived classes should override these methods to gain control over debugger
operation.
Derived classes should override these methods to gain control over debugger
operation.
.. method:: user_call(frame, argument_list)
.. method:: Bdb.user_call(frame, argument_list)
This method is called from :meth:`dispatch_call` when there is the
possibility that a break might be necessary anywhere inside the called
function.
This method is called from :meth:`dispatch_call` when there is the
possibility that a break might be necessary anywhere inside the called
function.
.. method:: user_line(frame)
.. method:: Bdb.user_line(frame)
This method is called from :meth:`dispatch_line` when either
:meth:`stop_here` or :meth:`break_here` yields True.
This method is called from :meth:`dispatch_line` when either
:meth:`stop_here` or :meth:`break_here` yields True.
.. method:: user_return(frame, return_value)
.. method:: Bdb.user_return(frame, return_value)
This method is called from :meth:`dispatch_return` when :meth:`stop_here`
yields True.
This method is called from :meth:`dispatch_return` when :meth:`stop_here`
yields True.
.. method:: user_exception(frame, exc_info)
.. method:: Bdb.user_exception(frame, exc_info)
This method is called from :meth:`dispatch_exception` when
:meth:`stop_here` yields True.
This method is called from :meth:`dispatch_exception` when :meth:`stop_here`
yields True.
.. method:: do_clear(arg)
.. method:: Bdb.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
stepping state.
Derived classes and clients can call the following methods to affect the
stepping state.
.. method:: set_step()
.. method:: Bdb.set_step()
Stop after one line of code.
Stop after one line of code.
.. method:: set_next(frame)
.. method:: Bdb.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:: set_return(frame)
.. method:: Bdb.set_return(frame)
Stop when returning from the given frame.
Stop when returning from the given frame.
.. method:: set_trace([frame])
.. method:: Bdb.set_trace([frame])
Start debugging from *frame*. If *frame* is not specified, debugging
starts from caller's frame.
Start debugging from *frame*. If *frame* is not specified, debugging starts
from caller's frame.
.. method:: set_continue()
.. method:: Bdb.set_continue()
Stop only at breakpoints or when finished. If there are no breakpoints,
set the system trace function to None.
Stop only at breakpoints or when finished. If there are no breakpoints, set
the system trace function to None.
.. method:: set_quit()
.. method:: Bdb.set_quit()
Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in
the next call to one of the :meth:`dispatch_\*` methods.
Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in
the next call to one of the :meth:`dispatch_\*` methods.
Derived classes and clients can call the following methods to manipulate
breakpoints. These methods return a string containing an error message if
something went wrong, or ``None`` if all is well.
Derived classes and clients can call the following methods to manipulate
breakpoints. These methods return a string containing an error message if
something went wrong, or ``None`` if all is well.
.. method:: set_break(filename, lineno[, temporary=0[, cond[, funcname]]])
.. method:: Bdb.set_break(filename, lineno[, temporary=0[, cond[, funcname]]])
Set a new breakpoint. If the *lineno* line doesn't exist for the
*filename* passed as argument, return an error message. The *filename*
should be in canonical form, as described in the :meth:`canonic` method.
Set a new breakpoint. If the *lineno* line doesn't exist for the *filename*
passed as argument, return an error message. The *filename* should be in
canonical form, as described in the :meth:`canonic` method.
.. method:: clear_break(filename, lineno)
.. method:: Bdb.clear_break(filename, lineno)
Delete the breakpoints in *filename* and *lineno*. If none were set, an
error message is returned.
Delete the breakpoints in *filename* and *lineno*. If none were set, an
error message is returned.
.. method:: clear_bpbynumber(arg)
.. method:: Bdb.clear_bpbynumber(arg)
Delete the breakpoint which has the index *arg* in the
:attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range,
return an error message.
Delete the breakpoint which has the index *arg* in the
:attr:`Breakpoint.bpbynumber`. If *arg* is not numeric or out of range,
return an error message.
.. method:: clear_all_file_breaks(filename)
.. method:: Bdb.clear_all_file_breaks(filename)
Delete all breakpoints in *filename*. If none were set, an error message
is returned.
Delete all breakpoints in *filename*. If none were set, an error message is
returned.
.. method:: clear_all_breaks()
.. method:: Bdb.clear_all_breaks()
Delete all existing breakpoints.
Delete all existing breakpoints.
.. method:: get_break(filename, lineno)
.. method:: Bdb.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:: get_breaks(filename, lineno)
.. method:: Bdb.get_breaks(filename, lineno)
Return all breakpoints for *lineno* in *filename*, or an empty list if
none are set.
Return all breakpoints for *lineno* in *filename*, or an empty list if none
are set.
.. method:: get_file_breaks(filename)
.. method:: Bdb.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:: get_all_breaks()
.. method:: Bdb.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
structure representing a stack trace.
Derived classes and clients can call the following methods to get a data
structure representing a stack trace.
.. method:: get_stack(f, t)
.. method:: Bdb.get_stack(f, t)
Get a list of records for a frame and all higher (calling) and lower
frames, and the size of the higher part.
Get a list of records for a frame and all higher (calling) and lower frames,
and the size of the higher part.
.. method:: format_stack_entry(frame_lineno, [lprefix=': '])
.. method:: Bdb.format_stack_entry(frame_lineno, [lprefix=': '])
Return a string with information about a stack entry, identified by a
``(frame, lineno)`` tuple:
Return a string with information about a stack entry, identified by a
``(frame, lineno)`` tuple:
* The canonical form of the filename which contains the frame.
* The function name, or ``"<lambda>"``.
* The input arguments.
* The return value.
* The line of code (if it exists).
* The canonical form of the filename which contains the frame.
* The function name, or ``"<lambda>"``.
* The input arguments.
* The return value.
* The line of code (if it exists).
The following two methods can be called by clients to use a debugger to debug
a :term:`statement`, given as a string.
The following two methods can be called by clients to use a debugger to debug a
:term:`statement`, given as a string.
.. method:: run(cmd, [globals, [locals]])
.. method:: Bdb.run(cmd, [globals, [locals]])
Debug a statement executed via the :keyword:`exec` statement. *globals*
defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*.
Debug a statement executed via the :keyword:`exec` statement. *globals*
defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*.
.. method:: runeval(expr, [globals, [locals]])
.. method:: Bdb.runeval(expr, [globals, [locals]])
Debug an expression executed via the :func:`eval` function. *globals* and
*locals* have the same meaning as in :meth:`run`.
Debug an expression executed via the :func:`eval` function. *globals* and
*locals* have the same meaning as in :meth:`run`.
.. method:: runctx(cmd, globals, locals)
.. method:: Bdb.runctx(cmd, globals, locals)
For backwards compatibility. Calls the :meth:`run` method.
For backwards compatibility. Calls the :meth:`run` method.
.. method:: runcall(func, *args, **kwds)
.. method:: Bdb.runcall(func, *args, **kwds)
Debug a single function call, and return its result.
Debug a single function call, and return its result.
Finally, the module defines the following functions:

View File

@ -46,85 +46,89 @@ Handling of compressed files is offered by the :class:`BZ2File` class.
.. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]])
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
exist, and truncated otherwise. If *buffering* is given, ``0`` means unbuffered,
and larger numbers specify the buffer size; the default is ``0``. If
*compresslevel* is given, it must be a number between ``1`` and ``9``; the
default is ``9``. Add a ``'U'`` to mode to open the file for input with
universal newline support. Any line ending in the input file will be seen as a
``'\n'`` in Python. Also, a file so opened gains the attribute
exist, and truncated otherwise. If *buffering* is given, ``0`` means
unbuffered, and larger numbers specify the buffer size; the default is
``0``. If *compresslevel* is given, it must be a number between ``1`` and
``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input
with universal newline support. Any line ending in the input file will be
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
read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the newline
types seen. Universal newlines are available only when reading. Instances
support iteration in the same way as normal :class:`file` instances.
read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the
newline types seen. Universal newlines are available only when
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
be used for further I/O operations. :meth:`close` may be called more than once
without error.
Close the file. Sets data attribute :attr:`closed` to true. A closed file
cannot be used for further I/O operations. :meth:`close` may be called
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*
argument is negative or omitted, read until EOF is reached.
Read at most *size* uncompressed bytes, returned as a string. If the
*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
non-negative *size* argument limits the maximum number of bytes to return (an
incomplete line may be returned then). Return an empty string at EOF.
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 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
approximate bound on the total number of bytes in the lines returned.
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.
.. method:: BZ2File.xreadlines()
.. method:: xreadlines()
For backward compatibility. :class:`BZ2File` objects now include the performance
optimizations previously implemented in the :mod:`xreadlines` module.
For backward compatibility. :class:`BZ2File` objects now include the
performance optimizations previously implemented in the :mod:`xreadlines`
module.
.. deprecated:: 2.3
This exists only for compatibility with the method by this name on :class:`file`
objects, which is deprecated. Use ``for line in file`` instead.
.. deprecated:: 2.3
This exists only for compatibility with the method by this name on
:class:`file` objects, which is deprecated. Use ``for line in file``
instead.
.. method:: BZ2File.seek(offset[, whence])
.. method:: seek(offset[, whence])
Move to new file position. Argument *offset* is a byte count. Optional argument
*whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start of file; offset
should be ``>= 0``); other values are ``os.SEEK_CUR`` or ``1`` (move relative to
current position; offset can be positive or negative), and ``os.SEEK_END`` or
``2`` (move relative to end of file; offset is usually negative, although many
platforms allow seeking beyond the end of a file).
Move to new file position. Argument *offset* is a byte count. Optional
argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start
of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or
``1`` (move relative to current position; offset can be positive or
negative), and ``os.SEEK_END`` or ``2`` (move relative to end of 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
operation may be extremely slow.
Note that seeking of bz2 files is emulated, and depending on the
parameters the operation may be extremely slow.
.. method:: BZ2File.tell()
.. method:: tell()
Return the current file position, an integer (may be a long integer).
Return the current file position, an integer (may be a long integer).
.. method:: BZ2File.write(data)
.. method:: write(data)
Write string *data* to file. Note that due to buffering, :meth:`close` may be
needed before the file on disk reflects the data written.
Write string *data* to file. Note that due to buffering, :meth:`close` may
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
sequence can be any iterable object producing strings. This is equivalent to
calling write() for each string.
Write the sequence of strings to the file. Note that newlines are not
added. The sequence can be any iterable object producing strings. This is
equivalent to calling write() for each string.
Sequential (de)compression
@ -137,23 +141,23 @@ Sequential compression and decompression is done using the classes
.. class:: BZ2Compressor([compresslevel])
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`
function instead. The *compresslevel* parameter, if given, must be a number
between ``1`` and ``9``; the default is ``9``.
sequentially. If you want to compress data in one shot, use the
:func:`compress` function instead. The *compresslevel* parameter, if given,
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
data whenever possible. When you've finished providing data to compress, call
the :meth:`flush` method to finish the compression process, and return what is
left in internal buffers.
Provide more data to the compressor object. It will return chunks of
compressed data whenever possible. When you've finished providing data to
compress, call the :meth:`flush` method to finish the compression process,
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
must not use the compressor object after calling this method.
Finish the compression process and return what is left in internal
buffers. You must not use the compressor object after calling this method.
.. class:: BZ2Decompressor()
@ -163,12 +167,13 @@ Sequential compression and decompression is done using the classes
:func:`decompress` function instead.
.. method:: BZ2Decompressor.decompress(data)
.. method:: decompress(data)
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
of stream is found, :exc:`EOFError` will be raised. If any data was found after
the end of stream, it'll be ignored and saved in :attr:`unused_data` attribute.
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 of stream is found, :exc:`EOFError` will be raised. If any data
was found after the end of stream, it'll be ignored and saved in
:attr:`unused_data` attribute.
One-shot (de)compression
@ -180,13 +185,13 @@ and :func:`decompress` functions.
.. function:: compress(data[, compresslevel])
Compress *data* in one shot. If you want to compress data sequentially, use an
instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, if
given, must be a number between ``1`` and ``9``; the default is ``9``.
Compress *data* in one shot. If you want to compress data sequentially, use
an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter,
if given, must be a number between ``1`` and ``9``; the default is ``9``.
.. function:: decompress(data)
Decompress *data* in one shot. If you want to decompress data sequentially, use
an instance of :class:`BZ2Decompressor` instead.
Decompress *data* in one shot. If you want to decompress data sequentially,
use an instance of :class:`BZ2Decompressor` instead.

View File

@ -34,75 +34,76 @@ it's the base calendar for all computations.
.. versionadded:: 2.5
: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.
The first value from the iterator will be the same as the value of the
:attr:`firstweekday` property.
Return an iterator for the week day numbers that will be used for one
week. The first value from the iterator will be the same as the value of
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
iterator will return all days (as :class:`datetime.date` objects) for the month
and all days before the start of the month or after the end of the month that
are required to get a complete week.
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 and all days before the start of the month or after the end of the
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
:meth:`itermonthdates`. Days returned will be tuples consisting of a day number
and a week day number.
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 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
:meth:`itermonthdates`. Days returned will simply be day numbers.
Return an iterator for the month *month* in the year *year* similar to
: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.
Weeks are lists of seven :class:`datetime.date` objects.
Return a list of the weeks in the month *month* of the *year* as full
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.
Weeks are lists of seven tuples of day numbers and weekday numbers.
Return a list of the weeks in the month *month* of the *year* as full
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.
Weeks are lists of seven day numbers.
Return a list of the weeks in the month *month* of the *year* as full
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
is a list of month rows. Each month row contains up to *width* months
(defaulting to 3). Each month contains between 4 and 6 weeks and each week
contains 1--7 days. Days are :class:`datetime.date` objects.
Return the data for the specified year ready for formatting. The return
value is a list of month rows. Each month row contains up to *width*
months (defaulting to 3). Each month contains between 4 and 6 weeks and
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
:meth:`yeardatescalendar`). Entries in the week lists are tuples of day
numbers and weekday numbers. Day numbers outside this month are zero.
Return the data for the specified year ready for formatting (similar to
:meth:`yeardatescalendar`). Entries in the week lists are tuples of day
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
:meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day
numbers outside this month are zero.
Return the data for the specified year ready for formatting (similar to
:meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day
numbers outside this month are zero.
.. class:: TextCalendar([firstweekday])
@ -111,36 +112,36 @@ it's the base calendar for all computations.
.. versionadded:: 2.5
: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
specifies the width of the date columns, which are centered. If *l* is given,
it specifies the number of lines that each week will use. Depends on the
first weekday as specified in the constructor or set by the
:meth:`setfirstweekday` method.
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, it specifies the number of lines that each week will use. Depends
on the first weekday as specified in the constructor or set by the
: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.
Optional parameters *w*, *l*, and *c* are for date column width, lines per
week, and number of spaces between month columns, respectively. Depends on
the first weekday as specified in the constructor or set by the
:meth:`setfirstweekday` method. The earliest year for which a calendar can
be generated is platform-dependent.
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
week, and number of spaces between month columns, respectively. Depends on
the first weekday as specified in the constructor or set by the
:meth:`setfirstweekday` method. The earliest year for which a calendar
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`.
.. class:: HTMLCalendar([firstweekday])
@ -149,36 +150,37 @@ it's the base calendar for all computations.
.. versionadded:: 2.5
: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
be included in the header, otherwise just the month name will be used.
Return a month's calendar as an HTML table. If *withyear* is true the year
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
the number of months per row.
Return a year's calendar as an HTML table. *width* (defaulting to 3)
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)
specifies the number of months per row. *css* is the name for the cascading
style sheet to be used. :const:`None` can be passed if no style sheet should be
used. *encoding* specifies the encoding to be used for the output (defaulting to
the system default encoding).
Return a year's calendar as a complete HTML page. *width* (defaulting to
3) specifies the number of months per row. *css* is the name for the
cascading style sheet to be used. :const:`None` can be passed if no style
sheet should be used. *encoding* specifies the encoding to be used for the
output (defaulting to the system default encoding).
.. class:: LocaleTextCalendar([firstweekday[, locale]])
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
this locale includes an encoding all strings containing month and weekday names
will be returned as unicode.
constructor and will return month and weekday names in the specified
locale. If this locale includes an encoding all strings containing month and
weekday names will be returned as unicode.
.. versionadded:: 2.5
@ -186,9 +188,9 @@ it's the base calendar for all computations.
.. class:: LocaleHTMLCalendar([firstweekday[, locale]])
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
this locale includes an encoding all strings containing month and weekday names
will be returned as unicode.
constructor and will return month and weekday names in the specified
locale. If this locale includes an encoding all strings containing month and
weekday names will be returned as unicode.
.. versionadded:: 2.5

View File

@ -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
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
as containing CGI scripts.
This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
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.
Error 501, "Can only POST to CGI scripts", is output when trying to POST to a
non-CGI url.
This method serves the ``'POST'`` request type, only allowed for CGI
scripts. Error 501, "Can only POST to CGI scripts", is output when trying
to POST to a non-CGI url.
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.

View File

@ -66,62 +66,64 @@ instance will fail with a :exc:`EOFError` exception.
optional argument *inclheader* is true, the size given in the chunk header
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
file.
Close and skip to the end of the chunk. This does not close the
underlying file.
The remaining methods will raise :exc:`IOError` if called after the
:meth:`close` method has been called.
The remaining methods will raise :exc:`IOError` if called after the
: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
defaults to ``0`` (absolute file positioning); other values are ``1`` (seek
relative to the current position) and ``2`` (seek relative to the file's end).
There is no return value. If the underlying file does not allow seek, only
forward seeks are allowed.
Set the chunk's current position. The *whence* argument is optional and
defaults to ``0`` (absolute file positioning); other values are ``1``
(seek relative to the current position) and ``2`` (seek relative to the
file's end). There is no return value. If the underlying file does not
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
chunk before obtaining *size* bytes). If the *size* argument is negative or
omitted, read all data until the end of the chunk. The bytes are returned as a
string object. An empty string is returned when the end of the chunk is
encountered immediately.
Read at most *size* bytes from the chunk (less if the read hits the end of
the chunk before obtaining *size* bytes). If the *size* argument is
negative or omitted, read all data until the end of the chunk. The bytes
are returned as a string object. An empty string is returned when the end
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

View File

@ -435,16 +435,16 @@ define in order to be compatible with the Python codec registry.
:func:`register_error`.
.. method:: IncrementalEncoder.encode(object[, final])
.. method:: encode(object[, final])
Encodes *object* (taking the current state of the encoder into account) and
returns the resulting encoded object. If this is the last call to :meth:`encode`
*final* must be true (the default is false).
Encodes *object* (taking the current state of the encoder into account)
and returns the resulting encoded object. If this is the last call to
: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.
.. _incremental-decoder-objects:
@ -483,20 +483,21 @@ define in order to be compatible with the Python codec registry.
:func:`register_error`.
.. method:: IncrementalDecoder.decode(object[, final])
.. method:: decode(object[, final])
Decodes *object* (taking the current state of the decoder into account) and
returns the resulting decoded object. If this is the last call to :meth:`decode`
*final* must be true (the default is false). If *final* is true the decoder must
decode the input completely and must flush all buffers. If this isn't possible
(e.g. because of incomplete byte sequences at the end of the input) it must
initiate error handling just like in the stateless case (which might raise an
exception).
Decodes *object* (taking the current state of the decoder into account)
and returns the resulting decoded object. If this is the last call to
:meth:`decode` *final* must be true (the default is false). If *final* is
true the decoder must decode the input completely and must flush all
buffers. If this isn't possible (e.g. because of incomplete byte sequences
at the end of the input) it must initiate error handling just like in the
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.
The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
working interfaces which can be used to implement new encoding submodules very
@ -544,24 +545,25 @@ compatible with the Python codec registry.
: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
:meth:`write` method).
Writes the concatenated list of strings to the stream (possibly by reusing
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 clean state that allows appending of new fresh data without having to
rescan the whole stream to recover state.
Calling this method should ensure that the data on the output is put into a
clean state that allows appending of new fresh data without having to rescan the
whole stream to recover state.
In addition to the above methods, the :class:`StreamWriter` must also inherit
all other methods and attributes from the underlying stream.
@ -604,64 +606,68 @@ compatible with the Python codec registry.
: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`
will never return more than *chars* characters, but it might return less, if
there are not enough characters available.
*chars* indicates the number of characters to read from the
stream. :func:`read` will never return more than *chars* characters, but
it might return less, if there are not enough characters available.
*size* indicates the approximate maximum number of bytes to read from the stream
for decoding purposes. The decoder can modify this setting as appropriate. The
default value -1 indicates to read and decode as much as possible. *size* is
intended to prevent having to decode huge files in one step.
*size* indicates the approximate maximum number of bytes to read from the
stream for decoding purposes. The decoder can modify this setting as
appropriate. The default value -1 indicates to read and decode as much as
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,
if there are decoding errors on later lines.
*firstline* indicates that it would be sufficient to only return the first
line, if there are decoding errors on later lines.
The method should use a greedy read strategy meaning that it should read as much
data as is allowed within the definition of the encoding and the given size,
e.g. if optional encoding endings or state markers are available on the stream,
these should be read too.
The method should use a greedy read strategy meaning that it should read
as much data as is allowed within the definition of the encoding and the
given size, e.g. if optional encoding endings or state markers are
available on the stream, these should be read too.
.. versionchanged:: 2.4
*chars* argument added.
.. versionchanged:: 2.4
*chars* argument added.
.. versionchanged:: 2.4.2
*firstline* argument added.
.. versionchanged:: 2.4.2
*firstline* argument added.
.. 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`
method.
*size*, if given, is passed as size argument to the stream's
: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.
.. versionchanged:: 2.4
*keepends* argument added.
.. versionchanged:: 2.4
*keepends* argument added.
.. 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
in the list entries if *keepends* is true.
Line-endings are implemented using the codec's decoder method and are
included in the list entries if *keepends* is true.
*sizehint*, if given, is passed as the *size* argument to the stream's
:meth:`read` method.
*sizehint*, if given, is passed as the *size* argument to the stream's
: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 intended to be able to recover from decoding errors.
Note that no stream repositioning should take place. This method is primarily
intended to be able to recover from decoding errors.
In addition to the above methods, the :class:`StreamReader` must also inherit
all other methods and attributes from the underlying stream.
@ -730,6 +736,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
writers.
:class:`StreamRecoder` instances define the combined interfaces of
:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
methods and attributes from the underlying stream.

View File

@ -179,62 +179,63 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
.. versionchanged:: 2.6
Added *maxlen* parameter.
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
argument.
Extend the right side of the deque by appending elements from the iterable
argument.
.. method:: deque.extendleft(iterable)
.. method:: extendleft(iterable)
Extend the left side of the deque by appending elements from *iterable*. Note,
the series of left appends results in reversing the order of elements in the
iterable argument.
Extend the left side of the deque by appending elements from *iterable*.
Note, the series of left appends results in reversing the order of
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
are present, raises an :exc:`IndexError`.
Remove and return an element from the right side of the deque. If no
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
present, raises an :exc:`IndexError`.
Remove and return an element from the left side of the deque. If no
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
:exc:`ValueError`.
Removed the first occurrence of *value*. If not found, raises a
:exc:`ValueError`.
.. versionadded:: 2.5
.. versionadded:: 2.5
.. method:: deque.rotate(n)
.. method:: rotate(n)
Rotate the deque *n* steps to the right. If *n* is negative, rotate to
the left. Rotating one step to the right is equivalent to:
``d.appendleft(d.pop())``.
Rotate the deque *n* steps to the right. If *n* is negative, rotate to the
left. Rotating one step to the right is equivalent to:
``d.appendleft(d.pop())``.
In addition to the above, deques support iteration, pickling, ``len(d)``,
``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
@ -365,33 +366,35 @@ in Unix::
.. versionadded:: 2.5
:class:`defaultdict` objects support the following method in addition to the
standard :class:`dict` operations:
:class:`defaultdict` objects support the following method in addition to the
standard :class:`dict` operations:
.. method:: defaultdict.__missing__(key)
.. method:: defaultdict.__missing__(key)
If the :attr:`default_factory` attribute is ``None``, this raises an
:exc:`KeyError` exception with the *key* as argument.
If the :attr:`default_factory` attribute is ``None``, this raises an
:exc:`KeyError` exception with the *key* as argument.
If :attr:`default_factory` is not ``None``, it is called without arguments to
provide a default value for the given *key*, this value is inserted in the
dictionary for the *key*, and returned.
If :attr:`default_factory` is not ``None``, it is called without arguments
to provide a default value for the given *key*, this value is inserted in
the dictionary for the *key*, and returned.
If calling :attr:`default_factory` raises an exception this exception is
propagated unchanged.
If calling :attr:`default_factory` raises an exception this exception is
propagated unchanged.
This method is called by the :meth:`__getitem__` method of the :class:`dict`
class when the requested key is not found; whatever it returns or raises is then
returned or raised by :meth:`__getitem__`.
:class:`defaultdict` objects support the following instance variable:
This method is called by the :meth:`__getitem__` method of the
:class:`dict` class when the requested key is not found; whatever it
returns or raises is then returned or raised by :meth:`__getitem__`.
.. attribute:: defaultdict.default_factory
:class:`defaultdict` objects support the following instance variable:
This attribute is used by the :meth:`__missing__` method; it is initialized from
the first argument to the constructor, if present, or to ``None``, if absent.
.. attribute:: defaultdict.default_factory
This attribute is used by the :meth:`__missing__` method; it is
initialized from the first argument to the constructor, if present, or to
``None``, if absent.
.. _defaultdict-examples:

View File

@ -153,22 +153,24 @@ set of named attributes for child nodes.
``None``. XXX Not sure what the rules are for which nodes will have a useful
lineno.
All :class:`Node` objects offer the following methods:
All :class:`Node` objects offer the following methods:
.. method:: Node.getChildren()
.. method:: getChildren()
Returns a flattened list of the child nodes and objects in the order they occur.
Specifically, the order of the nodes is the order in which they appear in the
Python grammar. Not all of the children are :class:`Node` instances. The names
of functions and classes, for example, are plain strings.
Returns a flattened list of the child nodes and objects in the order they
occur. Specifically, the order of the nodes is the order in which they
appear in the Python grammar. Not all of the children are :class:`Node`
instances. The names of functions and classes, for example, are plain
strings.
.. method:: Node.getChildNodes()
.. method:: getChildNodes()
Returns a flattened list of the child nodes in the order they occur. This
method is like :meth:`getChildren`, except that it only returns those
children that are :class:`Node` instances.
Returns a flattened list of the child nodes in the order they occur. This
method is like :meth:`getChildren`, except that it only returns those children
that are :class:`Node` instances.
Two examples illustrate the general structure of :class:`Node` classes. The
:keyword:`while` statement is defined by the following grammar production::
@ -613,18 +615,18 @@ XXX The magic :meth:`visit` method for visitors.
particular child node. If no visitor is found for a particular node type, the
:meth:`default` method is called.
:class:`ASTVisitor` objects have the following methods:
:class:`ASTVisitor` objects have the following methods:
XXX describe extra arguments
XXX describe extra arguments
.. method:: ASTVisitor.default(node[, ...])
.. method:: default(node[, ...])
.. method:: ASTVisitor.dispatch(node[, ...])
.. method:: dispatch(node[, ...])
.. method:: ASTVisitor.preorder(tree, visitor)
.. method:: preorder(tree, visitor)
Bytecode Generation

View File

@ -218,19 +218,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 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
parameters found. If the optional *delimiters* parameter is given, it is
interpreted as a string containing possible valid delimiter characters.
Analyze the given *sample* and return a :class:`Dialect` subclass
reflecting the parameters found. If the optional *delimiters* parameter
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`
if the first row appears to be a series of column headers.
Analyze the sample text (presumed to be in CSV format) and return
:const:`True` if the first row appears to be a series of column headers.
An example for :class:`Sniffer` use::

View File

@ -1443,10 +1443,10 @@ loader instance.
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
returns a new instance of the library.
Load a shared library into the process and return it. This method always
returns a new instance of the library.
These prefabricated library loaders are available:
@ -1503,50 +1503,51 @@ They are instances of a private class:
Base class for C callable foreign functions.
Instances of foreign functions are also C compatible data types; they represent
C function pointers.
Instances of foreign functions are also C compatible data types; they
represent C function pointers.
This behavior can be customized by assigning to special attributes of the
foreign function object.
This behavior can be customized by assigning to special attributes of the
foreign function object.
.. attribute:: _FuncPtr.restype
.. attribute:: restype
Assign a ctypes type to specify the result type of the foreign function. Use
``None`` for ``void`` a function not returning anything.
Assign a ctypes type to specify the result type of the foreign function.
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
this case the function is assumed to return a C ``int``, and the callable will
be called with this integer, allowing to do further processing or error
checking. Using this is deprecated, for more flexible post processing or error
checking use a ctypes data type as :attr:`restype` and assign a callable to the
:attr:`errcheck` attribute.
It is possible to assign a callable Python object that is not a ctypes
type, in this case the function is assumed to return a C ``int``, and the
callable will be called with this integer, allowing to do further
processing or error checking. Using this is deprecated, for more flexible
post processing or error checking use a ctypes data type as
: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
accepts. Functions using the ``stdcall`` calling convention can only be called
with the same number of arguments as the length of this tuple; functions using
the C calling convention accept additional, unspecified arguments as well.
Assign a tuple of ctypes types to specify the argument types that the
function accepts. Functions using the ``stdcall`` calling convention can
only be called with the same number of arguments as the length of this
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
:meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this
method allows to adapt the actual argument to an object that the foreign
function accepts. For example, a :class:`c_char_p` item in the :attr:`argtypes`
tuple will convert a unicode string passed as argument into an byte string using
ctypes conversion rules.
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 method allows to adapt the actual argument to an object that
the foreign function accepts. For example, a :class:`c_char_p` item in
the :attr:`argtypes` tuple will convert a unicode string passed as
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
each item must have a :meth:`from_param` method which returns a value usable as
argument (integer, string, ctypes instance). This allows to define adapters
that can adapt custom objects as function parameters.
New: It is now possible to put items in argtypes which are not ctypes
types, but each item must have a :meth:`from_param` method which returns a
value usable as argument (integer, string, ctypes instance). This allows
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
will be called with three or more arguments:
Assign a Python function or another callable to this attribute. The
callable will be called with three or more arguments:
.. function:: callable(result, func, arguments)
@ -1561,9 +1562,9 @@ foreign function object.
``arguments`` is a tuple containing the parameters originally passed to the
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
call, but it can also check the result value and raise an exception if the
foreign function call failed.
The object that this function returns will be returned from the foreign
function call, but it can also check the result value and raise an exception
if the foreign function call failed.
.. exception:: ArgumentError()
@ -1945,57 +1946,58 @@ Data types
:attr:`_objects`; this contains other Python objects that need to be kept alive
in case the memory block contains pointers.
Common methods of ctypes data types, these are all class methods (to be exact,
they are methods of the :term:`metaclass`):
Common methods of ctypes data types, these are all class methods (to be
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
which must be an integer.
This method returns a ctypes type instance using the memory specified by
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
used in a foreign function call, when the type is present in the foreign
functions :attr:`argtypes` tuple; it must return an object that can be used as
function call parameter.
This method adapts obj to a ctypes type. It is called with the actual
object used in a foreign function call, when the type is present in the
foreign functions :attr:`argtypes` tuple; it must return an object that
can be used as function call parameter.
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
accept other objects as well.
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 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*
is the name of the symbol that exports the data, *library* is the loaded shared
library.
Common instance variables of ctypes data types:
This method returns a ctypes type instance exported by a shared
library. *name* is the name of the symbol that exports the data, *library*
is the loaded shared library.
.. attribute:: _CData._b_base_
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
:attr:`_b_base_` read-only member is the root ctypes object that owns the memory
block.
Common instance variables of ctypes data types:
.. attribute:: _CData._b_needsfree_
.. attribute:: _b_base_
This read-only variable is true when the ctypes data instance has allocated the
memory block itself, false otherwise.
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
:attr:`_b_base_` read-only member is the root ctypes object that owns the
memory block.
.. attribute:: _CData._objects
.. attribute:: _b_needsfree_
This member is either ``None`` or a dictionary containing Python objects that
need to be kept alive so that the memory block contents is kept valid. This
object is only exposed for debugging; never modify the contents of this
dictionary.
This read-only variable is true when the ctypes data instance has
allocated the memory block itself, false otherwise.
.. attribute:: _objects
This member is either ``None`` or a dictionary containing Python objects
that need to be kept alive so that the memory block contents is kept
valid. This object is only exposed for debugging; never modify the
contents of this dictionary.
.. _ctypes-fundamental-data-types-2:
@ -2015,19 +2017,20 @@ Fundamental data types
ctypes data types that are not 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
pointer types, it is an integer, for character types, it is a single character
string, for character pointer types it is a Python string or unicode string.
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 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
object is returned each time. ``ctypes`` does *not* implement original object
return, always a new object is constructed. The same is true for all other
ctypes object instances.
When the ``value`` attribute is retrieved from a ctypes instance, usually
a new object is returned each time. ``ctypes`` does *not* implement
original object return, always a new object is constructed. The same is
true for all other ctypes object instances.
Fundamental data types, when returned as foreign function call results, or, for
example, by retrieving structure field members or array items, are transparently
@ -2265,90 +2268,92 @@ other data types containing pointer type fields.
Abstract base class for structures in *native* byte order.
Concrete structure and union types must be created by subclassing one of these
types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will
create :term:`descriptor`\s which allow reading and writing the fields by direct
attribute accesses. These are the
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
create :term:`descriptor`\s which allow reading and writing the fields by direct
attribute accesses. These are the
.. attribute:: Structure._fields_
.. attribute:: _fields_
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
the type of the field; it can be any ctypes data type.
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 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.
It must be a small positive integer defining the bit width of the field.
For integer type fields like :class:`c_int`, a third optional item can be
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,
only one field can be accessed when names are repeated.
Field names must be unique within one structure or union. This is not
checked, only one field can be accessed when names are repeated.
It is possible to define the :attr:`_fields_` class variable *after* the class
statement that defines the Structure subclass, this allows to create data types
that directly or indirectly reference themselves::
It is possible to define the :attr:`_fields_` class variable *after* the
class statement that defines the Structure subclass, this allows to create
data types that directly or indirectly reference themselves::
class List(Structure):
pass
List._fields_ = [("pnext", POINTER(List)),
...
]
class List(Structure):
pass
List._fields_ = [("pnext", POINTER(List)),
...
]
The :attr:`_fields_` class variable must, however, be defined before the type is
first used (an instance is created, ``sizeof()`` is called on it, and so on).
Later assignments to the :attr:`_fields_` class variable will raise an
AttributeError.
The :attr:`_fields_` class variable must, however, be defined before the
type is first used (an instance is created, ``sizeof()`` is called on it,
and so on). Later assignments to the :attr:`_fields_` class variable will
raise an AttributeError.
Structure and union subclass constructors accept both positional and named
arguments. Positional arguments are used to initialize the fields in the same
order as they appear in the :attr:`_fields_` definition, named arguments are
used to initialize the fields with the corresponding name.
Structure and union subclass constructors accept both positional and named
arguments. Positional arguments are used to initialize the fields in the
same order as they appear in the :attr:`_fields_` definition, named
arguments are used to initialize the fields with the corresponding name.
It is possible to defined sub-subclasses of structure types, they inherit the
fields of the base class plus the :attr:`_fields_` defined in the sub-subclass,
if any.
It is possible to defined sub-subclasses of structure types, they inherit
the fields of the base class plus the :attr:`_fields_` defined in the
sub-subclass, if any.
.. attribute:: Structure._pack_
.. attribute:: _pack_
An optional small integer that allows to override the alignment of structure
fields in the instance. :attr:`_pack_` must already be defined when
:attr:`_fields_` is assigned, otherwise it will have no effect.
An optional small integer that allows to override the alignment of
structure fields in the instance. :attr:`_pack_` must already be defined
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.
``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
otherwise it will have no effect.
An optional sequence that lists the names of unnamed (anonymous) fields.
``_anonymous_`` must be already defined when :attr:`_fields_` is assigned,
otherwise it will have no effect.
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
the nested fields directly, without the need to create the structure or union
field.
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 the nested fields directly, without the need to create the
structure or union field.
Here is an example type (Windows)::
Here is an example type (Windows)::
class _U(Union):
_fields_ = [("lptdesc", POINTER(TYPEDESC)),
("lpadesc", POINTER(ARRAYDESC)),
("hreftype", HREFTYPE)]
class _U(Union):
_fields_ = [("lptdesc", POINTER(TYPEDESC)),
("lpadesc", POINTER(ARRAYDESC)),
("hreftype", HREFTYPE)]
class TYPEDESC(Structure):
_fields_ = [("u", _U),
("vt", VARTYPE)]
class TYPEDESC(Structure):
_fields_ = [("u", _U),
("vt", VARTYPE)]
_anonymous_ = ("u",)
_anonymous_ = ("u",)
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies
which one of the union fields is valid. Since the ``u`` field is defined as
anonymous field, it is now possible to access the members directly off the
TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the
former is faster since it does not need to create a temporary union instance::
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
specifies which one of the union fields is valid. Since the ``u`` field
is defined as anonymous field, it is now possible to access the members
directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
are equivalent, but the former is faster since it does not need to create
a temporary union instance::
td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)
td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)
It is possible to defined sub-subclasses of structures, they inherit the fields
of the base class. If the subclass definition has a separate :attr:`_fields_`

View File

@ -1572,92 +1572,94 @@ You can instantiate a :class:`Textbox` object as follows:
containing window, with coordinates ``(0, 0)``. The instance's
: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
until one of the termination keystrokes is entered. If *validator* is supplied,
it must be a function. It will be called for each keystroke entered with the
keystroke as a parameter; command dispatch is done on the result. This method
returns the window contents as a string; whether blanks in the window are
included is affected by the :attr:`stripspaces` member.
This is the entry point you will normally use. It accepts editing
keystrokes until one of the termination keystrokes is entered. If
*validator* is supplied, it must be a function. It will be called for
each keystroke entered with the keystroke as a parameter; command dispatch
is done on the result. This method returns the window contents as a
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 |
+==================+===========================================+
| :kbd:`Control-A` | Go to left edge of window. |
+------------------+-------------------------------------------+
| :kbd:`Control-B` | Cursor left, wrapping to previous line if |
| | appropriate. |
+------------------+-------------------------------------------+
| :kbd:`Control-D` | Delete character under cursor. |
+------------------+-------------------------------------------+
| :kbd:`Control-E` | Go to right edge (stripspaces off) or end |
| | of line (stripspaces on). |
+------------------+-------------------------------------------+
| :kbd:`Control-F` | Cursor right, wrapping to next line when |
| | appropriate. |
+------------------+-------------------------------------------+
| :kbd:`Control-G` | Terminate, returning the window contents. |
+------------------+-------------------------------------------+
| :kbd:`Control-H` | Delete character backward. |
+------------------+-------------------------------------------+
| :kbd:`Control-J` | Terminate if the window is 1 line, |
| | otherwise insert newline. |
+------------------+-------------------------------------------+
| :kbd:`Control-K` | If line is blank, delete it, otherwise |
| | clear to end of line. |
+------------------+-------------------------------------------+
| :kbd:`Control-L` | Refresh screen. |
+------------------+-------------------------------------------+
| :kbd:`Control-N` | Cursor down; move down one line. |
+------------------+-------------------------------------------+
| :kbd:`Control-O` | Insert a blank line at cursor location. |
+------------------+-------------------------------------------+
| :kbd:`Control-P` | Cursor up; move up one line. |
+------------------+-------------------------------------------+
+------------------+-------------------------------------------+
| Keystroke | Action |
+==================+===========================================+
| :kbd:`Control-A` | Go to left edge of window. |
+------------------+-------------------------------------------+
| :kbd:`Control-B` | Cursor left, wrapping to previous line if |
| | appropriate. |
+------------------+-------------------------------------------+
| :kbd:`Control-D` | Delete character under cursor. |
+------------------+-------------------------------------------+
| :kbd:`Control-E` | Go to right edge (stripspaces off) or end |
| | of line (stripspaces on). |
+------------------+-------------------------------------------+
| :kbd:`Control-F` | Cursor right, wrapping to next line when |
| | appropriate. |
+------------------+-------------------------------------------+
| :kbd:`Control-G` | Terminate, returning the window contents. |
+------------------+-------------------------------------------+
| :kbd:`Control-H` | Delete character backward. |
+------------------+-------------------------------------------+
| :kbd:`Control-J` | Terminate if the window is 1 line, |
| | otherwise insert newline. |
+------------------+-------------------------------------------+
| :kbd:`Control-K` | If line is blank, delete it, otherwise |
| | clear to end of line. |
+------------------+-------------------------------------------+
| :kbd:`Control-L` | Refresh screen. |
+------------------+-------------------------------------------+
| :kbd:`Control-N` | Cursor down; move down one line. |
+------------------+-------------------------------------------+
| :kbd:`Control-O` | Insert a blank line at cursor location. |
+------------------+-------------------------------------------+
| :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
possible. The following synonyms are supported where possible:
Move operations do nothing if the cursor is at an edge where the movement
is not possible. The following synonyms are supported where possible:
+------------------------+------------------+
| Constant | Keystroke |
+========================+==================+
| :const:`KEY_LEFT` | :kbd:`Control-B` |
+------------------------+------------------+
| :const:`KEY_RIGHT` | :kbd:`Control-F` |
+------------------------+------------------+
| :const:`KEY_UP` | :kbd:`Control-P` |
+------------------------+------------------+
| :const:`KEY_DOWN` | :kbd:`Control-N` |
+------------------------+------------------+
| :const:`KEY_BACKSPACE` | :kbd:`Control-h` |
+------------------------+------------------+
+------------------------+------------------+
| Constant | Keystroke |
+========================+==================+
| :const:`KEY_LEFT` | :kbd:`Control-B` |
+------------------------+------------------+
| :const:`KEY_RIGHT` | :kbd:`Control-F` |
+------------------------+------------------+
| :const:`KEY_UP` | :kbd:`Control-P` |
+------------------------+------------------+
| :const:`KEY_DOWN` | :kbd:`Control-N` |
+------------------------+------------------+
| :const:`KEY_BACKSPACE` | :kbd:`Control-h` |
+------------------------+------------------+
All other keystrokes are treated as a command to insert the given character and
move right (with line wrapping).
All other keystrokes are treated as a command to insert the given
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
window are included is affected by the :attr:`stripspaces` member.
This method returns the window contents as a string; whether blanks in the
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
window. When it is on, trailing blanks on each line are ignored; any cursor
motion that would land the cursor on a trailing blank goes to the end of that
line instead, and trailing blanks are stripped when the window contents are
gathered.
This data member is a flag which controls the interpretation of blanks in
the window. When it is on, trailing blanks on each line are ignored; any
cursor motion that would land the cursor on a trailing blank goes to the
end of that line instead, and trailing blanks are stripped when the window
contents are gathered.
:mod:`curses.wrapper` --- Terminal handler for curses programs

File diff suppressed because it is too large Load Diff

View File

@ -350,173 +350,178 @@ The :class:`SequenceMatcher` class has this constructor:
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`.
: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
second sequence, so if you want to compare one sequence against many sequences,
use :meth:`set_seq2` to set the commonly used sequence once and call
:meth:`set_seq1` repeatedly, once for each of the other sequences.
:class:`SequenceMatcher` computes and caches detailed information about the
second sequence, so if you want to compare one sequence against many
sequences, use :meth:`set_seq2` to set the commonly used sequence once and
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
not changed.
Set the first sequence to be compared. The second sequence to be compared
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
not changed.
Set the second sequence to be compared. The first sequence to be compared
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,
k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <=
ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those
conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i ==
i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks,
return one that starts earliest in *a*, and of all those maximal matching blocks
that start earliest in *a*, return the one that starts earliest in *b*.
If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
<= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
<= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
all maximal matching blocks, return one that starts earliest in *a*, and
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.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
If *isjunk* was provided, first the longest matching block is determined as
above, but with the additional restriction that no junk element appears in the
block. Then that block is extended as far as possible by matching (only) junk
elements on both sides. So the resulting block never matches on junk except as
identical junk happens to be adjacent to an interesting match.
If *isjunk* was provided, first the longest matching block is determined
as above, but with the additional restriction that no junk element appears
in the block. Then that block is extended as far as possible by matching
(only) junk elements on both sides. So the resulting block never matches
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
prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second
sequence directly. Instead only the ``'abcd'`` can match, and matches the
leftmost ``'abcd'`` in the second sequence:
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 sequence directly. Instead only the ``'abcd'`` can match, and
matches the leftmost ``'abcd'`` in the second sequence:
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
If no blocks match, this returns ``(alo, blo, 0)``.
If no blocks match, this returns ``(alo, blo, 0)``.
.. versionchanged:: 2.6
This method returns a :term:`named tuple` ``Match(a, b, size)``.
.. versionchanged:: 2.6
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
form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The triples are
monotonically increasing in *i* and *j*.
Return list of triples describing matching subsequences. Each triple is of
the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The
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 only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` are
adjacent triples in the list, and the second is not the last triple in the list,
then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always
describe non-adjacent equal blocks.
The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It
is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')``
are adjacent triples in the list, and the second is not the last triple in
the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
triples always describe non-adjacent equal blocks.
.. XXX Explain why a dummy is used!
.. XXX Explain why a dummy is used!
.. versionchanged:: 2.5
The guarantee that adjacent triples always describe non-adjacent blocks was
implemented.
.. versionchanged:: 2.5
The guarantee that adjacent triples always describe non-adjacent blocks
was implemented.
.. doctest::
.. doctest::
>>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
>>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks()
[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
the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == 0``, and
remaining tuples have *i1* equal to the *i2* from the preceding tuple, and,
likewise, *j1* equal to the previous *j2*.
Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 ==
0``, and remaining tuples have *i1* equal to the *i2* from the preceding
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:
+---------------+---------------------------------------------+
| Value | Meaning |
+===============+=============================================+
| ``'replace'`` | ``a[i1:i2]`` should be replaced by |
| | ``b[j1:j2]``. |
+---------------+---------------------------------------------+
| ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that |
| | ``j1 == j2`` in this case. |
+---------------+---------------------------------------------+
| ``'insert'`` | ``b[j1:j2]`` should be inserted at |
| | ``a[i1:i1]``. Note that ``i1 == i2`` in |
| | this case. |
+---------------+---------------------------------------------+
| ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
| | are equal). |
+---------------+---------------------------------------------+
+---------------+---------------------------------------------+
| Value | Meaning |
+===============+=============================================+
| ``'replace'`` | ``a[i1:i2]`` should be replaced by |
| | ``b[j1:j2]``. |
+---------------+---------------------------------------------+
| ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that |
| | ``j1 == j2`` in this case. |
+---------------+---------------------------------------------+
| ``'insert'`` | ``b[j1:j2]`` should be inserted at |
| | ``a[i1:i1]``. Note that ``i1 == i2`` in |
| | this case. |
+---------------+---------------------------------------------+
| ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
| | are equal). |
+---------------+---------------------------------------------+
For example:
For example:
>>> a = "qabxcd"
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
delete a[0:1] (q) b[0:0] ()
equal a[1:3] (ab) b[0:2] (ab)
replace a[3:4] (x) b[2:3] (y)
equal a[4:6] (cd) b[3:5] (cd)
insert a[6:6] () b[5:6] (f)
>>> a = "qabxcd"
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
delete a[0:1] (q) b[0:0] ()
equal a[1:3] (ab) b[0:2] (ab)
replace a[3:4] (x) b[2:3] (y)
equal a[4:6] (cd) b[3:5] (cd)
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
smaller change clusters and eliminates intervening ranges which have no changes.
Starting with the groups returned by :meth:`get_opcodes`, this method
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`.
.. versionadded:: 2.3
.. versionadded:: 2.3
.. 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
of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the sequences are
identical, and ``0.0`` if they have nothing in common.
Where T is the total number of elements in both sequences, and M is the
number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
sequences are identical, and ``0.0`` if they have nothing in common.
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
try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper bound.
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 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
faster to compute.
This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
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
faster to compute than either :meth:`ratio` or :meth:`quick_ratio`.
This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
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
different results due to differing levels of approximation, although
@ -603,17 +608,17 @@ The :class:`Differ` class has this constructor:
length 1), and returns true if the character is junk. The default is ``None``,
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).
Each sequence must contain individual single-line strings ending with newlines.
Such sequences can be obtained from the :meth:`readlines` method of file-like
objects. The delta generated also consists of newline-terminated strings, ready
to be printed as-is via the :meth:`writelines` method of a file-like object.
Each sequence must contain individual single-line strings ending with newlines.
Such sequences can be obtained from the :meth:`readlines` method of file-like
objects. The delta generated also consists of newline-terminated strings, ready
to be printed as-is via the :meth:`writelines` method of a file-like object.
.. _differ-examples:

View File

@ -1179,48 +1179,48 @@ DocTest Objects
.. versionadded:: 2.4
:class:`DocTest` defines the following member variables. They are initialized
by the constructor, and should not be modified directly.
:class:`DocTest` defines the following member variables. They are initialized by
the constructor, and should not be modified directly.
.. attribute:: DocTest.examples
.. attribute:: examples
A list of :class:`Example` objects encoding the individual interactive Python
examples that should be run by this test.
A list of :class:`Example` objects encoding the individual interactive Python
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
dictionary mapping names to values. Any changes to the namespace made by the
examples (such as binding new variables) will be reflected in :attr:`globs`
after the test is run.
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
examples (such as binding new variables) will be reflected in :attr:`globs`
after the test is run.
.. attribute:: DocTest.name
.. attribute:: name
A string name identifying the :class:`DocTest`. Typically, this is the name of
the object or file that the test was extracted from.
A string name identifying the :class:`DocTest`. Typically, this is the name
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``
if the filename is unknown, or if the :class:`DocTest` was not extracted from a
file.
The name of the file that this :class:`DocTest` was extracted from; or
``None`` if the filename is unknown, or if the :class:`DocTest` was not
extracted from a file.
.. attribute:: DocTest.lineno
.. attribute:: lineno
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
respect to the beginning of the file.
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 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
unavailable, or if the test was not extracted from a string.
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.
.. _doctest-example:
@ -1237,53 +1237,53 @@ Example Objects
.. versionadded:: 2.4
:class:`Example` defines the following member variables. They are initialized
by the constructor, and should not be modified directly.
:class:`Example` defines the following member variables. They are initialized by
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
single Python statement, and always ends with a newline; the constructor adds a
newline when necessary.
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 newline when necessary.
.. attribute:: Example.want
.. attribute:: want
The expected output from running the example's source code (either from stdout,
or a traceback in case of exception). :attr:`want` ends with a newline unless
no output is expected, in which case it's an empty string. The constructor adds
a newline when necessary.
The expected output from running the example's source code (either from
stdout, or a traceback in case of exception). :attr:`want` ends with a
newline unless no output is expected, in which case it's an empty string. The
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
generate an exception; or ``None`` if it is not expected to generate an
exception. This exception message is compared against the return value of
:func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline
unless it's ``None``. The constructor adds a newline if needed.
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
exception. This exception message is compared against the return value of
:func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline
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
begins. This line number is zero-based with respect to the beginning of the
containing string.
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
containing string.
.. attribute:: Example.indent
.. attribute:: indent
The example's indentation in the containing string, i.e., the number of space
characters that precede the example's first prompt.
The example's indentation in the containing string, i.e., the number of space
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
to override default options for this example. Any option flags not contained in
this dictionary are left at their default value (as specified by the
:class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
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 this dictionary are left at their default value (as specified by the
:class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
.. _doctest-doctestfinder:
@ -1314,44 +1314,44 @@ DocTestFinder objects
.. versionadded:: 2.4
: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,
or by any of its contained objects' docstrings.
Return a list of the :class:`DocTest`\ s that are defined by *obj*'s
docstring, or by any of its contained objects' docstrings.
The optional argument *name* specifies the object's name; this name will be used
to construct names for the returned :class:`DocTest`\ s. If *name* is not
specified, then ``obj.__name__`` is used.
The optional argument *name* specifies the object's name; this name will be
used to construct names for the returned :class:`DocTest`\ s. If *name* is
not specified, then ``obj.__name__`` is used.
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
automatically determine the correct module. The object's module is used:
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 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.
* To prevent the DocTestFinder from extracting DocTests from objects that are
imported from other modules. (Contained objects with modules other than
*module* are ignored.)
* To prevent the DocTestFinder from extracting DocTests from objects that are
imported from other modules. (Contained objects with modules other than
*module* are ignored.)
* To find the name of the file containing the object.
* To find the name of the file containing the object.
* To help find the line number of the object within its file.
* To help find the line number of the object within its file.
If *module* is ``False``, no attempt to find the module will be made. This is
obscure, of use mostly in testing doctest itself: if *module* is ``False``, or
is ``None`` but cannot be found automatically, then all objects are considered
to belong to the (non-existent) module, so all contained objects will
(recursively) be searched for doctests.
If *module* is ``False``, no attempt to find the module will be made. This is
obscure, of use mostly in testing doctest itself: if *module* is ``False``, or
is ``None`` but cannot be found automatically, then all objects are considered
to belong to the (non-existent) module, so all contained objects will
(recursively) be searched for doctests.
The globals for each :class:`DocTest` is formed by combining *globs* and
*extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
shallow copy of the globals dictionary is created for each :class:`DocTest`. If
*globs* is not specified, then it defaults to the module's *__dict__*, if
specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
defaults to ``{}``.
The globals for each :class:`DocTest` is formed by combining *globs* and
*extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
shallow copy of the globals dictionary is created for each :class:`DocTest`.
If *globs* is not specified, then it defaults to the module's *__dict__*, if
specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
defaults to ``{}``.
.. _doctest-doctestparser:
@ -1367,32 +1367,32 @@ DocTestParser objects
.. versionadded:: 2.4
: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
:class:`DocTest` object.
Extract all doctest examples from the given string, and collect them into a
:class:`DocTest` object.
*globs*, *name*, *filename*, and *lineno* are attributes for the new
:class:`DocTest` object. See the documentation for :class:`DocTest` for more
information.
*globs*, *name*, *filename*, and *lineno* are attributes for the new
:class:`DocTest` object. See the documentation for :class:`DocTest` for more
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
: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.
Extract all doctest examples from the given string, and return them as a list
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.
.. method:: DocTestParser.parse(string[, name])
.. method:: parse(string[, name])
Divide the given string into examples and intervening text, and return them as 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
identifying this string, and is only used for error messages.
Divide the given string into examples and intervening text, and return them as
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
identifying this string, and is only used for error messages.
.. _doctest-doctestrunner:
@ -1436,83 +1436,84 @@ DocTestRunner objects
.. versionadded:: 2.4
: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
is provided to allow subclasses of :class:`DocTestRunner` to customize their
output; it should not be called directly.
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
output; it should not be called directly.
*example* is the example about to be processed. *test* is the test containing
*example*. *out* is the output function that was passed to
:meth:`DocTestRunner.run`.
*example* is the example about to be processed. *test* is the test
*containing example*. *out* is the output function that was passed to
: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
allow subclasses of :class:`DocTestRunner` to customize their output; it should
not be called directly.
Report that the given example ran successfully. This method is provided to
allow subclasses of :class:`DocTestRunner` to customize their output; it
should not be called directly.
*example* is the example about to be processed. *got* is the actual output from
the example. *test* is the test containing *example*. *out* is the output
function that was passed to :meth:`DocTestRunner.run`.
*example* is the example about to be processed. *got* is the actual output
from the example. *test* is the test containing *example*. *out* is the
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
subclasses of :class:`DocTestRunner` to customize their output; it should not be
called directly.
Report that the given example failed. This method is provided to allow
subclasses of :class:`DocTestRunner` to customize their output; it should not
be called directly.
*example* is the example about to be processed. *got* is the actual output from
the example. *test* is the test containing *example*. *out* is the output
function that was passed to :meth:`DocTestRunner.run`.
*example* is the example about to be processed. *got* is the actual output
from the example. *test* is the test containing *example*. *out* is the
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
provided to allow subclasses of :class:`DocTestRunner` to customize their
output; it should not be called directly.
Report that the given example raised an unexpected exception. This method is
provided to allow subclasses of :class:`DocTestRunner` to customize their
output; it should not be called directly.
*example* is the example about to be processed. *exc_info* is a tuple containing
information about the unexpected exception (as returned by
:func:`sys.exc_info`). *test* is the test containing *example*. *out* is the
output function that was passed to :meth:`DocTestRunner.run`.
*example* is the example about to be processed. *exc_info* is a tuple
containing information about the unexpected exception (as returned by
:func:`sys.exc_info`). *test* is the test containing *example*. *out* is the
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
using the writer function *out*.
Run the examples in *test* (a :class:`DocTest` object), and display the
results using the writer function *out*.
The examples are run in the namespace ``test.globs``. If *clear_globs* is true
(the default), then this namespace will be cleared after the test runs, to help
with garbage collection. If you would like to examine the namespace after the
test completes, then use *clear_globs=False*.
The examples are run in the namespace ``test.globs``. If *clear_globs* is
true (the default), then this namespace will be cleared after the test runs,
to help with garbage collection. If you would like to examine the namespace
after the test completes, then use *clear_globs=False*.
*compileflags* gives the set of flags that should be used by the Python compiler
when running the examples. If not specified, then it will default to the set of
future-import flags that apply to *globs*.
*compileflags* gives the set of flags that should be used by the Python
compiler when running the examples. If not specified, then it will default to
the set of future-import flags that apply to *globs*.
The output of each example is checked using the :class:`DocTestRunner`'s output
checker, and the results are formatted by the :meth:`DocTestRunner.report_\*`
methods.
The output of each example is checked using the :class:`DocTestRunner`'s
output checker, and the results are formatted by the
: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,
and return a :term:`named tuple` ``TestResults(failed, attempted)``.
Print a summary of all the test cases that have been run by this DocTestRunner,
and return a :term:`named tuple` ``TestResults(failed, attempted)``.
The optional *verbose* argument controls how detailed the summary is. If the
verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used.
The optional *verbose* argument controls how detailed the summary is. If the
verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
used.
.. versionchanged:: 2.6
Use a named tuple.
.. versionchanged:: 2.6
Use a named tuple.
.. _doctest-outputchecker:
@ -1531,23 +1532,23 @@ OutputChecker objects
.. versionadded:: 2.4
: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
expected output (*want*). These strings are always considered to match if they
are identical; but depending on what option flags the test runner is using,
several non-exact match types are also possible. See section
:ref:`doctest-options` for more information about option flags.
Return ``True`` iff the actual output from an example (*got*) matches the
expected output (*want*). These strings are always considered to match if
they are identical; but depending on what option flags the test runner is
using, several non-exact match types are also possible. See section
: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
given example (*example*) and the actual output (*got*). *optionflags* is the
set of option flags used to compare *want* and *got*.
Return a string describing the differences between the expected output for a
given example (*example*) and the actual output (*got*). *optionflags* is the
set of option flags used to compare *want* and *got*.
.. _doctest-debugging:

View File

@ -40,164 +40,168 @@ Import this class from the :mod:`email.charset` module.
will not be encoded, but output text will be converted from the ``euc-jp``
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
*official* email names (e.g. ``latin_1`` is converted to ``iso-8859-1``).
Defaults to 7-bit ``us-ascii``.
The initial character set specified. Common aliases are converted to
their *official* email names (e.g. ``latin_1`` is converted to
``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,
this attribute will be set to ``Charset.QP`` (for quoted-printable),
``Charset.BASE64`` (for base64 encoding), or ``Charset.SHORTEST`` for the
shortest of QP or BASE64 encoding. Otherwise, it will be ``None``.
If the character set must be encoded before it can be used in an email
header, this attribute will be set to ``Charset.QP`` (for
quoted-printable), ``Charset.BASE64`` (for base64 encoding), or
``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
body, which indeed may be different than the header encoding.
``Charset.SHORTEST`` is not allowed for *body_encoding*.
Same as *header_encoding*, but describes the encoding for the mail
message's body, which indeed may be different than the header 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
or bodies. If the *input_charset* is one of them, this attribute will contain
the name of the character set output will be converted to. Otherwise, it will
be ``None``.
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 the name of the character set output will be converted to. Otherwise, it will
be ``None``.
.. data:: input_codec
.. attribute:: input_codec
The name of the Python codec used to convert the *input_charset* to Unicode. If
no conversion codec is necessary, this attribute will be ``None``.
The name of the Python codec used to convert the *input_charset* to
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*.
If no conversion codec is necessary, this attribute will have the same value as
the *input_codec*.
The name of the Python codec used to convert Unicode to the
*output_charset*. If no conversion codec is necessary, this attribute
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
encoding used, or it is a function, in which case you should call the function
with a single argument, the Message object being encoded. The function should
then set the :mailheader:`Content-Transfer-Encoding` header itself to whatever
is appropriate.
This is either the string ``quoted-printable`` or ``base64`` depending on
the encoding used, or it is a function, in which case you should call the
function with a single argument, the Message object being encoded. The
function should then set the :mailheader:`Content-Transfer-Encoding`
header itself to whatever is appropriate.
Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, returns
the string ``base64`` if *body_encoding* is ``BASE64``, and returns the string
``7bit`` otherwise.
Returns the string ``quoted-printable`` if *body_encoding* is ``QP``,
returns the string ``base64`` if *body_encoding* is ``BASE64``, and
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
string to split.
Convert a possibly multibyte string to a safely splittable format. *s* is
the string to split.
Uses the *input_codec* to try and convert the string to Unicode, so it can be
safely split on character boundaries (even for multibyte characters).
Uses the *input_codec* to try and convert the string to Unicode, so it can
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
the *input_charset*.
Returns the string as-is if it isn't known how to convert *s* to Unicode
with the *input_charset*.
Characters that could not be converted to Unicode will be replaced with the
Unicode replacement character ``'U+FFFD'``.
Characters that could not be converted to Unicode will be replaced with
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
string to "unsplit".
Convert a splittable string back into an encoded string. *ustr* is a
Unicode string to "unsplit".
This method uses the proper codec to try and convert the string from Unicode
back into an encoded format. Return the string as-is if it is not Unicode, or
if it could not be converted from Unicode.
This method uses the proper codec to try and convert the string from
Unicode back into an encoded format. Return the string as-is if it is not
Unicode, or if it could not be converted from Unicode.
Characters that could not be converted from Unicode will be replaced with an
appropriate character (usually ``'?'``).
Characters that could not be converted from Unicode will be replaced with
an appropriate character (usually ``'?'``).
If *to_output* is ``True`` (the default), uses *output_codec* to convert to an
encoded format. If *to_output* is ``False``, it uses *input_codec*.
If *to_output* is ``True`` (the default), uses *output_codec* to convert
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
*input_charset*.
This is the *output_charset* attribute if that is not ``None``, otherwise
it is *input_charset*.
.. method:: Charset.encoded_header_len()
.. method:: encoded_header_len()
Return the length of the encoded header string, properly calculating for
quoted-printable or base64 encoding.
Return the length of the encoded header string, properly calculating for
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
the output charset automatically. This is not useful for multibyte character
sets, which have line length issues (multibyte characters must be split on a
character, not a byte boundary); use the higher-level :class:`Header` class to
deal with these issues (see :mod:`email.header`). *convert* defaults to
``False``.
If *convert* is ``True``, the string will be converted from the input
charset to the output charset automatically. This is not useful for
multibyte character sets, which have line length issues (multibyte
characters must be split on a character, not a byte boundary); use the
higher-level :class:`Header` class to deal with these issues (see
:mod:`email.header`). *convert* defaults to ``False``.
The type of encoding (base64 or quoted-printable) will be based on the
*header_encoding* attribute.
The type of encoding (base64 or quoted-printable) will be based on the
*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
input charset to output charset automatically. Unlike :meth:`header_encode`,
there are no issues with byte boundaries and multibyte charsets in email bodies,
so this is usually pretty safe.
If *convert* is ``True`` (the default), the string will be converted from
the input charset to output charset automatically. Unlike
:meth:`header_encode`, there are no issues with byte boundaries and
multibyte charsets in email bodies, so this is usually pretty safe.
The type of encoding (base64 or quoted-printable) will be based on the
*body_encoding* attribute.
The type of encoding (base64 or quoted-printable) will be based on the
*body_encoding* attribute.
The :class:`Charset` class also provides a number of methods to support standard
operations and built-in functions.
The :class:`Charset` class also provides a number of methods to support
standard operations and built-in functions.
.. method:: Charset.__str__()
.. method:: __str__()
Returns *input_charset* as a string coerced to lower case. :meth:`__repr__` is
an alias for :meth:`__str__`.
Returns *input_charset* as a string coerced to lower
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
new entries to the global character set, alias, and codec registries:

View File

@ -44,39 +44,40 @@ 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
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*
to the output file specified when the :class:`Generator` instance was created.
Subparts are visited depth-first and the resulting text will be properly MIME
encoded.
Print the textual representation of the message object structure rooted at
*msg* to the output file specified when the :class:`Generator` instance
was created. Subparts are visited depth-first and the resulting text will
be properly MIME encoded.
Optional *unixfrom* is a flag that forces the printing of the envelope header
delimiter before the first :rfc:`2822` header of the root message object. If
the root object has no envelope header, a standard one is crafted. By default,
this is set to ``False`` to inhibit the printing of the envelope delimiter.
Optional *unixfrom* is a flag that forces the printing of the envelope
header delimiter before the first :rfc:`2822` header of the root message
object. If the root object has no envelope header, a standard one is
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.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Generator.clone(fp)
.. method:: 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 same options.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Generator.write(s)
.. method:: write(s)
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` instances to be used in extended print statements.
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` instances to be used in extended print statements.
As a convenience, see the methods :meth:`Message.as_string` and
``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation

View File

@ -76,65 +76,67 @@ Here is the :class:`Header` class description:
and is usually either a space or a hard tab character. This character will be
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
:mod:`email.charset`) or the name of a character set, which will be converted to
a :class:`Charset` instance. A value of ``None`` (the default) means that the
*charset* given in the constructor is used.
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 a :class:`Charset` instance. A value of ``None`` (the
default) means that the *charset* given in the constructor is used.
*s* may be a byte string or a Unicode string. If it is a byte string (i.e.
``isinstance(s, str)`` is true), then *charset* is the encoding of that byte
string, and a :exc:`UnicodeError` will be raised if the string cannot be decoded
with that character set.
*s* may be a byte string or a Unicode string. If it is a byte string
(i.e. ``isinstance(s, str)`` is true), then *charset* is the encoding of
that byte string, and a :exc:`UnicodeError` will be raised if the string
cannot be decoded with that character set.
If *s* is a Unicode string, then *charset* is a hint specifying the character
set of the characters in the string. In this case, when producing an
:rfc:`2822`\ -compliant header using :rfc:`2047` rules, the Unicode string will
be encoded using the following charsets in order: ``us-ascii``, the *charset*
hint, ``utf-8``. The first character set to not provoke a :exc:`UnicodeError`
is used.
If *s* is a Unicode string, then *charset* is a hint specifying the
character set of the characters in the string. In this case, when
producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the
Unicode string will be encoded using the following charsets in order:
``us-ascii``, the *charset* hint, ``utf-8``. The first character set to
not provoke a :exc:`UnicodeError` is used.
Optional *errors* is passed through to any :func:`unicode` or
:func:`ustr.encode` call, and defaults to "strict".
Optional *errors* is passed through to any :func:`unicode` or
: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
lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings.
Optional *splitchars* is a string containing characters to split long ASCII
lines on, in rough support of :rfc:`2822`'s *highest level syntactic breaks*.
This doesn't affect :rfc:`2047` encoded lines.
Encode a message header into an RFC-compliant format, possibly wrapping
long lines and encapsulating non-ASCII parts in base64 or quoted-printable
encodings. Optional *splitchars* is a string containing characters to
split long ASCII lines on, in rough support of :rfc:`2822`'s *highest
level syntactic breaks*. This doesn't affect :rfc:`2047` encoded lines.
The :class:`Header` class also provides a number of methods to support standard
operators and built-in functions.
The :class:`Header` class also provides a number of methods to support
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 the built-in :func:`unicode` function. Returns the header as a
Unicode string.
A helper for the built-in :func:`unicode` function. Returns the header as
a Unicode string.
.. method:: Header.__eq__(other)
.. method:: __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:: Header.__ne__(other)
.. method:: __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.

View File

@ -36,513 +36,532 @@ Here are the methods of the :class:`Message` class:
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
``True``, the envelope header is included in the returned string. *unixfrom*
defaults to ``False``.
Return the entire message flattened as a string. When optional *unixfrom*
is ``True``, the envelope header is included in the returned string.
*unixfrom* defaults to ``False``.
Note that this method is provided as a convenience and may not always format the
message the way you want. For example, by default it mangles lines that begin
with ``From``. For more flexibility, instantiate a :class:`Generator` instance
and use its :meth:`flatten` method directly. For example::
Note that this method is provided as a convenience and may not always
format the message the way you want. For example, by default it mangles
lines that begin with ``From``. For more flexibility, instantiate a
:class:`Generator` instance and use its :meth:`flatten` method directly.
For example::
from cStringIO import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=False, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
from cStringIO import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=False, maxheaderlen=60)
g.flatten(msg)
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`
objects, otherwise return ``False``. When :meth:`is_multipart` returns False,
the payload should be a string object.
Return ``True`` if the message's payload is a list of sub-\
:class:`Message` objects, otherwise return ``False``. When
: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
header was never set.
Return the message's envelope header. Defaults to ``None`` if the
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
of :class:`Message` objects before the call. After the call, the payload will
always be a list of :class:`Message` objects. If you want to set the payload to
a scalar object (e.g. a string), use :meth:`set_payload` instead.
Add the given *payload* to the current payload, which must be ``None`` or
a list of :class:`Message` objects before the call. After the call, the
payload will always be a list of :class:`Message` objects. If you want to
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`
objects when :meth:`is_multipart` is ``True``, or a string when
:meth:`is_multipart` is ``False``. If the payload is a list and you mutate the
list object, you modify the message's payload in place.
Return a reference the current payload, which will be a list of
:class:`Message` objects when :meth:`is_multipart` is ``True``, or a
string when :meth:`is_multipart` is ``False``. If the payload is a list
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
of the payload, counting from zero, if :meth:`is_multipart` is ``True``. An
:exc:`IndexError` will be raised if *i* is less than 0 or greater than or equal
to the number of items in the payload. If the payload is a string (i.e.
:meth:`is_multipart` is ``False``) and *i* is given, a :exc:`TypeError` is
raised.
With optional argument *i*, :meth:`get_payload` will return the *i*-th
element of the payload, counting from zero, if :meth:`is_multipart` is
``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or
greater than or equal to the number of items in the payload. If the
payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is
given, a :exc:`TypeError` is raised.
Optional *decode* is a flag indicating whether the payload should be decoded or
not, according to the :mailheader:`Content-Transfer-Encoding` header. When
``True`` and the message is not a multipart, the payload will be decoded if this
header's value is ``quoted-printable`` or ``base64``. If some other encoding is
used, or :mailheader:`Content-Transfer-Encoding` header is missing, or if the
payload has bogus base64 data, the payload is returned as-is (undecoded). If
the message is a multipart and the *decode* flag is ``True``, then ``None`` is
returned. The default for *decode* is ``False``.
Optional *decode* is a flag indicating whether the payload should be
decoded or not, according to the :mailheader:`Content-Transfer-Encoding`
header. When ``True`` and the message is not a multipart, the payload will
be decoded if this header's value is ``quoted-printable`` or ``base64``.
If some other encoding is used, or :mailheader:`Content-Transfer-Encoding`
header is missing, or if the payload has bogus base64 data, the payload is
returned as-is (undecoded). If the message is a multipart and the
*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
responsibility to ensure the payload invariants. Optional *charset* sets the
message's default character set; see :meth:`set_charset` for details.
Set the entire message object's payload to *payload*. It is the client's
responsibility to ensure the payload invariants. Optional *charset* sets
the message's default character set; see :meth:`set_charset` for details.
.. versionchanged:: 2.2.2
*charset* argument added.
.. versionchanged:: 2.2.2
*charset* argument added.
.. method:: Message.set_charset(charset)
.. method:: set_charset(charset)
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
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
will be removed from the :mailheader:`Content-Type` header. Anything else will
generate a :exc:`TypeError`.
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
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 will be removed from the :mailheader:`Content-Type`
header. Anything else will generate a :exc:`TypeError`.
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
encoded properly, if needed, when generating the plain text representation of
the message. MIME headers (:mailheader:`MIME-Version`,
:mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will be
added as needed.
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 encoded properly, if needed, when generating the plain text
representation of the message. MIME headers (:mailheader:`MIME-Version`,
:mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will
be added as needed.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. 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.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
The following methods implement a mapping-like interface for accessing the
message's :rfc:`2822` headers. Note that there are some semantic differences
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
duplicate message headers. Also, in dictionaries there is no guaranteed order
to the keys returned by :meth:`keys`, but in a :class:`Message` object, headers
are always returned in the order they appeared in the original message, or were
added to the message later. Any header deleted and then re-added are always
appended to the end of the header list.
The following methods implement a mapping-like interface for accessing the
message's :rfc:`2822` headers. Note that there are some semantic differences
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
duplicate message headers. Also, in dictionaries there is no guaranteed
order to the keys returned by :meth:`keys`, but in a :class:`Message` object,
headers are always returned in the order they appeared in the original
message, or were added to the message later. Any header deleted and then
re-added are always appended to the end of the header list.
These semantic differences are intentional and are biased toward maximal
convenience.
These semantic differences are intentional and are biased toward maximal
convenience.
Note that in all cases, any envelope header present in the message is not
included in the mapping interface.
Note that in all cases, any envelope header present in the message is not
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
case-insensitively and *name* should not include the trailing colon. Used for
the ``in`` operator, e.g.::
Return true if the message object has a field named *name*. Matching is
done case-insensitively and *name* should not include the trailing colon.
Used for the ``in`` operator, e.g.::
if 'message-id' in myMessage:
print 'Message-ID:', myMessage['message-id']
if 'message-id' in myMessage:
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
field separator. If the header is missing, ``None`` is returned; a
:exc:`KeyError` is never raised.
Return the value of the named header field. *name* should not include the
colon field separator. If the header is missing, ``None`` is returned; a
:exc:`KeyError` is never raised.
Note that if the named field appears more than once in the message's headers,
exactly which of those field values will be returned is undefined. Use the
:meth:`get_all` method to get the values of all the extant named headers.
Note that if the named field appears more than once in the message's
headers, exactly which of those field values will be returned is
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
is appended to the end of the message's existing fields.
Add a header to the message with field name *name* and value *val*. The
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
name. If you want to ensure that the new header is the only one present in the
message with field name *name*, delete the field first, e.g.::
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
message with field name *name*, delete the field first, e.g.::
del msg['subject']
msg['subject'] = 'Python roolz!'
del msg['subject']
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.
No exception is raised if the named field isn't present in the headers.
Delete all occurrences of the field with name *name* from the message's
headers. No exception is raised if the named field isn't present in the headers.
.. method:: Message.has_key(name)
.. method:: has_key(name)
Return true if the message contains a header field named *name*, otherwise
return false.
Return true if the message contains a header field named *name*, otherwise
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
:meth:`__getitem__` except that optional *failobj* is returned if the named
header is missing (defaults to ``None``).
Return the value of the named header field. This is identical to
:meth:`__getitem__` except that optional *failobj* is returned if the
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
named headers in the message, *failobj* is returned (defaults to ``None``).
Return a list of all the values for the field named *name*. If there are
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
that additional header parameters can be provided as keyword arguments. *_name*
is the header field to add and *_value* is the *primary* value for the header.
Extended header setting. This method is similar to :meth:`__setitem__`
except that additional header parameters can be provided as keyword
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
the parameter name, with underscores converted to dashes (since dashes are
illegal in Python identifiers). Normally, the parameter will be added as
``key="value"`` unless the value is ``None``, in which case only the key will be
added.
For each item in the keyword argument dictionary *_params*, the key is
taken as the parameter name, with underscores converted to dashes (since
dashes are illegal in Python identifiers). Normally, the parameter will
be added as ``key="value"`` unless the value is ``None``, in which case
only the key will be added.
Here's an example::
Here's an example::
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
This will add a header that looks like ::
This will add a header that looks like ::
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
*_name*, retaining header order and field name case. If no matching header was
found, a :exc:`KeyError` is raised.
Replace a header. Replace the first header found in the message that
matches *_name*, retaining header order and field name case. If no
matching header was found, a :exc:`KeyError` is raised.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.get_content_type()
.. method:: get_content_type()
Return the message's content type. The returned string is coerced to 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
:meth:`get_default_type` will be returned. Since according to :rfc:`2045`,
messages always have a default type, :meth:`get_content_type` will always return
a value.
Return the message's content type. The returned string is coerced to
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 :meth:`get_default_type` will be returned. Since according to
:rfc:`2045`, messages always have a default type, :meth:`get_content_type`
will always return a value.
:rfc:`2045` defines a message's default type to be :mimetype:`text/plain` unless
it appears inside a :mimetype:`multipart/digest` container, in which case it
would be :mimetype:`message/rfc822`. If the :mailheader:`Content-Type` header
has an invalid type specification, :rfc:`2045` mandates that the default type be
:mimetype:`text/plain`.
:rfc:`2045` defines a message's default type to be :mimetype:`text/plain`
unless it appears inside a :mimetype:`multipart/digest` container, in
which case it would be :mimetype:`message/rfc822`. If the
:mailheader:`Content-Type` header has an invalid type specification,
:rfc:`2045` mandates that the default type be :mimetype:`text/plain`.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.get_content_maintype()
.. method:: get_content_maintype()
Return the message's main content type. This is the :mimetype:`maintype` part
of the string returned by :meth:`get_content_type`.
Return the message's main content type. This is the :mimetype:`maintype`
part of the string returned by :meth:`get_content_type`.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.get_content_subtype()
.. method:: get_content_subtype()
Return the message's sub-content type. This is the :mimetype:`subtype` part of
the string returned by :meth:`get_content_type`.
Return the message's sub-content type. This is the :mimetype:`subtype`
part of the string returned by :meth:`get_content_type`.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.get_default_type()
.. method:: get_default_type()
Return the default content type. Most messages have a default content type of
:mimetype:`text/plain`, except for messages that are subparts of
:mimetype:`multipart/digest` containers. Such subparts have a default content
type of :mimetype:`message/rfc822`.
Return the default content type. Most messages have a default content
type of :mimetype:`text/plain`, except for messages that are subparts of
:mimetype:`multipart/digest` containers. Such subparts have a default
content type of :mimetype:`message/rfc822`.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.set_default_type(ctype)
.. method:: set_default_type(ctype)
Set the default content type. *ctype* should either be :mimetype:`text/plain`
or :mimetype:`message/rfc822`, although this is not enforced. The default
content type is not stored in the :mailheader:`Content-Type` header.
Set the default content type. *ctype* should either be
:mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not
enforced. The default content type is not stored in the
:mailheader:`Content-Type` header.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. 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
elements of the returned list are 2-tuples of key/value pairs, as split on the
``'='`` sign. The left hand side of the ``'='`` is the key, while the right
hand side is the value. If there is no ``'='`` sign in the parameter the value
is the empty string, otherwise the value is as described in :meth:`get_param`
and is unquoted if optional *unquote* is ``True`` (the default).
Return the message's :mailheader:`Content-Type` parameters, as a list.
The elements of the returned list are 2-tuples of key/value pairs, as
split on the ``'='`` sign. The left hand side of the ``'='`` is the key,
while the right hand side is the value. If there is no ``'='`` sign in
the parameter the value is the empty string, otherwise the value is as
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
:mailheader:`Content-Type` header. Optional *header* is the header to search
instead of :mailheader:`Content-Type`.
Optional *failobj* is the object to return if there is no
:mailheader:`Content-Type` header. Optional *header* is the header to
search instead of :mailheader:`Content-Type`.
.. versionchanged:: 2.2.2
*unquote* argument added.
.. versionchanged:: 2.2.2
*unquote* argument added.
.. 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
a string. If the message has no :mailheader:`Content-Type` header or if there
is no such parameter, then *failobj* is returned (defaults to ``None``).
Return the value of the :mailheader:`Content-Type` header's parameter
*param* as a string. If the message has no :mailheader:`Content-Type`
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
:mailheader:`Content-Type`.
Optional *header* if given, specifies the message header to use instead of
:mailheader:`Content-Type`.
Parameter keys are always compared case insensitively. The return value can
either be a string, or a 3-tuple if the parameter was :rfc:`2231` encoded. When
it's a 3-tuple, the elements of the value are of the form ``(CHARSET, LANGUAGE,
VALUE)``. Note that both ``CHARSET`` and ``LANGUAGE`` can be ``None``, in which
case you should consider ``VALUE`` to be encoded in the ``us-ascii`` charset.
You can usually ignore ``LANGUAGE``.
Parameter keys are always compared case insensitively. The return value
can either be a string, or a 3-tuple if the parameter was :rfc:`2231`
encoded. When it's a 3-tuple, the elements of the value are of the form
``(CHARSET, LANGUAGE, VALUE)``. Note that both ``CHARSET`` and
``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE``
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
:rfc:`2231`, you can collapse the parameter value by calling
:func:`email.Utils.collapse_rfc2231_value`, passing in the return value from
:meth:`get_param`. This will return a suitably decoded Unicode string whn the
value is a tuple, or the original string unquoted if it isn't. For example::
If your application doesn't care whether the parameter was encoded as in
:rfc:`2231`, you can collapse the parameter value by calling
:func:`email.Utils.collapse_rfc2231_value`, passing in the return value
from :meth:`get_param`. This will return a suitably decoded Unicode
string whn the value is a tuple, or the original string unquoted if it
isn't. For example::
rawparam = msg.get_param('foo')
param = email.Utils.collapse_rfc2231_value(rawparam)
rawparam = msg.get_param('foo')
param = email.Utils.collapse_rfc2231_value(rawparam)
In any case, the parameter value (either the returned string, or the ``VALUE``
item in the 3-tuple) is always unquoted, unless *unquote* is set to ``False``.
In any case, the parameter value (either the returned string, or the
``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set
to ``False``.
.. versionchanged:: 2.2.2
*unquote* argument added, and 3-tuple return value possible.
.. versionchanged:: 2.2.2
*unquote* argument added, and 3-tuple return value possible.
.. 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
already exists in the header, its value will be replaced with *value*. If the
:mailheader:`Content-Type` header as not yet been defined for this message, it
will be set to :mimetype:`text/plain` and the new parameter value will be
appended as per :rfc:`2045`.
Set a parameter in the :mailheader:`Content-Type` header. If the
parameter already exists in the header, its value will be replaced with
*value*. If the :mailheader:`Content-Type` header as not yet been defined
for this message, it will be set to :mimetype:`text/plain` and the new
parameter value will be appended as per :rfc:`2045`.
Optional *header* specifies an alternative header to :mailheader:`Content-Type`,
and all parameters will be quoted as necessary unless optional *requote* is
``False`` (the default is ``True``).
Optional *header* specifies an alternative header to
:mailheader:`Content-Type`, and all parameters will be quoted as necessary
unless optional *requote* is ``False`` (the default is ``True``).
If optional *charset* is specified, the parameter will be encoded according to
:rfc:`2231`. Optional *language* specifies the RFC 2231 language, defaulting to
the empty string. Both *charset* and *language* should be strings.
If optional *charset* is specified, the parameter will be encoded
according to :rfc:`2231`. Optional *language* specifies the RFC 2231
language, defaulting to the empty string. Both *charset* and *language*
should be strings.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.del_param(param[, header[, requote]])
.. method:: del_param(param[, header[, requote]])
Remove the given parameter completely from the :mailheader:`Content-Type`
header. The header will be re-written in place without the parameter or its
value. All values will be quoted as necessary unless *requote* is ``False``
(the default is ``True``). Optional *header* specifies an alternative to
: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 value. All values will be quoted as necessary unless *requote* is
``False`` (the default is ``True``). Optional *header* specifies an
alternative to :mailheader:`Content-Type`.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. 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*
must be a string in the form :mimetype:`maintype/subtype`, otherwise a
:exc:`ValueError` is raised.
Set the main type and subtype for the :mailheader:`Content-Type`
header. *type* must be a string in the form :mimetype:`maintype/subtype`,
otherwise a :exc:`ValueError` is raised.
This method replaces the :mailheader:`Content-Type` header, keeping all the
parameters in place. If *requote* is ``False``, this leaves the existing
header's quoting as is, otherwise the parameters will be quoted (the default).
This method replaces the :mailheader:`Content-Type` header, keeping all
the parameters in place. If *requote* is ``False``, this leaves the
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
:mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` header is
also added.
An alternative header can be specified in the *header* argument. When the
:mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
header is also added.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.get_filename([failobj])
.. method:: get_filename([failobj])
Return the value of the ``filename`` parameter of the
:mailheader:`Content-Disposition` header of the message. If the header does not
have a ``filename`` parameter, this method falls back to looking for the
``name`` parameter. If neither is found, or the header is missing, then
*failobj* is returned. The returned string will always be unquoted as per
:meth:`Utils.unquote`.
Return the value of the ``filename`` parameter of the
:mailheader:`Content-Disposition` header of the message. If the header
does not have a ``filename`` parameter, this method falls back to looking
for the ``name`` parameter. If neither is found, or the header is
missing, then *failobj* is returned. The returned string will always be
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`
header of the message, or *failobj* if either the header is missing, or has no
``boundary`` parameter. The returned string will always be unquoted as per
:meth:`Utils.unquote`.
Return the value of the ``boundary`` parameter of the
:mailheader:`Content-Type` header of the message, or *failobj* if either
the header is missing, or has no ``boundary`` parameter. The returned
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
*boundary*. :meth:`set_boundary` will always quote *boundary* if necessary. A
:exc:`HeaderParseError` is raised if the message object has no
:mailheader:`Content-Type` header.
Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to
*boundary*. :meth:`set_boundary` will always quote *boundary* if
necessary. A :exc:`HeaderParseError` is raised if the message object has
no :mailheader:`Content-Type` header.
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
:meth:`add_header`, because :meth:`set_boundary` preserves the order of the
:mailheader:`Content-Type` header in the list of headers. However, it does *not*
preserve any continuation lines which may have been present in the original
:mailheader:`Content-Type` header.
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 :meth:`add_header`, because :meth:`set_boundary` preserves
the order of the :mailheader:`Content-Type` header in the list of
headers. However, it does *not* preserve any continuation lines which may
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,
coerced to lower case. If there is no :mailheader:`Content-Type` header, or if
that header has no ``charset`` parameter, *failobj* is returned.
Return the ``charset`` parameter of the :mailheader:`Content-Type` header,
coerced to lower case. If there is no :mailheader:`Content-Type` header, or if
that header has no ``charset`` parameter, *failobj* is returned.
Note that this method differs from :meth:`get_charset` which returns the
:class:`Charset` instance for the default encoding of the message body.
Note that this method differs from :meth:`get_charset` which returns the
:class:`Charset` instance for the default encoding of the message body.
.. versionadded:: 2.2.2
.. versionadded:: 2.2.2
.. method:: Message.get_charsets([failobj])
.. method:: get_charsets([failobj])
Return a list containing the character set names in the message. If the message
is a :mimetype:`multipart`, then the list will contain one element for each
subpart in the payload, otherwise, it will be a list of length 1.
Return a list containing the character set names in the message. If the
message is a :mimetype:`multipart`, then the list will contain one element
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``
parameter in the :mailheader:`Content-Type` header for the represented subpart.
However, if the subpart has no :mailheader:`Content-Type` header, no ``charset``
parameter, or is not of the :mimetype:`text` main MIME type, then that item in
the returned list will be *failobj*.
Each item in the list will be a string which is the value of the
``charset`` parameter in the :mailheader:`Content-Type` header for the
represented subpart. However, if the subpart has no
:mailheader:`Content-Type` header, no ``charset`` parameter, or is not of
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
over all the parts and subparts of a message object tree, in depth-first
traversal order. You will typically use :meth:`walk` as the iterator in a
``for`` loop; each iteration returns the next subpart.
The :meth:`walk` method is an all-purpose generator which can be used to
iterate over all the parts and subparts of a message object tree, in
depth-first traversal order. You will typically use :meth:`walk` as the
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
structure::
Here's an example that prints the MIME type of every part of a multipart
message structure::
>>> for part in msg.walk():
... print part.get_content_type()
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
.. versionchanged:: 2.5
The previously deprecated methods :meth:`get_type`, :meth:`get_main_type`, and
:meth:`get_subtype` were removed.
:class:`Message` objects can also optionally contain two instance attributes,
which can be used when generating the plain text of a MIME message.
.. data:: preamble
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
text is never visible in a MIME-aware mail reader because it falls outside the
standard MIME armor. However, when viewing the raw text of 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
documents. When the :class:`Parser` discovers some text after the headers but
before the first boundary string, it assigns this text to the message's
*preamble* attribute. When the :class:`Generator` is writing out the plain text
representation of a MIME message, and it finds the message has a *preamble*
attribute, it will write this text in the area 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
be ``None``.
.. data:: epilogue
The *epilogue* attribute acts the same way as the *preamble* attribute, except
that it contains text that appears between the last boundary and the end of the
message.
>>> for part in msg.walk():
... print part.get_content_type()
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
.. versionchanged:: 2.5
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.
The previously deprecated methods :meth:`get_type`, :meth:`get_main_type`, and
:meth:`get_subtype` were removed.
:class:`Message` objects can also optionally contain two instance attributes,
which can be used when generating the plain text of a MIME message.
.. data:: defects
.. attribute:: preamble
The *defects* attribute contains a list of all the problems found when parsing
this message. See :mod:`email.errors` for a detailed description of the
possible parsing defects.
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 text is never visible in a MIME-aware mail reader because it falls
outside the standard MIME armor. However, when viewing the raw text of
the message, or when viewing the message in a non-MIME aware reader, this
text can become visible.
.. versionadded:: 2.4
The *preamble* attribute contains this leading extra-armor text for MIME
documents. When the :class:`Parser` discovers some text after the headers
but before the first boundary string, it assigns this text to the
message's *preamble* attribute. When the :class:`Generator` is writing
out the plain text representation of a MIME message, and it finds the
message has a *preamble* attribute, it will write this text in the area
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 be ``None``.
.. attribute:: epilogue
The *epilogue* attribute acts the same way as the *preamble* attribute,
except that it contains text that appears between the last boundary and
the end of the message.
.. versionchanged:: 2.5
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.
.. attribute:: defects
The *defects* attribute contains a list of all the problems found when
parsing this message. See :mod:`email.errors` for a detailed description
of the possible parsing defects.
.. versionadded:: 2.4

View File

@ -67,20 +67,21 @@ Here is the API for the :class:`FeedParser`:
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
containing one or more lines. The lines can be partial and the
:class:`FeedParser` will stitch such partial lines together properly. The lines
in the string can have any of the common three line endings, carriage return,
newline, or carriage return and newline (they can even be mixed).
Feed the :class:`FeedParser` some more data. *data* should be a string
containing one or more lines. The lines can be partial and the
:class:`FeedParser` will stitch such partial lines together properly. The
lines in the string can have any of the common three line endings,
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,
and returns the root message object. It is undefined what happens if you feed
more data to a closed :class:`FeedParser`.
Closing a :class:`FeedParser` completes the parsing of all previously fed
data, and returns the root message object. It is undefined what happens
if you feed more data to a closed :class:`FeedParser`.
Parser class API
@ -119,39 +120,40 @@ class.
.. versionchanged:: 2.4
The *strict* flag was deprecated.
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
return the root message object. *fp* must support both the :meth:`readline` and
the :meth:`read` methods on file-like objects.
Read all the data from the file-like object *fp*, parse the resulting
text, and return the root message object. *fp* must support both the
: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
headers and header continuation lines, optionally preceded by a envelope
header. The header block is terminated either by the end of the data or by a
blank line. Following the header block is the body of the message (which may
contain MIME-encoded subparts).
The text contained in *fp* must be formatted as a block of :rfc:`2822`
style headers and header continuation lines, optionally preceded by a
envelope header. The header block is terminated either by the end of the
data or by a blank line. Following the header block is the body of the
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.
.. versionchanged:: 2.2.2
The *headersonly* flag was added.
.. versionchanged:: 2.2.2
The *headersonly* flag was added.
.. method:: Parser.parsestr(text[, headersonly])
.. method:: 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 equivalent to
wrapping *text* in a :class:`StringIO` instance first and calling :meth:`parse`.
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
equivalent to wrapping *text* in a :class:`StringIO` instance first and
calling :meth:`parse`.
Optional *headersonly* is a flag specifying whether to stop parsing after
reading the headers or not. The default is ``False``, meaning it parses the
entire contents of the file.
Optional *headersonly* is a flag specifying whether to stop parsing after
reading the headers or not. The default is ``False``, meaning it parses
the entire contents of the file.
.. versionchanged:: 2.2.2
The *headersonly* flag was added.
.. versionchanged:: 2.2.2
The *headersonly* flag was added.
Since creating a message object structure from a string or a file object is such
a common task, two functions are provided as a convenience. They are available

View File

@ -66,88 +66,91 @@ The :class:`dircmp` class
'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir,
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
to get various bits of information about the directory trees being compared.
The :class:`dircmp` offers a number of interesting attributes that may be
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
there is no speed penalty if only those attributes which are lightweight to
compute are used.
Note that via :meth:`__getattr__` hooks, all attributes are computed lazily,
so there is no speed penalty if only those attributes which are lightweight
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,
or names for which :func:`os.stat` reports an error.
Names in both *a* and *b*, such that the type differs between the
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.

View File

@ -31,60 +31,58 @@ Fraction number class.
: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
exact value of *flt*, which must be a :class:`float`. Beware that
``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3,
10)``
This classmethod constructs a :class:`Fraction` representing the exact
value of *flt*, which must be a :class:`float`. Beware that
``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3, 10)``
.. method:: Fraction.from_decimal(dec)
.. method:: from_decimal(dec)
This classmethod constructs a :class:`Fraction` representing the
exact value of *dec*, which must be a
:class:`decimal.Decimal`.
This classmethod constructs a :class:`Fraction` representing the exact
value of *dec*, which must be a :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
has denominator at most max_denominator. This method is useful for
finding rational approximations to a given floating-point number:
Finds and returns the closest :class:`Fraction` to ``self`` that has
denominator at most max_denominator. This method is useful for finding
rational approximations to a given floating-point number:
>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355L, 113L)
>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355L, 113L)
or for recovering a rational number that's represented as a float:
or for recovering a rational number that's represented as a float:
>>> from math import pi, cos
>>> Fraction.from_float(cos(pi/3))
Fraction(4503599627370497L, 9007199254740992L)
>>> Fraction.from_float(cos(pi/3)).limit_denominator()
Fraction(1L, 2L)
>>> from math import pi, cos
>>> Fraction.from_float(cos(pi/3))
Fraction(4503599627370497L, 9007199254740992L)
>>> Fraction.from_float(cos(pi/3)).limit_denominator()
Fraction(1L, 2L)
.. method:: Fraction.__floor__()
.. method:: __floor__()
Returns the greatest :class:`int` ``<= self``. Will be accessible
through :func:`math.floor` in Py3k.
Returns the greatest :class:`int` ``<= self``. Will be accessible through
:func:`math.floor` in Py3k.
.. method:: Fraction.__ceil__()
.. method:: __ceil__()
Returns the least :class:`int` ``>= self``. Will be accessible
through :func:`math.ceil` in Py3k.
Returns the least :class:`int` ``>= self``. Will be accessible through
:func:`math.ceil` in Py3k.
.. method:: Fraction.__round__()
Fraction.__round__(ndigits)
.. method:: __round__()
__round__(ndigits)
The first version returns the nearest :class:`int` to ``self``,
rounding half to even. The second version rounds ``self`` to the
nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if
``ndigits`` is negative), again rounding half toward even. Will be
accessible through :func:`round` in Py3k.
The first version returns the nearest :class:`int` to ``self``, rounding
half to even. The second version rounds ``self`` to the nearest multiple
of ``Fraction(1, 10**ndigits)`` (logically, if ``ndigits`` is negative),
again rounding half toward even. Will be accessible through :func:`round`
in Py3k.
.. seealso::

View File

@ -50,33 +50,34 @@ The module defines the following items:
*timeout* was added.
.. data:: all_errors
.. attribute:: all_errors
The set of all exceptions (as a tuple) that methods of :class:`FTP` instances
may raise as a result of problems with the FTP connection (as opposed to
programming errors made by the caller). This set includes the four exceptions
listed below as well as :exc:`socket.error` and :exc:`IOError`.
The set of all exceptions (as a tuple) that methods of :class:`FTP`
instances may raise as a result of problems with the FTP connection (as
opposed to programming errors made by the caller). This set includes the
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
with a digit in the range 1--5.
Exception raised when a reply is received from the server that does not
begin with a digit in the range 1--5.
.. seealso::

View File

@ -240,7 +240,7 @@ interface you can use to write your own specialized translation classes. Here
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.
Initializes "protected" instance variables *_info* and *_charset* which are set
@ -249,121 +249,126 @@ are the methods of :class:`NullTranslations`:
``None``.
.. method:: NullTranslations._parse(fp)
.. method:: _parse(fp)
No-op'd in the base class, this method takes file object *fp*, and reads the
data from the file, initializing its message catalog. If you have an
unsupported message catalog file format, you should override this method to
parse your format.
No-op'd in the base class, this method takes file object *fp*, and reads
the data from the file, initializing its message catalog. If you have an
unsupported message catalog file format, you should override this method
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
translation object should consult the fallback if it cannot provide a
translation for a given message.
Add *fallback* as the fallback object for the current translation
object. A translation object should consult the fallback if it cannot provide a
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,
return the translated message. Overridden in derived classes.
If a fallback has been set, forward :meth:`gettext` to the
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,
return the translated message. Overridden in derived classes.
If a fallback has been set, forward :meth:`lgettext` to the
fallback. Otherwise, return the translated message. Overridden in derived
classes.
.. versionadded:: 2.4
.. versionadded:: 2.4
.. method:: NullTranslations.ugettext(message)
.. method:: ugettext(message)
If a fallback has been set, forward :meth:`ugettext` to the fallback. Otherwise,
return the translated message as a Unicode string. Overridden in derived
classes.
If a fallback has been set, forward :meth:`ugettext` to the
fallback. Otherwise, return the translated message as a Unicode
string. Overridden in derived classes.
.. method:: NullTranslations.ngettext(singular, plural, n)
.. method:: 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, return the translated message. Overridden in derived
classes.
.. versionadded:: 2.3
.. versionadded:: 2.3
.. method:: NullTranslations.lngettext(singular, plural, n)
.. method:: lngettext(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, return the translated message. Overridden in derived
classes.
.. versionadded:: 2.4
.. versionadded:: 2.4
.. method:: NullTranslations.ungettext(singular, plural, n)
.. method:: ungettext(singular, plural, n)
If a fallback has been set, forward :meth:`ungettext` to the fallback.
Otherwise, return the translated message as a Unicode string. Overridden in
derived classes.
If a fallback has been set, forward :meth:`ungettext` to the fallback.
Otherwise, return the translated message as a Unicode string. Overridden
in derived classes.
.. versionadded:: 2.3
.. versionadded:: 2.3
.. method:: NullTranslations.info()
.. method:: 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
encoding used to return translated messages.
Return the "protected" :attr:`_output_charset` variable, which defines the
encoding used to return translated messages.
.. versionadded:: 2.4
.. versionadded:: 2.4
.. method:: NullTranslations.set_output_charset(charset)
.. method:: set_output_charset(charset)
Change the "protected" :attr:`_output_charset` variable, which defines the
encoding used to return translated messages.
Change the "protected" :attr:`_output_charset` variable, which defines the
encoding used to return translated messages.
.. versionadded:: 2.4
.. versionadded:: 2.4
.. method:: NullTranslations.install([unicode [, names]])
.. method:: install([unicode [, names]])
If the *unicode* flag is false, this method installs :meth:`self.gettext` into
the built-in namespace, binding it to ``_``. If *unicode* is true, it binds
:meth:`self.ugettext` instead. By default, *unicode* is false.
If the *unicode* flag is false, this method installs :meth:`self.gettext`
into the built-in namespace, binding it to ``_``. If *unicode* is true,
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
functions you want to install in the builtin namespace in addition to :func:`_`.
Supported names are ``'gettext'`` (bound to :meth:`self.gettext` or
:meth:`self.ugettext` according to the *unicode* flag), ``'ngettext'`` (bound to
:meth:`self.ngettext` or :meth:`self.ungettext` according to the *unicode*
flag), ``'lgettext'`` and ``'lngettext'``.
If the *names* parameter is given, it must be a sequence containing the
names of functions you want to install in the builtin namespace in
addition to :func:`_`. Supported names are ``'gettext'`` (bound to
:meth:`self.gettext` or :meth:`self.ugettext` according to the *unicode*
flag), ``'ngettext'`` (bound to :meth:`self.ngettext` or
: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
:func:`_` function available to your application. Because it affects the entire
application globally, and specifically the built-in namespace, localized modules
should never install :func:`_`. Instead, they should use this code to make
:func:`_` available to their module::
Note that this is only one way, albeit the most convenient way, to make
the :func:`_` function available to your application. Because it affects
the entire application globally, and specifically the built-in namespace,
localized modules should never install :func:`_`. Instead, they should use
this code to make :func:`_` available to their module::
import gettext
t = gettext.translation('mymodule', ...)
_ = t.gettext
import gettext
t = gettext.translation('mymodule', ...)
_ = t.gettext
This puts :func:`_` only in the module's global namespace and so only affects
calls within this module.
This puts :func:`_` only in the module's global namespace and so only
affects calls within this module.
.. versionchanged:: 2.5
Added the *names* parameter.
.. versionchanged:: 2.5
Added the *names* parameter.
The :class:`GNUTranslations` class

View File

@ -1514,19 +1514,19 @@ and :meth:`flush` methods).
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
written to the stream with a trailing newline. If exception information is
present, it is formatted using :func:`traceback.print_exception` and appended to
the stream.
If a formatter is specified, it is used to format the record. The record
is then written to the stream with a trailing newline. If exception
information is present, it is formatted using
: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
:meth:`close` method is inherited from :class:`Handler` and so does nothing, so
an explicit :meth:`flush` call may be needed at times.
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 an explicit :meth:`flush` call may be needed at times.
FileHandler
@ -1546,14 +1546,14 @@ sends logging output to a disk file. It inherits the output functionality from
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.
WatchedFileHandler
@ -1588,11 +1588,11 @@ this value.
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.
If it has, the existing stream is flushed and closed and the file opened again,
before outputting the record to the file.
Outputs the record to the file, but first checks to see if the file has
changed. If it has, the existing stream is flushed and closed and the
file opened again, before outputting the record to the file.
RotatingFileHandler
@ -1624,14 +1624,15 @@ module, supports rotation of disk log files.
: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
@ -1677,14 +1678,14 @@ timed intervals.
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.
SocketHandler
@ -1700,43 +1701,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*.
.. 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
format. If there is an error with the socket, silently drops the packet. If the
connection was previously lost, re-establishes the connection. To unpickle the
record at the receiving end into a :class:`LogRecord`, use the
:func:`makeLogRecord` function.
Pickles the record's attribute dictionary and writes it to the socket in
binary format. If there is an error with the socket, silently drops the
packet. If the connection was previously lost, re-establishes the
connection. To unpickle the record at the receiving end into a
: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
is a lost connection. Closes the socket so that we can retry on the next event.
Handles an error which has occurred during :meth:`emit`. The most likely
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
socket they want. The default implementation creates a TCP socket
(:const:`socket.SOCK_STREAM`).
This is a factory method which allows subclasses to define the precise
type of socket they want. The default implementation creates a TCP socket
(:const:`socket.SOCK_STREAM`).
.. method:: SocketHandler.makePickle(record)
.. method:: makePickle(record)
Pickles the record's attribute dictionary in binary format with a length prefix,
and returns it ready for transmission across the socket.
Pickles the record's attribute dictionary in binary format with a length
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
sends which can happen when the network is busy.
Send a pickled string *packet* to the socket. This function allows for
partial sends which can happen when the network is busy.
DatagramHandler
@ -1753,23 +1755,23 @@ over UDP sockets.
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
format. If there is an error with the socket, silently drops the packet. To
unpickle the record at the receiving end into a :class:`LogRecord`, use the
:func:`makeLogRecord` function.
Pickles the record's attribute dictionary and writes it to the socket in
binary format. If there is an error with the socket, silently drops the
packet. To unpickle the record at the receiving end into a
: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
socket (:const:`socket.SOCK_DGRAM`).
The factory method of :class:`SocketHandler` is here overridden to create
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.
SysLogHandler
@ -1791,22 +1793,22 @@ supports sending logging messages to a remote or local Unix syslog.
: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
information is present, it is *not* sent to the server.
The record is formatted, and then sent to the syslog server. If exception
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
integers - if strings are passed, internal mapping dictionaries are used to
convert them to integers.
Encodes the facility and priority into an integer. You can pass in strings
or integers - if strings are passed, internal mapping dictionaries are
used to convert them to integers.
NTEventLogHandler
@ -1834,45 +1836,45 @@ extensions for Python installed.
defaults to ``'Application'``.
.. method:: NTEventLogHandler.close()
.. method:: close()
At this point, you can remove the application name from the registry as a source
of event log entries. However, if you do this, you will not be able to see the
events as you intended in the Event Log Viewer - it needs to be able to access
the registry to get the .dll name. The current version does not do this (in fact
it doesn't do anything).
At this point, you can remove the application name from the registry as a
source of event log entries. However, if you do this, you will not be able
to see the events as you intended in the Event Log Viewer - it needs to be
able to access the registry to get the .dll name. The current version does
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
message in the NT event log.
Determines the message ID, event category and event type, and then logs
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
your own categories. This version returns 0.
Returns the event category for the record. Override this if you want to
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
own types. This version does a mapping using the handler's typemap attribute,
which is set up in :meth:`__init__` to a dictionary which contains mappings for
:const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and
:const:`CRITICAL`. If you are using your own levels, you will either need to
override this method or place a suitable dictionary in the handler's *typemap*
attribute.
Returns the event type for the record. Override this if you want to
specify your own types. This version does a mapping using the handler's
typemap attribute, which is set up in :meth:`__init__` to a dictionary
which contains mappings for :const:`DEBUG`, :const:`INFO`,
:const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
your own levels, you will either need to override this method or place a
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
could do this by having the *msg* passed to the logger being an ID rather than a
format string. Then, in here, you could use a dictionary lookup to get the
message ID. This version returns 1, which is the base message ID in
:file:`win32service.pyd`.
Returns the message ID for the record. If you are using your own messages,
you could do this by having the *msg* passed to the logger being an ID
rather than a format string. Then, in here, you could use a dictionary
lookup to get the message ID. This version returns 1, which is the base
message ID in :file:`win32service.pyd`.
SMTPHandler
@ -1895,15 +1897,15 @@ supports sending logging messages to an email address via SMTP.
*credentials* was added.
.. 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
method.
If you want to specify a subject line which is record-dependent, override
this method.
MemoryHandler
@ -1926,22 +1928,22 @@ should, then :meth:`flush` is expected to do the needful.
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
:meth:`flush` to process the buffer.
Appends the record to the buffer. If :meth:`shouldFlush` returns true,
calls :meth:`flush` to process the buffer.
.. method:: BufferingHandler.flush()
.. method:: flush()
You can override this to implement custom flushing behavior. This version just
zaps the buffer to empty.
You can override this to implement custom flushing behavior. This version
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
implement custom flushing strategies.
Returns true if the buffer is up to capacity. This method can be
overridden to implement custom flushing strategies.
.. class:: MemoryHandler(capacity[, flushLevel [, target]])
@ -1952,25 +1954,27 @@ should, then :meth:`flush` is expected to do the needful.
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
to the target, if there is one. Override if you want different behavior.
For a :class:`MemoryHandler`, flushing means just sending the buffered
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.
HTTPHandler
@ -1989,9 +1993,9 @@ supports sending logging messages to a Web server, using either ``GET`` or
*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.
.. _formatter-objects:
@ -2079,38 +2083,42 @@ Currently, the useful mapping keys in a :class:`LogRecord` are:
is used.
.. method:: Formatter.format(record)
.. method:: format(record)
The record's attribute dictionary is used as the operand to a string formatting
operation. Returns the resulting string. Before formatting the dictionary, a
couple of preparatory steps are carried out. The *message* attribute of the
record is computed using *msg* % *args*. If the formatting string contains
``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there
is exception information, it is formatted using :meth:`formatException` and
appended to the message. Note that the formatted exception information is cached
in attribute *exc_text*. This is useful because the exception information can
be pickled and sent across the wire, but you should be careful if you have more
than one :class:`Formatter` subclass which customizes the formatting of exception
information. In this case, you will have to clear the cached 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.
The record's attribute dictionary is used as the operand to a string
formatting operation. Returns the resulting string. Before formatting the
dictionary, a couple of preparatory steps are carried out. The *message*
attribute of the record is computed using *msg* % *args*. If the
formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
to format the event time. If there is exception information, it is
formatted using :meth:`formatException` and appended to the message. Note
that the formatted exception information is cached in attribute
*exc_text*. This is useful because the exception information can be
pickled and sent across the wire, but you should be careful if you have
more than one :class:`Formatter` subclass which customizes the formatting
of exception information. In this case, you will have to clear the cached
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
make use of a formatted time. This method can be overridden in formatters to
provide for any specific requirement, but the basic behavior is as follows: if
*datefmt* (a string) is specified, it is used with :func:`time.strftime` to
format the creation time of the record. Otherwise, the ISO8601 format is used.
The resulting string is returned.
This method should be called from :meth:`format` by a formatter which
wants to make use of a formatted time. This method can be overridden in
formatters to provide for any specific requirement, but the basic behavior
is as follows: if *datefmt* (a string) is specified, it is used with
:func:`time.strftime` to format the creation time of the
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
returned by :func:`sys.exc_info`) as a string. This default implementation just
uses :func:`traceback.print_exception`. The resulting string is returned.
Formats the specified exception information (a standard exception tuple as
returned by :func:`sys.exc_info`) as a string. This default implementation
just uses :func:`traceback.print_exception`. The resulting string is
returned.
Filter Objects
@ -2131,10 +2139,11 @@ initialized with the empty string, all events are passed.
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
deemed appropriate, the record may be modified in-place by this method.
Is the specified record to be logged? Returns zero for no, nonzero for
yes. If deemed appropriate, the record may be modified in-place by this
method.
LogRecord Objects
@ -2165,10 +2174,11 @@ made, and any exception information to be logged.
*func* was added.
.. method:: LogRecord.getMessage()
.. method:: getMessage()
Returns the message for this :class:`LogRecord` instance after merging any
user-supplied arguments with the message.
Returns the message for this :class:`LogRecord` instance after merging any
user-supplied arguments with the message.
LoggerAdapter Objects
---------------------
@ -2186,13 +2196,13 @@ __ context-info_
Returns an instance of :class:`LoggerAdapter` initialized with an
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
order to insert contextual information. This implementation takes the
object passed as *extra* to the constructor and adds it to *kwargs* using
key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
(possibly modified) versions of the arguments passed in.
Modifies the message and/or keyword arguments passed to a logging call in
order to insert contextual information. This implementation takes the object
passed as *extra* to the constructor and adds it to *kwargs* using key
'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
(possibly modified) versions of the arguments passed in.
In addition to the above, :class:`LoggerAdapter` supports all the logging
methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,

File diff suppressed because it is too large Load Diff

View File

@ -137,111 +137,111 @@ memory but does not update the underlying file.
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
result in an exception being raised.
Close the file. Subsequent calls to other methods of the object will
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
found, such that *string* is contained in the range [*start*, *end*].
Optional arguments *start* and *end* are interpreted as in slice notation.
Returns ``-1`` on failure.
Returns the lowest index in the object where the substring *string* is
found, such that *string* is contained in the range [*start*, *end*].
Optional arguments *start* and *end* are interpreted as in slice notation.
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
use of this call there is no guarantee that changes are written back before
the object is destroyed. If *offset* and *size* are specified, only
changes to the given range of bytes will be flushed to disk; otherwise, the
whole extent of the mapping is flushed.
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
the object is destroyed. If *offset* and *size* are specified, only
changes to the given range of bytes will be flushed to disk; otherwise, the
whole extent of the mapping is flushed.
**(Windows version)** A nonzero value returned indicates success; zero
indicates failure.
**(Windows version)** A nonzero value returned indicates success; zero
indicates failure.
**(Unix version)** A zero value is returned to indicate success. An
exception is raised when the call failed.
**(Unix version)** A zero value is returned to indicate success. An
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
*dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to
move will throw a :exc:`TypeError` exception.
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
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
position; the file position is updated to point after the bytes that were
returned.
Return a string containing up to *num* bytes starting from the current
file position; the file position is updated to point after the bytes that
were returned.
.. method:: mmap.read_byte()
.. method:: read_byte()
Returns a string of length 1 containing the character at the current file
position, and advances the file position by 1.
Returns a string of length 1 containing the character at the current file
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
next newline.
Returns a single line, starting at the current file position and up to the
next newline.
.. method:: mmap.resize(newsize)
.. method:: resize(newsize)
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
throw a :exc:`TypeError` exception.
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
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
found, such that *string* is contained in the range [*start*, *end*].
Optional arguments *start* and *end* are interpreted as in slice notation.
Returns ``-1`` on failure.
Returns the highest index in the object where the substring *string* is
found, such that *string* is contained in the range [*start*, *end*].
Optional arguments *start* and *end* are interpreted as in slice notation.
Returns ``-1`` on failure.
.. method:: mmap.seek(pos[, whence])
.. method:: seek(pos[, whence])
Set the file's current position. *whence* argument is optional and
defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position)
and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).
Set the file's current position. *whence* argument is optional and
defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
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
memory-mapped area.
Return the length of the file, which can be larger than the size of the
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
pointer; the file position is updated to point after the bytes that were
written. If the mmap was created with :const:`ACCESS_READ`, then writing to
it will throw a :exc:`TypeError` exception.
Write the bytes in *string* into memory at the current position of the
file pointer; the file position is updated to point after the bytes that
were written. If the mmap was created with :const:`ACCESS_READ`, then
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
position of the file pointer; the file position is advanced by ``1``. If
the mmap was created with :const:`ACCESS_READ`, then writing to it will
throw a :exc:`TypeError` exception.
Write the single-character string *byte* into memory at the current
position of the file pointer; the file position is advanced by ``1``. If
the mmap was created with :const:`ACCESS_READ`, then writing to it will
throw a :exc:`TypeError` exception.

View File

@ -40,19 +40,21 @@ report of the imported modules will be printed.
be replaced in module paths.
.. method:: ModuleFinder.report()
.. method:: report()
Print a report to standard output that lists the modules imported by the script
and their paths, as well as modules that are missing or seem to be missing.
Print a report to standard output that lists the modules imported by the
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:

View File

@ -320,19 +320,20 @@ CAB Objects
*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*.
If there is already a file named *logical*, a new file name is created.
Add the file with the pathname *full* to the CAB file, under the name
*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
inside the CAB file.
Return the index of the file in the CAB file, and the new name of the 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
``Media`` table, and remove the generated file from the disk.
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.
.. _msi-directory:
@ -353,33 +354,33 @@ Directory Objects
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
component for this directory. If no component name is given, the directory name
is used. If no *feature* is given, the current feature is used. If no *flags*
are given, the directory's default flags are used. If no *keyfile* is given, the
KeyPath is left null in the Component table.
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 is used. If no *feature* is given, the current feature is used. If no
*flags* are given, the directory's default flags are used. If no *keyfile*
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
there is no current component. By default, the file name in the source and the
file table will be identical. If the *src* file is specified, it is interpreted
relative to the current directory. Optionally, a *version* and a *language* can
be specified for the entry in the File table.
Add a file to the current component of the directory, starting a new one
if there is no current component. By default, the file name in the source
and the file table will be identical. If the *src* file is specified, it
is interpreted relative to the current directory. Optionally, a *version*
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.
Individual files can be excluded in the *exclude* list.
Add a list of files to the current component as specified in the glob
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.
.. seealso::
@ -403,11 +404,11 @@ Features
:class:`Directory`.
.. method:: Feature.set_current()
.. method:: set_current()
Make this feature the current feature of :mod:`msilib`. New components are
automatically added to the default feature, unless a feature is explicitly
specified.
Make this feature the current feature of :mod:`msilib`. New components are
automatically added to the default feature, unless a feature is explicitly
specified.
.. seealso::
@ -430,19 +431,19 @@ to create MSI files with a user-interface for installing Python packages.
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.
.. class:: RadioButtonGroup(dlg, name, property)
@ -451,11 +452,11 @@ to create MSI files with a user-interface for installing Python packages.
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*,
*width*, *height*, and with the label *text*. If *value* is omitted, it defaults
to *name*.
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 to *name*.
.. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel)
@ -465,42 +466,43 @@ to create MSI files with a user-interface for installing Python packages.
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
with the specified parameters.
Return a new :class:`Control` object. An entry in the ``Control`` table is
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.
.. seealso::

View File

@ -29,18 +29,18 @@ The numeric tower
``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
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() ==
(1-3j)``.
Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate()
== (1-3j)``.
.. class:: Real
@ -62,13 +62,13 @@ The numeric tower
should be in lowest terms. With these, it provides a default for
:func:`float`.
.. attribute:: Rational.numerator
.. attribute:: numerator
Abstract.
Abstract.
.. attribute:: Rational.denominator
.. attribute:: denominator
Abstract.
Abstract.
.. class:: Integral

View File

@ -256,34 +256,34 @@ 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
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
constructor. Either the binary or ASCII format will be used, depending on the
value of the *protocol* argument passed to the constructor.
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
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
which objects the pickler has already seen, so that shared or recursive objects
pickled by reference and not by value. This method is useful when re-using
picklers.
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
pickled by reference and not by value. This method is useful when re-using
picklers.
.. note::
.. note::
Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers
created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an
instance variable called :attr:`memo` which is a Python dictionary. So to clear
the memo for a :mod:`pickle` module pickler, you could do the following::
Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers
created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an
instance variable called :attr:`memo` which is a Python dictionary. So to clear
the memo for a :mod:`pickle` module pickler, you could do the following::
mypickler.memo.clear()
mypickler.memo.clear()
Code that does not need to support older versions of Python should simply use
:meth:`clear_memo`.
Code that does not need to support older versions of Python should simply use
:meth:`clear_memo`.
It is possible to make multiple calls to the :meth:`dump` method of the same
:class:`Pickler` instance. These must then be matched to the same number of
@ -307,29 +307,30 @@ 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
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
constructor, and return the reconstituted object hierarchy specified therein.
Read a pickled object representation from the open file object given in
the constructor, and return the reconstituted object hierarchy specified
therein.
This method automatically determines whether the data stream was written in
binary mode or not.
This method automatically determines whether the data stream was written
in binary mode or not.
.. method:: Unpickler.noload()
.. method:: noload()
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"
that may be referenced in a pickle data stream. See section
:ref:`pickle-protocol` below for more details.
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" that may be referenced in a pickle data stream. See section
:ref:`pickle-protocol` below for more details.
**Note:** the :meth:`noload` method is currently only available on
:class:`Unpickler` objects created with the :mod:`cPickle` module.
:mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload`
method.
**Note:** the :meth:`noload` method is currently only available on
:class:`Unpickler` objects created with the :mod:`cPickle` module.
:mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload`
method.
What can be pickled and unpickled?

View File

@ -25,35 +25,35 @@ structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.
single :file:`robots.txt` file.
.. method:: RobotFileParser.set_url(url)
.. method:: set_url(url)
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.
.. method:: RobotFileParser.parse(lines)
.. method:: parse(lines)
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
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
long-running web spiders that need to check for new ``robots.txt`` files
periodically.
.. method:: RobotFileParser.modified()
.. method:: modified()
Sets the time the ``robots.txt`` file was last fetched to the current time.

View File

@ -23,60 +23,62 @@ The :mod:`SimpleHTTPServer` module defines the following class:
:class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the
: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
in the module.
This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
defined in the module.
.. attribute:: SimpleHTTPRequestHandler.extensions_map
.. attribute:: extensions_map
A dictionary mapping suffixes into MIME types. The default is signified by an
empty string, and is considered to be ``application/octet-stream``. The mapping
is used case-insensitively, and so should contain only lower-cased keys.
A dictionary mapping suffixes into MIME types. The default is signified by
an empty string, and is considered to be ``application/octet-stream``. The
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
send for the equivalent ``GET`` request. See the :meth:`do_GET` method for a
more complete explanation of the possible headers.
This method serves the ``'HEAD'`` request type: it sends the headers it
would send for the equivalent ``GET`` request. See the :meth:`do_GET`
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
relative to the current working directory.
The request is mapped to a local file by interpreting the request as a
path relative to the current working directory.
If the request was mapped to a directory, the directory is checked for a file
named ``index.html`` or ``index.htm`` (in that order). If found, the file's
contents are returned; otherwise a directory listing is generated by calling the
:meth:`list_directory` method. This method uses :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 directory, the directory is checked for a
file named ``index.html`` or ``index.htm`` (in that order). If found, the
file's contents are returned; otherwise a directory listing is generated
by calling the :meth:`list_directory` method. This method uses
: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.
Any :exc:`IOError` exception in opening the requested file is mapped to a
``404``, ``'File not found'`` error. Otherwise, the content type is guessed by
calling the :meth:`guess_type` method, which in turn uses the *extensions_map*
variable.
If the request was mapped to a file, it is opened and the contents are
returned. Any :exc:`IOError` exception in opening the requested file is
mapped to a ``404``, ``'File not found'`` error. Otherwise, the content
type is guessed by calling the :meth:`guess_type` method, which in turn
uses the *extensions_map* variable.
A ``'Content-type:'`` header with the guessed content type is output, followed
by a ``'Content-Length:'`` header with the file's size and a
``'Last-Modified:'`` header with the file's modification time.
A ``'Content-type:'`` header with the guessed content type is output,
followed by a ``'Content-Length:'`` header with the file's size and a
``'Last-Modified:'`` header with the file's modification time.
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/``
the file is opened in text mode; otherwise binary mode is used.
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/`` 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.
.. versionadded:: 2.5
The ``'Last-Modified'`` header.
.. versionadded:: 2.5
The ``'Last-Modified'`` header.
.. seealso::

View File

@ -27,14 +27,15 @@ SMTPServer Objects
: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
something useful with this message. Whatever was passed in the constructor as
*remoteaddr* will be available as the :attr:`_remoteaddr` attribute. *peer* is
the remote host's address, *mailfrom* is the envelope originator, *rcpttos* are
the envelope recipients and *data* is a string containing the contents of the
e-mail (which should be in :rfc:`2822` format).
Raise :exc:`NotImplementedError` exception. Override this in subclasses to
do something useful with this message. Whatever was passed in the
constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
attribute. *peer* is the remote host's address, *mailfrom* is the envelope
originator, *rcpttos* are the envelope recipients and *data* is a string
containing the contents of the e-mail (which should be in :rfc:`2822`
format).
DebuggingServer Objects

View File

@ -136,29 +136,29 @@ these rules. The methods of :class:`Template` are:
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
dictionary-like object with keys that match the placeholders in the template.
Alternatively, you can provide keyword arguments, where the keywords are the
placeholders. When both *mapping* and *kws* are given and there are duplicates,
the placeholders from *kws* take precedence.
Performs the template substitution, returning a new string. *mapping* is
any dictionary-like object with keys that match the placeholders in the
template. Alternatively, you can provide keyword arguments, where the
keywords are the placeholders. When both *mapping* and *kws* are given
and there are duplicates, the placeholders from *kws* take precedence.
.. method:: Template.safe_substitute(mapping[, **kws])
.. method:: safe_substitute(mapping[, **kws])
Like :meth:`substitute`, except that if placeholders are missing from *mapping*
and *kws*, instead of raising a :exc:`KeyError` exception, the original
placeholder will appear in the resulting string intact. Also, unlike with
:meth:`substitute`, any other appearances of the ``$`` will simply return ``$``
instead of raising :exc:`ValueError`.
Like :meth:`substitute`, except that if placeholders are missing from
*mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
original placeholder will appear in the resulting string intact. Also,
unlike with :meth:`substitute`, any other appearances of the ``$`` will
simply return ``$`` instead of raising :exc:`ValueError`.
While other exceptions may still occur, this method is called "safe" because
substitutions always tries to return a usable string instead of raising an
exception. In another sense, :meth:`safe_substitute` may be anything other than
safe, since it will silently ignore malformed templates containing dangling
delimiters, unmatched braces, or placeholders that are not valid Python
identifiers.
While other exceptions may still occur, this method is called "safe"
because substitutions always tries to return a usable string instead of
raising an exception. In another sense, :meth:`safe_substitute` may be
anything other than safe, since it will silently ignore malformed
templates containing dangling delimiters, unmatched braces, or
placeholders that are not valid Python identifiers.
:class:`Template` instances also provide one public data attribute:

View File

@ -260,38 +260,38 @@ The :mod:`struct` module also defines the following type:
.. versionadded:: 2.5
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.
(``len(result)`` will equal :attr:`self.size`.)
Identical to the :func:`pack` function, using the compiled format.
(``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.
(``len(string)`` must equal :attr:`self.size`).
Identical to the :func:`unpack` function, using the compiled format.
(``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.
(``len(buffer[offset:])`` must be at least :attr:`self.size`).
Identical to the :func:`unpack_from` function, using the compiled format.
(``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
to :attr:`format`.
The calculated size of the struct (and hence of the string) corresponding
to :attr:`format`.

View File

@ -87,106 +87,107 @@ indentation from strings that have unwanted whitespace to the left of the text.
change any of its options through direct assignment to instance attributes
between uses.
The :class:`TextWrapper` instance attributes (and keyword arguments to the
constructor) are as follows:
The :class:`TextWrapper` instance attributes (and keyword arguments to the
constructor) are as follows:
.. attribute:: TextWrapper.width
.. attribute:: width
(default: ``70``) The maximum length of wrapped lines. As long as there are no
individual words in the input text longer than :attr:`width`,
:class:`TextWrapper` guarantees that no output line will be longer than
:attr:`width` characters.
(default: ``70``) The maximum length of wrapped lines. As long as there
are no individual words in the input text longer than :attr:`width`,
:class:`TextWrapper` guarantees that no output line will be longer than
:attr:`width` characters.
.. attribute:: TextWrapper.expand_tabs
.. attribute:: expand_tabs
(default: ``True``) If true, then all tab characters in *text* will be expanded
to spaces using the :meth:`expandtabs` method of *text*.
(default: ``True``) If true, then all tab characters in *text* will be
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
``string.whitespace``) remaining after tab expansion will be replaced by a
single space.
(default: ``True``) If true, each whitespace character (as defined by
``string.whitespace``) remaining after tab expansion will be replaced by a
single space.
.. note::
.. note::
If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, each tab
character will be replaced by a single space, which is *not* the same as tab
expansion.
If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true,
each tab character will be replaced by a single space, which is *not*
the same as tab expansion.
.. attribute:: TextWrapper.drop_whitespace
.. attribute:: drop_whitespace
(default: ``True``) If true, whitespace that, after wrapping, happens to end up
at the beginning or end of a line is dropped (leading whitespace in the first
line is always preserved, though).
(default: ``True``) If true, whitespace that, after wrapping, happens to
end up at the beginning or end of a line is dropped (leading whitespace in
the first line is always preserved, though).
.. versionadded:: 2.6
Whitespace was always dropped in earlier versions.
.. versionadded:: 2.6
Whitespace was always dropped in earlier versions.
.. attribute:: TextWrapper.initial_indent
.. attribute:: initial_indent
(default: ``''``) String that will be prepended to the first line of wrapped
output. Counts towards the length of the first line.
(default: ``''``) String that will be prepended to the first line of
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
except the first. Counts towards the length of each line except the first.
(default: ``''``) String that will be prepended to all lines of wrapped
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
endings and ensure that sentences are always separated by exactly two spaces.
This is generally desired for text in a monospaced font. However, the sentence
detection algorithm is imperfect: it assumes that a sentence ending consists of
a lowercase letter followed by one of ``'.'``, ``'!'``, or ``'?'``, possibly
followed by one of ``'"'`` or ``"'"``, followed by a space. One problem with
this is algorithm is that it is unable to detect the difference between "Dr." in
::
(default: ``False``) If true, :class:`TextWrapper` attempts to detect
sentence endings and ensure that sentences are always separated by exactly
two spaces. This is generally desired for text in a monospaced font.
However, the sentence detection algorithm is imperfect: it assumes that a
sentence ending consists of a lowercase letter followed by one of ``'.'``,
``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``,
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 [...]
and "Spot." in ::
and "Spot." in ::
[...] See Spot. See Spot run [...]
[...] See Spot. See Spot run [...]
: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
definition of "lowercase letter," and a convention of using two spaces after
a period to separate sentences on the same line, it is specific to
English-language texts.
Since the sentence detection algorithm relies on ``string.lowercase`` for
the definition of "lowercase letter," and a convention of using two spaces
after a period to separate sentences on the same line, it is specific to
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
in order to ensure that no lines are longer than :attr:`width`. If it is false,
long words will not be broken, and some lines may be longer than :attr:`width`.
(Long words will be put on a line by themselves, in order to minimize the amount
by which :attr:`width` is exceeded.)
(default: ``True``) If true, then words longer than :attr:`width` will be
broken in order to ensure that no lines are longer than :attr:`width`. If
it is false, long words will not be broken, and some lines may be longer
than :attr:`width`. (Long words will be put on a line by themselves, in
order to minimize the amount by which :attr:`width` is exceeded.)
:class:`TextWrapper` also provides two public methods, analogous to the
module-level convenience functions:
:class:`TextWrapper` also provides two public methods, analogous to the
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
:attr:`width` characters long. All wrapping options are taken from instance
attributes of the :class:`TextWrapper` instance. Returns a list of output lines,
without final newlines.
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 attributes of the :class:`TextWrapper` instance. Returns a list
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
wrapped paragraph.
Wraps the single paragraph in *text*, and returns a single string
containing the wrapped paragraph.

View File

@ -304,61 +304,63 @@ ElementTree Objects
XML *file* if given.
.. method:: ElementTree._setroot(element)
.. method:: _setroot(element)
Replaces the root element for this tree. This discards the current contents of
the tree, and replaces it with the given element. Use with care. *element* is
an element instance.
Replaces the root element for this tree. This discards the current
contents of the tree, and replaces it with the given element. Use with
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).
*path* is the element to look for. Returns the first matching element, or
``None`` if no element was found.
Finds the first toplevel element with given tag. Same as
getroot().find(path). *path* is the element to look for. Returns the
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).
*path* is the element to look for. Returns a list or :term:`iterator` containing all
matching elements, in document order.
Finds all toplevel elements with the given tag. Same as
getroot().findall(path). *path* is the element to look for. Returns a
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
getroot().findtext(path). *path* is the toplevel element to look for. *default*
is the value to return if the element was not found. Returns the text content of
the first matching element, or the default value no element was found. Note
that if the element has is found, but has no text content, this method returns
an empty string.
Finds the element text for the first toplevel element with given tag.
Same as getroot().findtext(path). *path* is the toplevel element to look
for. *default* is the value to return if the element was not
found. Returns the text content of the first matching element, or the
default value no element was found. Note that if the element has is
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
over all elements in this tree, in section order. *tag* is the tag to look for
(default is to return all elements)
Creates and returns a tree iterator for the root element. The iterator
loops over all elements in this tree, in section order. *tag* is the tag
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
file object. *parser* is an optional parser instance. If not given, the
standard XMLTreeBuilder parser is used. Returns the section root element.
Loads an external XML section into this element tree. *source* is a file
name or file object. *parser* is an optional parser instance. If not
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
object opened for writing. *encoding* [1]_ is the output encoding (default is
US-ASCII).
Writes the element tree to a file, as XML. *file* is a file name, or a
file object opened for writing. *encoding* [1]_ is the output encoding
(default is US-ASCII).
This is the XML file that is going to be manipulated::
@ -419,28 +421,28 @@ TreeBuilder Objects
Element instances when given.
.. method:: TreeBuilder.close()
.. method:: close()
Flushes the parser buffers, and returns the toplevel document element. Returns an
Element instance.
Flushes the parser buffers, and returns the toplevel document
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
8-bit string containing ASCII text, or a Unicode string.
Adds text to the current element. *data* is a string. This should be
either an 8-bit string containing ASCII text, or a Unicode string.
.. method:: TreeBuilder.end(tag)
.. method:: end(tag)
Closes the current element. *tag* is the element name. Returns the closed
element.
Closes the current element. *tag* is the element name. Returns the closed
element.
.. method:: TreeBuilder.start(tag, attrs)
.. method:: start(tag, attrs)
Opens a new element. *tag* is the element name. *attrs* is a dictionary
containing element attributes. Returns the opened element.
Opens a new element. *tag* is the element name. *attrs* is a dictionary
containing element attributes. Returns the opened element.
.. _elementtree-xmltreebuilder-objects:
@ -457,20 +459,20 @@ XMLTreeBuilder Objects
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
identifier. *system* is the system identifier.
Handles a doctype declaration. *name* is the doctype name. *pubid* is the
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.
:meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method
for each opening tag, its :meth:`end` method for each closing tag,

View File

@ -28,214 +28,223 @@ parsing text files formatted in XML (Extensible Markup Language).
The :class:`XMLParser` class must be instantiated without arguments. [#]_
This class provides the following interface methods and instance variables:
This class provides the following interface methods and instance variables:
.. attribute:: XMLParser.attributes
.. attribute:: attributes
A mapping of element names to mappings. The latter mapping maps attribute names
that are valid for the element to the default value of the attribute, or if
there is no default to ``None``. The default value is the empty dictionary.
This variable is meant to be overridden, not extended since the default is
shared by all instances of :class:`XMLParser`.
A mapping of element names to mappings. The latter mapping maps attribute
names that are valid for the element to the default value of the
attribute, or if there is no default to ``None``. The default value is
the empty dictionary. This variable is meant to be overridden, not
extended since the default is shared by all instances of
:class:`XMLParser`.
.. attribute:: XMLParser.elements
.. attribute:: elements
A mapping of element names to tuples. The tuples contain a function for
handling the start and end tag respectively of the element, or ``None`` if the
method :meth:`unknown_starttag` or :meth:`unknown_endtag` is to be called. The
default value is the empty dictionary. This variable is meant to be overridden,
not extended since the default is shared by all instances of :class:`XMLParser`.
A mapping of element names to tuples. The tuples contain a function for
handling the start and end tag respectively of the element, or ``None`` if
the method :meth:`unknown_starttag` or :meth:`unknown_endtag` is to be
called. The default value is the empty dictionary. This variable is
meant to be overridden, not extended since the default is shared by all
instances of :class:`XMLParser`.
.. attribute:: XMLParser.entitydefs
.. attribute:: entitydefs
A mapping of entitynames to their values. The default value contains
definitions for ``'lt'``, ``'gt'``, ``'amp'``, ``'quot'``, and ``'apos'``.
A mapping of entitynames to their values. The default value contains
definitions for ``'lt'``, ``'gt'``, ``'amp'``, ``'quot'``, and ``'apos'``.
.. method:: XMLParser.reset()
.. method:: reset()
Reset the instance. Loses all unprocessed data. This is called implicitly at
the instantiation time.
Reset the instance. Loses all unprocessed data. This is called
implicitly at the instantiation time.
.. method:: XMLParser.setnomoretags()
.. method:: setnomoretags()
Stop processing tags. Treat all following input as literal input (CDATA).
Stop processing tags. Treat all following input as literal input (CDATA).
.. method:: XMLParser.setliteral()
.. method:: setliteral()
Enter literal mode (CDATA mode). This mode is automatically exited when the
close tag matching the last unclosed open tag is encountered.
Enter literal mode (CDATA mode). This mode is automatically exited when
the close tag matching the last unclosed open tag is encountered.
.. method:: XMLParser.feed(data)
.. method:: feed(data)
Feed some text to the parser. It is processed insofar as it consists of
complete tags; incomplete data is buffered until more data is fed or
:meth:`close` is called.
Feed some text to the parser. It is processed insofar as it consists of
complete tags; incomplete data is buffered until more data is fed or
:meth:`close` is called.
.. method:: XMLParser.close()
.. method:: close()
Force processing of all buffered data as if it were followed by an end-of-file
mark. This method may be redefined by a derived class to define additional
processing at the end of the input, but the redefined version should always call
:meth:`close`.
Force processing of all buffered data as if it were followed by an
end-of-file mark. This method may be redefined by a derived class to
define additional processing at the end of the input, but the redefined
version should always call :meth:`close`.
.. method:: XMLParser.translate_references(data)
.. method:: translate_references(data)
Translate all entity and character references in *data* and return the
translated string.
Translate all entity and character references in *data* and return the
translated string.
.. method:: XMLParser.getnamespace()
.. method:: getnamespace()
Return a mapping of namespace abbreviations to namespace URIs that are currently
in effect.
Return a mapping of namespace abbreviations to namespace URIs that are
currently in effect.
.. method:: XMLParser.handle_xml(encoding, standalone)
.. method:: handle_xml(encoding, standalone)
This method is called when the ``<?xml ...?>`` tag is processed. The arguments
are the values of the encoding and standalone attributes in the tag. Both
encoding and standalone are optional. The values passed to :meth:`handle_xml`
default to ``None`` and the string ``'no'`` respectively.
This method is called when the ``<?xml ...?>`` tag is processed. The
arguments are the values of the encoding and standalone attributes in the
tag. Both encoding and standalone are optional. The values passed to
:meth:`handle_xml` default to ``None`` and the string ``'no'``
respectively.
.. method:: XMLParser.handle_doctype(tag, pubid, syslit, data)
.. method:: handle_doctype(tag, pubid, syslit, data)
.. index::
single: DOCTYPE declaration
single: Formal Public Identifier
.. index::
single: DOCTYPE declaration
single: Formal Public Identifier
This method is called when the ``<!DOCTYPE...>`` declaration is processed. The
arguments are the tag name of the root element, the Formal Public Identifier (or
``None`` if not specified), the system identifier, and the uninterpreted
contents of the internal DTD subset as a string (or ``None`` if not present).
This method is called when the ``<!DOCTYPE...>`` declaration is processed.
The arguments are the tag name of the root element, the Formal Public
Identifier (or ``None`` if not specified), the system identifier, and the
uninterpreted contents of the internal DTD subset as a string (or ``None``
if not present).
.. method:: XMLParser.handle_starttag(tag, method, attributes)
.. method:: handle_starttag(tag, method, attributes)
This method is called to handle start tags for which a start tag handler is
defined in the instance variable :attr:`elements`. The *tag* argument is the
name of the tag, and the *method* argument is the function (method) which should
be used to support semantic interpretation of the start tag. The *attributes*
argument is a dictionary of attributes, the key being the *name* and the value
being the *value* of the attribute found inside the tag's ``<>`` brackets.
Character and entity references in the *value* have been interpreted. For
instance, for the start tag ``<A HREF="http://www.cwi.nl/">``, this method would
be called as ``handle_starttag('A', self.elements['A'][0], {'HREF':
'http://www.cwi.nl/'})``. The base implementation simply calls *method* with
*attributes* as the only argument.
This method is called to handle start tags for which a start tag handler
is defined in the instance variable :attr:`elements`. The *tag* argument
is the name of the tag, and the *method* argument is the function (method)
which should be used to support semantic interpretation of the start tag.
The *attributes* argument is a dictionary of attributes, the key being the
*name* and the value being the *value* of the attribute found inside the
tag's ``<>`` brackets. Character and entity references in the *value*
have been interpreted. For instance, for the start tag ``<A
HREF="http://www.cwi.nl/">``, this method would be called as
``handle_starttag('A', self.elements['A'][0], {'HREF':
'http://www.cwi.nl/'})``. The base implementation simply calls *method*
with *attributes* as the only argument.
.. method:: XMLParser.handle_endtag(tag, method)
.. method:: handle_endtag(tag, method)
This method is called to handle endtags for which an end tag handler is defined
in the instance variable :attr:`elements`. The *tag* argument is the name of
the tag, and the *method* argument is the function (method) which should be used
to support semantic interpretation of the end tag. For instance, for the endtag
``</A>``, this method would be called as ``handle_endtag('A',
self.elements['A'][1])``. The base implementation simply calls *method*.
This method is called to handle endtags for which an end tag handler is
defined in the instance variable :attr:`elements`. The *tag* argument is
the name of the tag, and the *method* argument is the function (method)
which should be used to support semantic interpretation of the end tag.
For instance, for the endtag ``</A>``, this method would be called as
``handle_endtag('A', self.elements['A'][1])``. The base implementation
simply calls *method*.
.. method:: XMLParser.handle_data(data)
.. method:: handle_data(data)
This method is called to process arbitrary data. It is intended to be
overridden by a derived class; the base class implementation does nothing.
This method is called to process arbitrary data. It is intended to be
overridden by a derived class; the base class implementation does nothing.
.. method:: XMLParser.handle_charref(ref)
.. method:: handle_charref(ref)
This method is called to process a character reference of the form ``&#ref;``.
*ref* can either be a decimal number, or a hexadecimal number when preceded by
an ``'x'``. In the base implementation, *ref* must be a number in the range
0-255. It translates the character to ASCII and calls the method
:meth:`handle_data` with the character as argument. If *ref* is invalid or out
of range, the method ``unknown_charref(ref)`` is called to handle the error. A
subclass must override this method to provide support for character references
outside of the ASCII range.
This method is called to process a character reference of the form
``&#ref;``. *ref* can either be a decimal number, or a hexadecimal number
when preceded by an ``'x'``. In the base implementation, *ref* must be a
number in the range 0-255. It translates the character to ASCII and calls
the method :meth:`handle_data` with the character as argument. If *ref*
is invalid or out of range, the method ``unknown_charref(ref)`` is called
to handle the error. A subclass must override this method to provide
support for character references outside of the ASCII range.
.. method:: XMLParser.handle_comment(comment)
.. method:: handle_comment(comment)
This method is called when a comment is encountered. The *comment* argument is
a string containing the text between the ``<!--`` and ``-->`` delimiters, but
not the delimiters themselves. For example, the comment ``<!--text-->`` will
cause this method to be called with the argument ``'text'``. The default method
does nothing.
This method is called when a comment is encountered. The *comment*
argument is a string containing the text between the ``<!--`` and ``-->``
delimiters, but not the delimiters themselves. For example, the comment
``<!--text-->`` will cause this method to be called with the argument
``'text'``. The default method does nothing.
.. method:: XMLParser.handle_cdata(data)
.. method:: handle_cdata(data)
This method is called when a CDATA element is encountered. The *data* argument
is a string containing the text between the ``<![CDATA[`` and ``]]>``
delimiters, but not the delimiters themselves. For example, the entity
``<![CDATA[text]]>`` will cause this method to be called with the argument
``'text'``. The default method does nothing, and is intended to be overridden.
This method is called when a CDATA element is encountered. The *data*
argument is a string containing the text between the ``<![CDATA[`` and
``]]>`` delimiters, but not the delimiters themselves. For example, the
entity ``<![CDATA[text]]>`` will cause this method to be called with the
argument ``'text'``. The default method does nothing, and is intended to
be overridden.
.. method:: XMLParser.handle_proc(name, data)
.. method:: handle_proc(name, data)
This method is called when a processing instruction (PI) is encountered. The
*name* is the PI target, and the *data* argument is a string containing the text
between the PI target and the closing delimiter, but not the delimiter itself.
For example, the instruction ``<?XML text?>`` will cause this method to be
called with the arguments ``'XML'`` and ``'text'``. The default method does
nothing. Note that if a document starts with ``<?xml ..?>``, :meth:`handle_xml`
is called to handle it.
This method is called when a processing instruction (PI) is encountered.
The *name* is the PI target, and the *data* argument is a string
containing the text between the PI target and the closing delimiter, but
not the delimiter itself. For example, the instruction ``<?XML text?>``
will cause this method to be called with the arguments ``'XML'`` and
``'text'``. The default method does nothing. Note that if a document
starts with ``<?xml ..?>``, :meth:`handle_xml` is called to handle it.
.. method:: XMLParser.handle_special(data)
.. method:: handle_special(data)
.. index:: single: ENTITY declaration
.. index:: single: ENTITY declaration
This method is called when a declaration is encountered. The *data* argument is
a string containing the text between the ``<!`` and ``>`` delimiters, but not
the delimiters themselves. For example, the entity declaration ``<!ENTITY
text>`` will cause this method to be called with the argument ``'ENTITY text'``.
The default method does nothing. Note that ``<!DOCTYPE ...>`` is handled
separately if it is located at the start of the document.
This method is called when a declaration is encountered. The *data*
argument is a string containing the text between the ``<!`` and ``>``
delimiters, but not the delimiters themselves. For example, the entity
declaration ``<!ENTITY text>`` will cause this method to be called with
the argument ``'ENTITY text'``. The default method does nothing. Note
that ``<!DOCTYPE ...>`` is handled separately if it is located at the
start of the document.
.. method:: XMLParser.syntax_error(message)
.. method:: syntax_error(message)
This method is called when a syntax error is encountered. The *message* is a
description of what was wrong. The default method raises a :exc:`RuntimeError`
exception. If this method is overridden, it is permissible for it to return.
This method is only called when the error can be recovered from. Unrecoverable
errors raise a :exc:`RuntimeError` without first calling :meth:`syntax_error`.
This method is called when a syntax error is encountered. The *message*
is a description of what was wrong. The default method raises a
:exc:`RuntimeError` exception. If this method is overridden, it is
permissible for it to return. This method is only called when the error
can be recovered from. Unrecoverable errors raise a :exc:`RuntimeError`
without first calling :meth:`syntax_error`.
.. method:: XMLParser.unknown_starttag(tag, attributes)
.. method:: unknown_starttag(tag, attributes)
This method is called to process an unknown start tag. It is intended to be
overridden by a derived class; the base class implementation does nothing.
This method is called to process an unknown start tag. It is intended to
be overridden by a derived class; the base class implementation does nothing.
.. method:: XMLParser.unknown_endtag(tag)
.. method:: unknown_endtag(tag)
This method is called to process an unknown end tag. It is intended to be
overridden by a derived class; the base class implementation does nothing.
This method is called to process an unknown end tag. It is intended to be
overridden by a derived class; the base class implementation does nothing.
.. method:: XMLParser.unknown_charref(ref)
.. method:: unknown_charref(ref)
This method is called to process unresolvable numeric character references. It
is intended to be overridden by a derived class; the base class implementation
does nothing.
This method is called to process unresolvable numeric character
references. It is intended to be overridden by a derived class; the base
class implementation does nothing.
.. method:: XMLParser.unknown_entityref(ref)
.. method:: unknown_entityref(ref)
This method is called to process an unknown entity reference. It is intended to
be overridden by a derived class; the base class implementation calls
:meth:`syntax_error` to signal an error.
This method is called to process an unknown entity reference. It is
intended to be overridden by a derived class; the base class
implementation calls :meth:`syntax_error` to signal an error.
.. seealso::

View File

@ -76,55 +76,57 @@ zipimporter Objects
(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
qualified (dotted) module name. It returns the zipimporter instance itself if
the module was found, or :const:`None` if it wasn't. The optional *path*
argument is ignored---it's there for compatibility with the importer protocol.
Search for a module specified by *fullname*. *fullname* must be the fully
qualified (dotted) module name. It returns the zipimporter instance itself
if the module was found, or :const:`None` if it wasn't. The optional
*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
the module couldn't be found.
Return the code object for the specified module. Raise
: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
wasn't found.
Return the data associated with *pathname*. Raise :exc:`IOError` if the
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
the module couldn't be found, return :const:`None` if the archive does contain
the module, but has no source for it.
Return the source code for the specified module. Raise
:exc:`ZipImportError` if the module couldn't be found, return
: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
:exc:`ZipImportError` if the module couldn't be found.
Return True if the module specified by *fullname* is a package. Raise
: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
(dotted) module name. It returns the imported module, or raises
:exc:`ZipImportError` if it wasn't found.
Load the module specified by *fullname*. *fullname* must be the fully
qualified (dotted) module name. It returns the imported module, or raises
: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
:class:`zipimporter` for details.
The path within the ZIP file where modules are searched; see
:class:`zipimporter` for details.
.. _zipimport-examples: