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,7 +197,7 @@ 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.
@ -212,23 +212,23 @@ 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.
.. method:: fifo.first()
.. method:: first()
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.
.. 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.

View File

@ -99,13 +99,13 @@ 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.
.. 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
@ -116,38 +116,38 @@ full set of methods that can be overridden in your subclass follows:
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.
.. 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.
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.
.. method:: dispatcher.handle_error()
.. method:: handle_error()
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.
.. 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
@ -155,50 +155,50 @@ full set of methods that can be overridden in your subclass follows:
default, all channels will be interested in read events.
.. 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.
.. method:: dispatcher.create_socket(family, type)
.. method:: 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
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.connect(address)
.. method:: connect(address)
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.send(data)
.. method:: send(data)
Send *data* to the remote end-point of the socket.
.. method:: dispatcher.recv(buffer_size)
.. method:: recv(buffer_size)
Read at most *buffer_size* bytes from the socket's remote end-point.
An empty string implies that the channel has been closed from the other
end.
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.listen(backlog)
.. method:: listen(backlog)
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.bind(address)
.. method:: bind(address)
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
@ -206,7 +206,7 @@ Most of these are nearly identical to their socket partners.
the :class:`dispatcher` object's :meth:`set_reuse_addr` method.
.. method:: dispatcher.accept()
.. method:: accept()
Accept a connection. The socket must be bound to an address and listening
for connections. The return value is a pair ``(conn, address)`` where
@ -215,7 +215,7 @@ Most of these are nearly identical to their socket partners.
end of the connection.
.. method:: dispatcher.close()
.. 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

View File

@ -34,113 +34,118 @@ 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:
.. 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'``.
.. attribute:: BaseHTTPRequestHandler.path
.. attribute:: path
Contains the request path.
.. attribute:: BaseHTTPRequestHandler.request_version
.. attribute:: request_version
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.
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:
.. attribute:: BaseHTTPRequestHandler.server_version
.. 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'``.
format is multiple whitespace-separated strings, where each string is of
the form name[/version]. For example, ``'BaseHTTP/0.2'``.
.. attribute:: BaseHTTPRequestHandler.sys_version
.. attribute:: sys_version
Contains the Python system version, in a form usable by the
:attr:`version_string` method and the :attr:`server_version` class variable. For
example, ``'Python/1.4'``.
:attr:`version_string` method and the :attr:`server_version` class
variable. For example, ``'Python/1.4'``.
.. attribute:: BaseHTTPRequestHandler.error_message_format
.. attribute:: error_message_format
Specifies a format string for building an error response to the client. It uses
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.
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
.. attribute:: error_content_type
Specifies the Content-Type HTTP header of error responses sent to the client.
The default value is ``'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
.. 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'``.
``'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
.. attribute:: MessageClass
.. index:: single: Message (in module mimetools)
@ -149,7 +154,7 @@ to a handler. Code to create and run the server looks like this::
:class:`mimetools.Message`.
.. attribute:: BaseHTTPRequestHandler.responses
.. attribute:: responses
This variable contains a mapping of error code integers to two-element tuples
containing a short and long message. For example, ``{code: (shortmessage,
@ -157,23 +162,25 @@ to a handler. Code to create and run the server looks like this::
error response, and *longmessage* as the *explain* key (see the
:attr:`error_message_format` class variable).
A :class:`BaseHTTPRequestHandler` instance has the following methods:
.. method:: BaseHTTPRequestHandler.handle()
.. method:: handle()
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.
enabled, multiple times) to handle incoming HTTP requests. You should
never need to override it; instead, implement appropriate :meth:`do_\*`
methods.
.. method:: BaseHTTPRequestHandler.handle_one_request()
.. method:: handle_one_request()
This method will parse and dispatch the request to the appropriate :meth:`do_\*`
method. You should never need to override it.
This method will parse and dispatch the request to the appropriate
:meth:`do_\*` method. You should never need to override it.
.. method:: BaseHTTPRequestHandler.send_error(code[, message])
.. method:: send_error(code[, message])
Sends and logs a complete error reply to the client. The numeric *code*
specifies the HTTP error code, with *message* as optional, more specific text. A
@ -181,59 +188,60 @@ A :class:`BaseHTTPRequestHandler` instance has the following methods:
:attr:`error_message_format` class variable.
.. method:: BaseHTTPRequestHandler.send_response(code[, message])
.. method:: send_response(code[, message])
Sends a response header and logs the accepted request. The HTTP response line is
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.
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:: BaseHTTPRequestHandler.send_header(keyword, value)
.. method:: send_header(keyword, value)
Writes a specific HTTP header to the output stream. *keyword* should specify the
header keyword, with *value* specifying its value.
Writes a specific HTTP header to the output stream. *keyword* should
specify the header keyword, with *value* specifying its value.
.. method:: BaseHTTPRequestHandler.end_headers()
.. method:: end_headers()
Sends a blank line, indicating the end of the HTTP headers in the response.
Sends a blank line, indicating the end of the HTTP headers in the
response.
.. method:: BaseHTTPRequestHandler.log_request([code[, size]])
.. method:: log_request([code[, size]])
Logs an accepted (successful) request. *code* should specify the numeric HTTP
code associated with the response. If a size of the response is available, then
it should be passed as the *size* parameter.
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:: BaseHTTPRequestHandler.log_error(...)
.. method:: log_error(...)
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 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:: BaseHTTPRequestHandler.log_message(format, ...)
.. method:: log_message(format, ...)
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.
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:: BaseHTTPRequestHandler.version_string()
.. method:: version_string()
Returns the server software's version string. This is a combination of the
:attr:`server_version` and :attr:`sys_version` class variables.
.. method:: BaseHTTPRequestHandler.date_time_string([timestamp])
.. method:: date_time_string([timestamp])
Returns the date and time given by *timestamp* (which must be in the format
returned by :func:`time.time`), formatted for a message header. If *timestamp*
is omitted, it uses the current date and time.
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'``.
@ -241,15 +249,15 @@ A :class:`BaseHTTPRequestHandler` instance has the following methods:
The *timestamp* parameter.
.. method:: BaseHTTPRequestHandler.log_date_time_string()
.. method:: log_date_time_string()
Returns the current date and time, formatted for logging.
.. method:: BaseHTTPRequestHandler.address_string()
.. method:: address_string()
Returns the client address, formatted for logging. A name lookup is performed on
the client's IP address.
Returns the client address, formatted for logging. A name lookup is
performed on the client's IP address.
.. seealso::

View File

@ -33,21 +33,24 @@ The :mod:`bdb` module also defines two classes:
: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
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()
.. method:: enable()
Mark the breakpoint as enabled.
.. method:: Breakpoint.disable()
.. method:: disable()
Mark the breakpoint as disabled.
.. method:: Breakpoint.bpprint([out])
.. method:: pprint([out])
Print all the information about the breakpoint:
@ -70,26 +73,25 @@ The :mod:`bdb` module also defines two classes:
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.
.. method:: Bdb.reset()
.. method:: reset()
Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and
:attr:`quitting` attributes with values ready to start debugging.
.. method:: Bdb.trace_dispatch(frame, event, arg)
.. method:: 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).
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
@ -100,39 +102,39 @@ The following methods of :class:`Bdb` normally don't need to be overridden.
* ``"c_return"``: A C function has returned.
* ``"c_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.
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:: Bdb.dispatch_line(frame)
.. method:: 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:: Bdb.dispatch_call(frame, arg)
.. method:: 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:`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:: Bdb.dispatch_return(frame, arg)
.. method:: 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:`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:: Bdb.dispatch_exception(frame, arg)
.. method:: dispatch_exception(frame, arg)
If the debugger should stop at this exception, invokes the
:meth:`user_exception` method (which should be overridden in subclasses).
@ -140,21 +142,21 @@ The following methods of :class:`Bdb` normally don't need to be overridden.
(which can be set from :meth:`user_exception`). Return a reference to the
: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:: Bdb.stop_here(frame)
.. method:: 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:: Bdb.break_here(frame)
.. method:: 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.
.. method:: Bdb.break_anywhere(frame)
.. method:: break_anywhere(frame)
This method checks if there is a breakpoint in the filename of the current
frame.
@ -162,28 +164,28 @@ they want to redefine the definition of stopping and breakpoints.
Derived classes should override these methods to gain control over debugger
operation.
.. method:: Bdb.user_call(frame, argument_list)
.. method:: user_call(frame, argument_list)
This method is called from :meth:`dispatch_call` when there is the
possibility that a break might be necessary anywhere inside the called
function.
.. method:: Bdb.user_line(frame)
.. method:: user_line(frame)
This method is called from :meth:`dispatch_line` when either
:meth:`stop_here` or :meth:`break_here` yields True.
.. method:: Bdb.user_return(frame, return_value)
.. method:: user_return(frame, return_value)
This method is called from :meth:`dispatch_return` when :meth:`stop_here`
yields True.
.. method:: Bdb.user_exception(frame, exc_info)
.. method:: user_exception(frame, exc_info)
This method is called from :meth:`dispatch_exception` when :meth:`stop_here`
yields True.
This method is called from :meth:`dispatch_exception` when
:meth:`stop_here` yields True.
.. method:: Bdb.do_clear(arg)
.. method:: do_clear(arg)
Handle how a breakpoint must be removed when it is a temporary one.
@ -193,29 +195,29 @@ operation.
Derived classes and clients can call the following methods to affect the
stepping state.
.. method:: Bdb.set_step()
.. method:: set_step()
Stop after one line of code.
.. method:: Bdb.set_next(frame)
.. method:: set_next(frame)
Stop on the next line in or below the given frame.
.. method:: Bdb.set_return(frame)
.. method:: set_return(frame)
Stop when returning from the given frame.
.. method:: Bdb.set_trace([frame])
.. method:: set_trace([frame])
Start debugging from *frame*. If *frame* is not specified, debugging starts
from caller's frame.
Start debugging from *frame*. If *frame* is not specified, debugging
starts from caller's frame.
.. method:: Bdb.set_continue()
.. method:: set_continue()
Stop only at breakpoints or when finished. If there are no breakpoints, set
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:: Bdb.set_quit()
.. method:: set_quit()
Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in
the next call to one of the :meth:`dispatch_\*` methods.
@ -225,46 +227,46 @@ 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:: Bdb.set_break(filename, lineno[, temporary=0[, cond[, funcname]]])
.. method:: set_break(filename, lineno[, temporary=0[, cond[, funcname]]])
Set a new breakpoint. If the *lineno* line doesn't exist for the *filename*
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:: Bdb.clear_break(filename, lineno)
.. method:: clear_break(filename, lineno)
Delete the breakpoints in *filename* and *lineno*. If none were set, an
error message is returned.
.. method:: Bdb.clear_bpbynumber(arg)
.. method:: 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.
.. method:: Bdb.clear_all_file_breaks(filename)
.. method:: clear_all_file_breaks(filename)
Delete all breakpoints in *filename*. If none were set, an error message is
returned.
Delete all breakpoints in *filename*. If none were set, an error message
is returned.
.. method:: Bdb.clear_all_breaks()
.. method:: clear_all_breaks()
Delete all existing breakpoints.
.. method:: Bdb.get_break(filename, lineno)
.. method:: get_break(filename, lineno)
Check if there is a breakpoint for *lineno* of *filename*.
.. method:: Bdb.get_breaks(filename, lineno)
.. method:: 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:: Bdb.get_file_breaks(filename)
.. method:: get_file_breaks(filename)
Return all breakpoints in *filename*, or an empty list if none are set.
.. method:: Bdb.get_all_breaks()
.. method:: get_all_breaks()
Return all breakpoints that are set.
@ -272,12 +274,12 @@ something went wrong, or ``None`` if all is well.
Derived classes and clients can call the following methods to get a data
structure representing a stack trace.
.. method:: Bdb.get_stack(f, t)
.. method:: get_stack(f, t)
Get a list of records for a frame and all higher (calling) and lower frames,
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:: Bdb.format_stack_entry(frame_lineno, [lprefix=': '])
.. method:: format_stack_entry(frame_lineno, [lprefix=': '])
Return a string with information about a stack entry, identified by a
``(frame, lineno)`` tuple:
@ -289,24 +291,24 @@ structure representing a stack trace.
* 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:: Bdb.run(cmd, [globals, [locals]])
.. method:: run(cmd, [globals, [locals]])
Debug a statement executed via the :keyword:`exec` statement. *globals*
defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*.
.. method:: Bdb.runeval(expr, [globals, [locals]])
.. method:: runeval(expr, [globals, [locals]])
Debug an expression executed via the :func:`eval` function. *globals* and
*locals* have the same meaning as in :meth:`run`.
.. method:: Bdb.runctx(cmd, globals, locals)
.. method:: runctx(cmd, globals, locals)
For backwards compatibility. Calls the :meth:`run` method.
.. method:: Bdb.runcall(func, *args, **kwds)
.. method:: runcall(func, *args, **kwds)
Debug a single function call, and return its result.

View File

@ -48,83 +48,87 @@ Handling of compressed files is offered by the :class:`BZ2File` class.
Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default)
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.
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.
.. 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.
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).
.. 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.
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

@ -37,68 +37,69 @@ it's the base calendar for all computations.
: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.
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.
: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.
.. 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.
.. 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
@ -114,31 +115,31 @@ it's the base calendar for all computations.
: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
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`.
.. 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.
: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`.
@ -152,33 +153,34 @@ it's the base calendar for all computations.
: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

@ -46,19 +46,19 @@ The :mod:`CGIHTTPServer` module defines the following class:
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:
.. 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

@ -69,59 +69,61 @@ instance will fail with a :exc:`EOFError` exception.
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.
.. 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.
.. method:: Chunk.isatty()
.. method:: isatty()
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.
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.
.. 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,14 +435,14 @@ 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.
@ -483,21 +483,22 @@ 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.
The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
working interfaces which can be used to implement new encoding submodules very
easily. See :mod:`encodings.utf_8` for an example of how this is done.
@ -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.
.. 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.
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,26 +606,27 @@ 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.
*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.
@ -632,36 +635,39 @@ compatible with the Python codec registry.
*firstline* argument added.
.. method:: StreamReader.readline([size[, keepends]])
.. method:: readline([size[, keepends]])
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.
.. 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.
.. method:: StreamReader.reset()
.. method:: reset()
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

@ -182,47 +182,47 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
Deque objects support the following methods:
.. method:: deque.append(x)
.. method:: append(x)
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.
.. method:: deque.clear()
.. method:: clear()
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.
.. 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`.
@ -230,12 +230,13 @@ Deque objects support the following methods:
.. 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:
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
the :keyword:`in` operator, and subscript references such as ``d[-1]``.
@ -374,24 +375,26 @@ standard :class:`dict` operations:
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.
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__`.
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:
.. 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.
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

@ -156,19 +156,21 @@ set of named attributes for child nodes.
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.
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::
@ -618,13 +620,13 @@ XXX The magic :meth:`visit` method for visitors.
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

@ -220,17 +220,18 @@ The :mod:`csv` module defines the following classes:
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,7 +1443,7 @@ 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.
@ -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.
.. 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.
: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.
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.
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:
.. attribute:: _CData._b_base_
.. attribute:: _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.
:attr:`_b_base_` read-only member is the root ctypes object that owns the
memory block.
.. attribute:: _CData._b_needsfree_
.. attribute:: _b_needsfree_
This read-only variable is true when the ctypes data instance has allocated the
memory block itself, false otherwise.
This read-only variable is true when the ctypes data instance has
allocated the memory block itself, false otherwise.
.. attribute:: _CData._objects
.. 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.
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:
@ -2018,16 +2020,17 @@ Fundamental data types
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.
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
@ -2271,21 +2274,22 @@ 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.
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
@ -2293,38 +2297,38 @@ attribute accesses. These are the
...
]
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.
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.
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.
``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)::
@ -2339,11 +2343,12 @@ attribute accesses. These are the
_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

View File

@ -1575,19 +1575,21 @@ You can instantiate a :class:`Textbox` object as follows:
: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 |
@ -1624,8 +1626,8 @@ You can instantiate a :class:`Textbox` object as follows:
| :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 |
@ -1641,23 +1643,23 @@ You can instantiate a :class:`Textbox` object as follows:
| :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.
.. 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

View File

@ -351,23 +351,24 @@ Decimal objects
Decimal floating point objects share many properties with the other built-in
numeric types such as :class:`float` and :class:`int`. All of the usual math
operations and special methods apply. Likewise, decimal objects can be copied,
pickled, printed, used as dictionary keys, used as set elements, compared,
sorted, and coerced to another type (such as :class:`float` or :class:`long`).
operations and special methods apply. Likewise, decimal objects can be
copied, pickled, printed, used as dictionary keys, used as set elements,
compared, sorted, and coerced to another type (such as :class:`float` or
:class:`long`).
In addition to the standard numeric properties, decimal floating point objects
also have a number of specialized methods:
In addition to the standard numeric properties, decimal floating point
objects also have a number of specialized methods:
.. method:: Decimal.adjusted()
.. method:: adjusted()
Return the adjusted exponent after shifting out the coefficient's rightmost
digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
returns seven. Used for determining the position of the most significant digit
with respect to the decimal point.
Return the adjusted exponent after shifting out the coefficient's
rightmost digits until only the lead digit remains:
``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
position of the most significant digit with respect to the decimal point.
.. method:: Decimal.as_tuple()
.. method:: as_tuple()
Return a :term:`named tuple` representation of the number:
``DecimalTuple(sign, digits, exponent)``.
@ -376,97 +377,92 @@ also have a number of specialized methods:
Use a named tuple.
.. method:: Decimal.canonical()
.. method:: canonical()
Return the canonical encoding of the argument. Currently, the
encoding of a :class:`Decimal` instance is always canonical, so
this operation returns its argument unchanged.
Return the canonical encoding of the argument. Currently, the encoding of
a :class:`Decimal` instance is always canonical, so this operation returns
its argument unchanged.
.. versionadded:: 2.6
.. method:: Decimal.compare(other[, context])
.. method:: compare(other[, context])
Compare the values of two Decimal instances. This operation
behaves in the same way as the usual comparison method
:meth:`__cmp__`, except that :meth:`compare` returns a Decimal
instance rather than an integer, and if either operand is a NaN
then the result is a NaN::
Compare the values of two Decimal instances. This operation behaves in
the same way as the usual comparison method :meth:`__cmp__`, except that
:meth:`compare` returns a Decimal instance rather than an integer, and if
either operand is a NaN then the result is a NaN::
a or b is a NaN ==> Decimal('NaN')
a < b ==> Decimal('-1')
a == b ==> Decimal('0')
a > b ==> Decimal('1')
.. method:: Decimal.compare_signal(other[, context])
.. method:: compare_signal(other[, context])
This operation is identical to the :meth:`compare` method, except
that all NaNs signal. That is, if neither operand is a signaling
NaN then any quiet NaN operand is treated as though it were a
signaling NaN.
This operation is identical to the :meth:`compare` method, except that all
NaNs signal. That is, if neither operand is a signaling NaN then any
quiet NaN operand is treated as though it were a signaling NaN.
.. versionadded:: 2.6
.. method:: Decimal.compare_total(other)
.. method:: compare_total(other)
Compare two operands using their abstract representation rather
than their numerical value. Similar to the :meth:`compare` method,
but the result gives a total ordering on :class:`Decimal`
instances. Two :class:`Decimal` instances with the same numeric
value but different representations compare unequal in this
ordering:
Compare two operands using their abstract representation rather than their
numerical value. Similar to the :meth:`compare` method, but the result
gives a total ordering on :class:`Decimal` instances. Two
:class:`Decimal` instances with the same numeric value but different
representations compare unequal in this ordering:
>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')
Quiet and signaling NaNs are also included in the total ordering.
The result of this function is ``Decimal('0')`` if both operands
have the same representation, ``Decimal('-1')`` if the first
operand is lower in the total order than the second, and
``Decimal('1')`` if the first operand is higher in the total order
than the second operand. See the specification for details of the
total order.
Quiet and signaling NaNs are also included in the total ordering. The
result of this function is ``Decimal('0')`` if both operands have the same
representation, ``Decimal('-1')`` if the first operand is lower in the
total order than the second, and ``Decimal('1')`` if the first operand is
higher in the total order than the second operand. See the specification
for details of the total order.
.. versionadded:: 2.6
.. method:: Decimal.compare_total_mag(other)
.. method:: compare_total_mag(other)
Compare two operands using their abstract representation rather
than their value as in :meth:`compare_total`, but ignoring the sign
of each operand. ``x.compare_total_mag(y)`` is equivalent to
Compare two operands using their abstract representation rather than their
value as in :meth:`compare_total`, but ignoring the sign of each operand.
``x.compare_total_mag(y)`` is equivalent to
``x.copy_abs().compare_total(y.copy_abs())``.
.. versionadded:: 2.6
.. method:: Decimal.copy_abs()
.. method:: copy_abs()
Return the absolute value of the argument. This operation is
unaffected by the context and is quiet: no flags are changed and no
rounding is performed.
Return the absolute value of the argument. This operation is unaffected
by the context and is quiet: no flags are changed and no rounding is
performed.
.. versionadded:: 2.6
.. method:: Decimal.copy_negate()
.. method:: copy_negate()
Return the negation of the argument. This operation is unaffected
by the context and is quiet: no flags are changed and no rounding
is performed.
Return the negation of the argument. This operation is unaffected by the
context and is quiet: no flags are changed and no rounding is performed.
.. versionadded:: 2.6
.. method:: Decimal.copy_sign(other)
.. method:: copy_sign(other)
Return a copy of the first operand with the sign set to be the
same as the sign of the second operand. For example:
Return a copy of the first operand with the sign set to be the same as the
sign of the second operand. For example:
>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')
This operation is unaffected by the context and is quiet: no flags
are changed and no rounding is performed.
This operation is unaffected by the context and is quiet: no flags are
changed and no rounding is performed.
.. versionadded:: 2.6
.. method:: Decimal.exp([context])
.. method:: exp([context])
Return the value of the (natural) exponential function ``e**x`` at the
given number. The result is correctly rounded using the
@ -479,22 +475,21 @@ also have a number of specialized methods:
.. versionadded:: 2.6
.. method:: Decimal.fma(other, third[, context])
.. method:: fma(other, third[, context])
Fused multiply-add. Return self*other+third with no rounding of
the intermediate product self*other.
Fused multiply-add. Return self*other+third with no rounding of the
intermediate product self*other.
>>> Decimal(2).fma(3, 5)
Decimal('11')
.. versionadded:: 2.6
.. method:: Decimal.is_canonical()
.. method:: is_canonical()
Return :const:`True` if the argument is canonical and
:const:`False` otherwise. Currently, a :class:`Decimal` instance
is always canonical, so this operation always returns
:const:`True`.
Return :const:`True` if the argument is canonical and :const:`False`
otherwise. Currently, a :class:`Decimal` instance is always canonical, so
this operation always returns :const:`True`.
.. versionadded:: 2.6
@ -507,23 +502,22 @@ also have a number of specialized methods:
.. method:: is_infinite()
Return :const:`True` if the argument is either positive or
negative infinity and :const:`False` otherwise.
Return :const:`True` if the argument is either positive or negative
infinity and :const:`False` otherwise.
.. versionadded:: 2.6
.. method:: is_nan()
Return :const:`True` if the argument is a (quiet or signaling)
NaN and :const:`False` otherwise.
Return :const:`True` if the argument is a (quiet or signaling) NaN and
:const:`False` otherwise.
.. versionadded:: 2.6
.. method:: is_normal()
Return :const:`True` if the argument is a *normal* finite number.
Return :const:`False` if the argument is zero, subnormal, infinite
or a NaN.
Return :const:`True` if the argument is a *normal* finite number. Return
:const:`False` if the argument is zero, subnormal, infinite or a NaN.
.. versionadded:: 2.6
@ -537,66 +531,64 @@ also have a number of specialized methods:
.. method:: is_signed()
Return :const:`True` if the argument has a negative sign and
:const:`False` otherwise. Note that zeros and NaNs can both carry
signs.
:const:`False` otherwise. Note that zeros and NaNs can both carry signs.
.. versionadded:: 2.6
.. method:: is_snan()
Return :const:`True` if the argument is a signaling NaN and
:const:`False` otherwise.
Return :const:`True` if the argument is a signaling NaN and :const:`False`
otherwise.
.. versionadded:: 2.6
.. method:: is_subnormal()
Return :const:`True` if the argument is subnormal, and
:const:`False` otherwise.
Return :const:`True` if the argument is subnormal, and :const:`False`
otherwise.
.. versionadded:: 2.6
.. method:: is_zero()
Return :const:`True` if the argument is a (positive or negative)
zero and :const:`False` otherwise.
Return :const:`True` if the argument is a (positive or negative) zero and
:const:`False` otherwise.
.. versionadded:: 2.6
.. method:: Decimal.ln([context])
.. method:: ln([context])
Return the natural (base e) logarithm of the operand. The result
is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
mode.
.. versionadded:: 2.6
.. method:: Decimal.log10([context])
Return the base ten logarithm of the operand. The result is
Return the natural (base e) logarithm of the operand. The result is
correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
.. versionadded:: 2.6
.. method:: Decimal.logb([context])
.. method:: log10([context])
For a nonzero number, return the adjusted exponent of its operand
as a :class:`Decimal` instance. If the operand is a zero then
``Decimal('-Infinity')`` is returned and the
:const:`DivisionByZero` flag is raised. If the operand is an
infinity then ``Decimal('Infinity')`` is returned.
Return the base ten logarithm of the operand. The result is correctly
rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
.. versionadded:: 2.6
.. method:: Decimal.logical_and(other[, context])
.. method:: logb([context])
:meth:`logical_and` is a logical operation which takes two
*logical operands* (see :ref:`logical_operands_label`). The result
is the digit-wise ``and`` of the two operands.
For a nonzero number, return the adjusted exponent of its operand as a
:class:`Decimal` instance. If the operand is a zero then
``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
returned.
.. versionadded:: 2.6
.. method:: Decimal.logical_invert(other[, context])
.. method:: logical_and(other[, context])
:meth:`logical_and` is a logical operation which takes two *logical
operands* (see :ref:`logical_operands_label`). The result is the
digit-wise ``and`` of the two operands.
.. versionadded:: 2.6
.. method:: logical_invert(other[, context])
:meth:`logical_invert` is a logical operation. The argument must
be a *logical operand* (see :ref:`logical_operands_label`). The
@ -604,7 +596,7 @@ also have a number of specialized methods:
.. versionadded:: 2.6
.. method:: Decimal.logical_or(other[, context])
.. method:: logical_or(other[, context])
:meth:`logical_or` is a logical operation which takes two *logical
operands* (see :ref:`logical_operands_label`). The result is the
@ -612,77 +604,80 @@ also have a number of specialized methods:
.. versionadded:: 2.6
.. method:: Decimal.logical_xor(other[, context])
.. method:: logical_xor(other[, context])
:meth:`logical_xor` is a logical operation which takes two
*logical operands* (see :ref:`logical_operands_label`). The result
is the digit-wise exclusive or of the two operands.
:meth:`logical_xor` is a logical operation which takes two *logical
operands* (see :ref:`logical_operands_label`). The result is the
digit-wise exclusive or of the two operands.
.. versionadded:: 2.6
.. method:: Decimal.max(other[, context])
.. method:: max(other[, context])
Like ``max(self, other)`` except that the context rounding rule is applied
before returning and that :const:`NaN` values are either signaled or ignored
(depending on the context and whether they are signaling or quiet).
before returning and that :const:`NaN` values are either signaled or
ignored (depending on the context and whether they are signaling or
quiet).
.. method:: Decimal.max_mag(other[, context])
.. method:: max_mag(other[, context])
Similar to the :meth:`max` method, but the comparison is done using
the absolute values of the operands.
Similar to the :meth:`max` method, but the comparison is done using the
absolute values of the operands.
.. versionadded:: 2.6
.. method:: Decimal.min(other[, context])
.. method:: min(other[, context])
Like ``min(self, other)`` except that the context rounding rule is applied
before returning and that :const:`NaN` values are either signaled or ignored
(depending on the context and whether they are signaling or quiet).
before returning and that :const:`NaN` values are either signaled or
ignored (depending on the context and whether they are signaling or
quiet).
.. method:: Decimal.min_mag(other[, context])
.. method:: min_mag(other[, context])
Similar to the :meth:`min` method, but the comparison is done using
the absolute values of the operands.
Similar to the :meth:`min` method, but the comparison is done using the
absolute values of the operands.
.. versionadded:: 2.6
.. method:: Decimal.next_minus([context])
.. method:: next_minus([context])
Return the largest number representable in the given context (or
in the current thread's context if no context is given) that is smaller
than the given operand.
Return the largest number representable in the given context (or in the
current thread's context if no context is given) that is smaller than the
given operand.
.. versionadded:: 2.6
.. method:: Decimal.next_plus([context])
.. method:: next_plus([context])
Return the smallest number representable in the given context (or
in the current thread's context if no context is given) that is
larger than the given operand.
Return the smallest number representable in the given context (or in the
current thread's context if no context is given) that is larger than the
given operand.
.. versionadded:: 2.6
.. method:: Decimal.next_toward(other[, context])
.. method:: next_toward(other[, context])
If the two operands are unequal, return the number closest to the
first operand in the direction of the second operand. If both
operands are numerically equal, return a copy of the first operand
with the sign set to be the same as the sign of the second operand.
If the two operands are unequal, return the number closest to the first
operand in the direction of the second operand. If both operands are
numerically equal, return a copy of the first operand with the sign set to
be the same as the sign of the second operand.
.. versionadded:: 2.6
.. method:: Decimal.normalize([context])
.. method:: normalize([context])
Normalize the number by stripping the rightmost trailing zeros and converting
any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
producing canonical values for members of an equivalence class. For example,
``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
equivalent value ``Decimal('32.1')``.
Normalize the number by stripping the rightmost trailing zeros and
converting any result equal to :const:`Decimal('0')` to
:const:`Decimal('0e0')`. Used for producing canonical values for members
of an equivalence class. For example, ``Decimal('32.100')`` and
``Decimal('0.321000e+2')`` both normalize to the equivalent value
``Decimal('32.1')``.
.. method:: Decimal.number_class([context])
.. method:: number_class([context])
Return a string describing the *class* of the operand. The
returned value is one of the following ten strings.
Return a string describing the *class* of the operand. The returned value
is one of the following ten strings.
* ``"-Infinity"``, indicating that the operand is negative infinity.
* ``"-Normal"``, indicating that the operand is a negative normal number.
@ -697,134 +692,132 @@ also have a number of specialized methods:
.. versionadded:: 2.6
.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
.. method:: quantize(exp[, rounding[, context[, watchexp]]])
Return a value equal to the first operand after rounding and
having the exponent of the second operand.
Return a value equal to the first operand after rounding and having the
exponent of the second operand.
>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')
Unlike other operations, if the length of the coefficient after the
quantize operation would be greater than precision, then an
:const:`InvalidOperation` is signaled. This guarantees that, unless
there is an error condition, the quantized exponent is always equal
to that of the right-hand operand.
:const:`InvalidOperation` is signaled. This guarantees that, unless there
is an error condition, the quantized exponent is always equal to that of
the right-hand operand.
Also unlike other operations, quantize never signals Underflow,
even if the result is subnormal and inexact.
Also unlike other operations, quantize never signals Underflow, even if
the result is subnormal and inexact.
If the exponent of the second operand is larger than that of the
first then rounding may be necessary. In this case, the rounding
mode is determined by the ``rounding`` argument if given, else by
the given ``context`` argument; if neither argument is given the
rounding mode of the current thread's context is used.
If the exponent of the second operand is larger than that of the first
then rounding may be necessary. In this case, the rounding mode is
determined by the ``rounding`` argument if given, else by the given
``context`` argument; if neither argument is given the rounding mode of
the current thread's context is used.
If *watchexp* is set (default), then an error is returned whenever the
resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
resulting exponent is greater than :attr:`Emax` or less than
:attr:`Etiny`.
.. method:: Decimal.radix()
.. method:: radix()
Return ``Decimal(10)``, the radix (base) in which the
:class:`Decimal` class does all its arithmetic. Included for
compatibility with the specification.
Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
class does all its arithmetic. Included for compatibility with the
specification.
.. versionadded:: 2.6
.. method:: Decimal.remainder_near(other[, context])
.. method:: remainder_near(other[, context])
Compute the modulo as either a positive or negative value depending on which is
closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Compute the modulo as either a positive or negative value depending on
which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
If both are equally close, the one chosen will have the same sign as *self*.
If both are equally close, the one chosen will have the same sign as
*self*.
.. method:: Decimal.rotate(other[, context])
.. method:: rotate(other[, context])
Return the result of rotating the digits of the first operand by
an amount specified by the second operand. The second operand
must be an integer in the range -precision through precision. The
absolute value of the second operand gives the number of places to
rotate. If the second operand is positive then rotation is to the
left; otherwise rotation is to the right. The coefficient of the
first operand is padded on the left with zeros to length precision
if necessary. The sign and exponent of the first operand are
unchanged.
.. versionadded:: 2.6
.. method:: Decimal.same_quantum(other[, context])
Test whether self and other have the same exponent or whether both are
:const:`NaN`.
.. method:: Decimal.scaleb(other[, context])
Return the first operand with exponent adjusted by the second.
Equivalently, return the first operand multiplied by ``10**other``.
The second operand must be an integer.
.. versionadded:: 2.6
.. method:: Decimal.shift(other[, context])
Return the result of shifting the digits of the first operand by
an amount specified by the second operand. The second operand must
be an integer in the range -precision through precision. The
absolute value of the second operand gives the number of places to
shift. If the second operand is positive then the shift is to the
left; otherwise the shift is to the right. Digits shifted into the
coefficient are zeros. The sign and exponent of the first operand
Return the result of rotating the digits of the first operand by an amount
specified by the second operand. The second operand must be an integer in
the range -precision through precision. The absolute value of the second
operand gives the number of places to rotate. If the second operand is
positive then rotation is to the left; otherwise rotation is to the right.
The coefficient of the first operand is padded on the left with zeros to
length precision if necessary. The sign and exponent of the first operand
are unchanged.
.. versionadded:: 2.6
.. method:: Decimal.sqrt([context])
.. method:: same_quantum(other[, context])
Test whether self and other have the same exponent or whether both are
:const:`NaN`.
.. method:: scaleb(other[, context])
Return the first operand with exponent adjusted by the second.
Equivalently, return the first operand multiplied by ``10**other``. The
second operand must be an integer.
.. versionadded:: 2.6
.. method:: shift(other[, context])
Return the result of shifting the digits of the first operand by an amount
specified by the second operand. The second operand must be an integer in
the range -precision through precision. The absolute value of the second
operand gives the number of places to shift. If the second operand is
positive then the shift is to the left; otherwise the shift is to the
right. Digits shifted into the coefficient are zeros. The sign and
exponent of the first operand are unchanged.
.. versionadded:: 2.6
.. method:: sqrt([context])
Return the square root of the argument to full precision.
.. method:: Decimal.to_eng_string([context])
.. method:: to_eng_string([context])
Convert to an engineering-type string.
Engineering notation has an exponent which is a multiple of 3, so there are up
to 3 digits left of the decimal place. For example, converts
Engineering notation has an exponent which is a multiple of 3, so there
are up to 3 digits left of the decimal place. For example, converts
``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
.. method:: Decimal.to_integral([rounding[, context]])
.. method:: to_integral([rounding[, context]])
Identical to the :meth:`to_integral_value` method. The ``to_integral``
name has been kept for compatibility with older versions.
.. method:: Decimal.to_integral_exact([rounding[, context]])
.. method:: to_integral_exact([rounding[, context]])
Round to the nearest integer, signaling
:const:`Inexact` or :const:`Rounded` as appropriate if rounding
occurs. The rounding mode is determined by the ``rounding``
parameter if given, else by the given ``context``. If neither
parameter is given then the rounding mode of the current context is
used.
Round to the nearest integer, signaling :const:`Inexact` or
:const:`Rounded` as appropriate if rounding occurs. The rounding mode is
determined by the ``rounding`` parameter if given, else by the given
``context``. If neither parameter is given then the rounding mode of the
current context is used.
.. versionadded:: 2.6
.. method:: Decimal.to_integral_value([rounding[, context]])
.. method:: to_integral_value([rounding[, context]])
Round to the nearest integer without signaling :const:`Inexact` or
:const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
method in either the supplied *context* or the current context.
:const:`Rounded`. If given, applies *rounding*; otherwise, uses the
rounding method in either the supplied *context* or the current context.
.. versionchanged:: 2.6
renamed from ``to_integral`` to ``to_integral_value``. The old name
remains valid for compatibility.
.. method:: Decimal.trim()
.. method:: trim()
Return the decimal with *insignificant* trailing zeros removed.
Here, a trailing zero is considered insignificant either if it
follows the decimal point, or if the exponent of the argument (that
is, the last element of the :meth:`as_tuple` representation) is
positive.
Return the decimal with *insignificant* trailing zeros removed. Here, a
trailing zero is considered insignificant either if it follows the decimal
point, or if the exponent of the argument (that is, the last element of
the :meth:`as_tuple` representation) is positive.
.. versionadded:: 2.6
@ -970,38 +963,37 @@ In addition to the three supplied contexts, new contexts can be created with the
.. versionchanged:: 2.6
The :const:`ROUND_05UP` rounding mode was added.
The :class:`Context` class defines several general purpose methods as
well as a large number of methods for doing arithmetic directly in a
given context. In addition, for each of the :class:`Decimal` methods
described above (with the exception of the :meth:`adjusted` and
:meth:`as_tuple` methods) there is a corresponding :class:`Context`
method. For example, ``C.exp(x)`` is equivalent to
``x.exp(context=C)``.
The :class:`Context` class defines several general purpose methods as well as
a large number of methods for doing arithmetic directly in a given context.
In addition, for each of the :class:`Decimal` methods described above (with
the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
equivalent to ``x.exp(context=C)``.
.. method:: Context.clear_flags()
.. method:: clear_flags()
Resets all of the flags to :const:`0`.
.. method:: Context.copy()
.. method:: copy()
Return a duplicate of the context.
.. method:: Context.copy_decimal(num)
.. method:: copy_decimal(num)
Return a copy of the Decimal instance num.
.. method:: Context.create_decimal(num)
.. method:: create_decimal(num)
Creates a new Decimal instance from *num* but using *self* as context. Unlike
the :class:`Decimal` constructor, the context precision, rounding method, flags,
and traps are applied to the conversion.
Creates a new Decimal instance from *num* but using *self* as
context. Unlike the :class:`Decimal` constructor, the context precision,
rounding method, flags, and traps are applied to the conversion.
This is useful because constants are often given to a greater precision than is
needed by the application. Another benefit is that rounding immediately
eliminates unintended effects from digits beyond the current precision. In the
following example, using unrounded inputs means that adding zero to a sum can
change the result:
This is useful because constants are often given to a greater precision
than is needed by the application. Another benefit is that rounding
immediately eliminates unintended effects from digits beyond the current
precision. In the following example, using unrounded inputs means that
adding zero to a sum can change the result:
.. doctest:: newcontext
@ -1011,111 +1003,110 @@ method. For example, ``C.exp(x)`` is equivalent to
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44')
This method implements the to-number operation of the IBM
specification. If the argument is a string, no leading or trailing
whitespace is permitted.
This method implements the to-number operation of the IBM specification.
If the argument is a string, no leading or trailing whitespace is
permitted.
.. method:: Context.Etiny()
.. method:: Etiny()
Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
for subnormal results. When underflow occurs, the exponent is set to
:const:`Etiny`.
Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
value for subnormal results. When underflow occurs, the exponent is set
to :const:`Etiny`.
.. method:: Context.Etop()
.. method:: Etop()
Returns a value equal to ``Emax - prec + 1``.
The usual approach to working with decimals is to create :class:`Decimal`
instances and then apply arithmetic operations which take place within the
current context for the active thread. An alternative approach is to use context
methods for calculating within a specific context. The methods are similar to
those for the :class:`Decimal` class and are only briefly recounted here.
current context for the active thread. An alternative approach is to use
context methods for calculating within a specific context. The methods are
similar to those for the :class:`Decimal` class and are only briefly
recounted here.
.. method:: Context.abs(x)
.. method:: abs(x)
Returns the absolute value of *x*.
.. method:: Context.add(x, y)
.. method:: add(x, y)
Return the sum of *x* and *y*.
.. method:: Context.divide(x, y)
.. method:: divide(x, y)
Return *x* divided by *y*.
.. method:: Context.divide_int(x, y)
.. method:: divide_int(x, y)
Return *x* divided by *y*, truncated to an integer.
.. method:: Context.divmod(x, y)
.. method:: divmod(x, y)
Divides two numbers and returns the integer part of the result.
.. method:: Context.minus(x)
.. method:: minus(x)
Minus corresponds to the unary prefix minus operator in Python.
.. method:: Context.multiply(x, y)
.. method:: multiply(x, y)
Return the product of *x* and *y*.
.. method:: Context.plus(x)
.. method:: plus(x)
Plus corresponds to the unary prefix plus operator in Python. This operation
applies the context precision and rounding, so it is *not* an identity
operation.
Plus corresponds to the unary prefix plus operator in Python. This
operation applies the context precision and rounding, so it is *not* an
identity operation.
.. method:: Context.power(x, y[, modulo])
.. method:: power(x, y[, modulo])
Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
given.
Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
With two arguments, compute ``x**y``. If ``x`` is negative then
``y`` must be integral. The result will be inexact unless ``y`` is
integral and the result is finite and can be expressed exactly in
'precision' digits. The result should always be correctly rounded,
using the rounding mode of the current thread's context.
With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
must be integral. The result will be inexact unless ``y`` is integral and
the result is finite and can be expressed exactly in 'precision' digits.
The result should always be correctly rounded, using the rounding mode of
the current thread's context.
With three arguments, compute ``(x**y) % modulo``. For the three
argument form, the following restrictions on the arguments hold:
With three arguments, compute ``(x**y) % modulo``. For the three argument
form, the following restrictions on the arguments hold:
- all three arguments must be integral
- ``y`` must be nonnegative
- at least one of ``x`` or ``y`` must be nonzero
- ``modulo`` must be nonzero and have at most 'precision' digits
The result of ``Context.power(x, y, modulo)`` is identical to
the result that would be obtained by computing ``(x**y) %
modulo`` with unbounded precision, but is computed more
efficiently. It is always exact.
The result of ``Context.power(x, y, modulo)`` is identical to the result
that would be obtained by computing ``(x**y) % modulo`` with unbounded
precision, but is computed more efficiently. It is always exact.
.. versionchanged:: 2.6
``y`` may now be nonintegral in ``x**y``.
Stricter requirements for the three-argument version.
.. method:: Context.remainder(x, y)
.. method:: remainder(x, y)
Returns the remainder from integer division.
The sign of the result, if non-zero, is the same as that of the original
dividend.
.. method:: Context.subtract(x, y)
.. method:: subtract(x, y)
Return the difference between *x* and *y*.
.. method:: Context.to_sci_string(x)
.. method:: to_sci_string(x)
Converts a number to a string using scientific notation.
@ -1196,28 +1187,29 @@ condition.
Numerical overflow.
Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
If not trapped, the result depends on the rounding mode, either pulling inward
to the largest representable finite number or rounding outward to
:const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
also signaled.
Indicates the exponent is larger than :attr:`Emax` after rounding has
occurred. If not trapped, the result depends on the rounding mode, either
pulling inward to the largest representable finite number or rounding outward
to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
are also signaled.
.. class:: Rounded
Rounding occurred though possibly no information was lost.
Signaled whenever rounding discards digits; even if those digits are zero (such
as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
unchanged. This signal is used to detect loss of significant digits.
Signaled whenever rounding discards digits; even if those digits are zero
(such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
the result unchanged. This signal is used to detect loss of significant
digits.
.. class:: Subnormal
Exponent was lower than :attr:`Emin` prior to rounding.
Occurs when an operation result is subnormal (the exponent is too small). If not
trapped, returns the result unchanged.
Occurs when an operation result is subnormal (the exponent is too small). If
not trapped, returns the result unchanged.
.. class:: Underflow

View File

@ -353,54 +353,56 @@ The :class:`SequenceMatcher` class has this constructor:
: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.
: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.
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]``.
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)
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:
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)
@ -412,23 +414,23 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
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!
.. versionchanged:: 2.5
The guarantee that adjacent triples always describe non-adjacent blocks was
implemented.
The guarantee that adjacent triples always describe non-adjacent blocks
was implemented.
.. doctest::
@ -437,12 +439,12 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
.. 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:
@ -478,45 +480,48 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
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.
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`.
.. 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.
: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.
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.
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

View File

@ -1179,17 +1179,17 @@ 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.
.. 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
@ -1197,27 +1197,27 @@ by the constructor, and should not be modified directly.
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.
``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.
@ -1237,26 +1237,26 @@ 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.
.. attribute:: Example.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
single Python statement, and always ends with a newline; the constructor adds
a newline when necessary.
.. attribute:: Example.exc_msg
.. 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.
.. 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
@ -1265,24 +1265,24 @@ by the constructor, and should not be modified directly.
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.
.. 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.
.. 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
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.
@ -1317,18 +1317,18 @@ DocTestFinder objects
: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:
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.
@ -1348,8 +1348,8 @@ DocTestFinder objects
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
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 ``{}``.
@ -1370,7 +1370,7 @@ DocTestParser objects
: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.
@ -1380,17 +1380,17 @@ DocTestParser objects
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
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
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.
@ -1439,77 +1439,78 @@ DocTestRunner objects
: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.
*example* is the example about to be processed. *test* is the test containing
*example*. *out* is the output function that was passed to
*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.
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.
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.
*example* is the example about to be processed. *exc_info* is a tuple containing
information about the unexpected exception (as returned by
*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)``.
The optional *verbose* argument controls how detailed the summary is. If the
verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used.
verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
used.
.. versionchanged:: 2.6
Use a named tuple.
@ -1534,16 +1535,16 @@ OutputChecker objects
: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
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

View File

@ -43,161 +43,165 @@ Import this class from the :mod:`email.charset` module.
: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.
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
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:
.. method:: Charset.get_body_encoding()
.. method:: get_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*.
.. 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.
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.
.. method:: Charset.header_encode(s[, convert])
.. method:: header_encode(s[, convert])
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.
.. method:: Charset.body_encode(s[, convert])
.. method:: body_encode(s[, convert])
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 :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

@ -47,36 +47,37 @@ Here are the public methods of the :class:`Generator` class, imported from the
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.
.. 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
.. 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.
: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

@ -79,62 +79,64 @@ Here is the :class:`Header` class description:
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.
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.
: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".
.. 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)``.
.. 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,16 +36,17 @@ 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
@ -55,93 +56,96 @@ Here are the methods of the :class:`Message` class:
text = fp.getvalue()
.. method:: Message.__str__()
.. method:: __str__()
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.
.. 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.
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.
.. 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`.
: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.
*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
.. 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
@ -149,11 +153,11 @@ 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.
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.
@ -162,36 +166,37 @@ 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.
.. 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']
.. 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
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
@ -201,59 +206,62 @@ included in the mapping interface.
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.
.. method:: Message.keys()
.. method:: keys()
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.
.. 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``).
:meth:`__getitem__` except that optional *failobj* is returned if the
named header is missing (defaults to ``None``).
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::
@ -264,198 +272,206 @@ Here are some additional useful methods:
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
.. 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
.. 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
.. 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
.. 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
.. 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
.. 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`.
:mailheader:`Content-Type` header. Optional *header* is the header to
search instead of :mailheader:`Content-Type`.
.. 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`.
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::
: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)
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.
.. 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
.. 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`.
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
.. 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.
:mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
header is also added.
.. 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`.
: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.
*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.
: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
@ -467,28 +483,29 @@ Here are some additional useful methods:
.. 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()
@ -507,42 +524,44 @@ Here are some additional useful methods:
which can be used when generating the plain text of a MIME message.
.. data:: preamble
.. attribute:: preamble
The format of a MIME document allows for some text between the blank line
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.
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.
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``.
Note that if the message object has no preamble, the *preamble* attribute
will be ``None``.
.. data:: epilogue
.. 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.
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.
.. data:: defects
.. 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.
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).
: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
@ -122,17 +123,17 @@ class.
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.
@ -140,15 +141,16 @@ The other public :class:`Parser` methods are:
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.
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.

View File

@ -69,85 +69,88 @@ The :class:`dircmp` class
The :class:`dircmp` class provides the following methods:
.. method:: dircmp.report()
.. method:: report()
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*.
.. attribute:: dircmp.right_list
.. attribute:: right_list
Files and subdirectories in *b*, filtered by *hide* and *ignore*.
.. attribute:: dircmp.common
.. attribute:: common
Files and subdirectories in both *a* and *b*.
.. attribute:: dircmp.left_only
.. attribute:: left_only
Files and subdirectories only in *a*.
.. attribute:: dircmp.right_only
.. attribute:: right_only
Files and subdirectories only in *b*.
.. attribute:: dircmp.common_dirs
.. attribute:: common_dirs
Subdirectories in both *a* and *b*.
.. attribute:: dircmp.common_files
.. attribute:: common_files
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*.
.. attribute:: dircmp.diff_files
.. attribute:: diff_files
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.
.. attribute:: dircmp.subdirs
.. attribute:: subdirs
A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects.

View File

@ -31,26 +31,24 @@ 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)
@ -65,26 +63,26 @@ Fraction number class.
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,12 +50,13 @@ 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
@ -75,8 +76,8 @@ The module defines the following items:
.. 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,78 +249,82 @@ 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
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.
.. method:: NullTranslations.lgettext(message)
If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise,
return the translated message. Overridden in derived classes.
.. versionadded:: 2.4
.. method:: NullTranslations.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
If a fallback has been set, forward :meth:`gettext` to the
fallback. Otherwise, return the translated message. Overridden in derived
classes.
.. method:: NullTranslations.ngettext(singular, plural, n)
.. method:: lgettext(message)
If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise,
return the translated message. Overridden in derived classes.
.. versionadded:: 2.3
.. method:: NullTranslations.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:`lgettext` to the
fallback. Otherwise, return the translated message. Overridden in derived
classes.
.. versionadded:: 2.4
.. method:: NullTranslations.ungettext(singular, plural, n)
.. method:: ugettext(message)
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:`ugettext` to the
fallback. Otherwise, return the translated message as a Unicode
string. Overridden in derived classes.
.. 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.
.. versionadded:: 2.3
.. method:: NullTranslations.info()
.. 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.
.. versionadded:: 2.4
.. 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.
.. versionadded:: 2.3
.. method:: info()
Return the "protected" :attr:`_info` variable.
.. method:: NullTranslations.charset()
.. method:: charset()
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.
@ -328,7 +332,7 @@ are the methods of :class:`NullTranslations`:
.. 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.
@ -336,31 +340,32 @@ are the methods of :class:`NullTranslations`:
.. 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
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.

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.
: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,12 +1546,12 @@ sends logging output to a disk file. It inherits the output functionality from
first call to :meth:`emit`. By default, the file grows indefinitely.
.. method:: FileHandler.close()
.. method:: close()
Closes the file.
.. method:: FileHandler.emit(record)
.. method:: emit(record)
Outputs the record to the file.
@ -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.
.. 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,12 +1678,12 @@ 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.
.. method:: TimedRotatingFileHandler.emit(record)
.. method:: emit(record)
Outputs the record to the file, catering for rollover as described above.
@ -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.
.. 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
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,21 +1755,21 @@ 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.
@ -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.
.. 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.
.. 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.
.. 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,23 +1954,25 @@ 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.
.. method:: MemoryHandler.shouldFlush(record)
.. method:: shouldFlush(record)
Checks for buffer full or a record at the *flushLevel* or higher.
@ -1989,7 +1993,7 @@ 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.
@ -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.
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,11 +2174,12 @@ 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.
LoggerAdapter Objects
---------------------
@ -2186,12 +2196,12 @@ __ 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
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

File diff suppressed because it is too large Load Diff

View File

@ -140,13 +140,13 @@ memory but does not update the underlying file.
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.
.. 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*].
@ -154,7 +154,7 @@ Memory-mapped file objects support the following methods:
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
@ -169,40 +169,40 @@ Memory-mapped file objects support the following methods:
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.
.. 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.
.. method:: mmap.readline()
.. method:: readline()
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.
.. 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*].
@ -210,34 +210,34 @@ Memory-mapped file objects support the following methods:
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).
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.
.. method:: mmap.tell()
.. method:: tell()
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

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,16 +320,17 @@ 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.
.. 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.
@ -353,31 +354,31 @@ 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.
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.
@ -403,7 +404,7 @@ 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
@ -430,17 +431,17 @@ 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.
.. method:: Control.mapping(event, attribute)
.. method:: mapping(event, attribute)
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.
@ -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*.
*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,40 +466,41 @@ 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.
.. method:: Dialog.bitmap(name, x, y, width, height, text)
.. method:: bitmap(name, x, y, width, height, text)
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.
.. 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.
.. 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.
.. 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.

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.
.. attribute:: Complex.imag
.. attribute:: imag
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,11 +62,11 @@ The numeric tower
should be in lowest terms. With these, it provides a default for
:func:`float`.
.. attribute:: Rational.numerator
.. attribute:: numerator
Abstract.
.. attribute:: Rational.denominator
.. attribute:: denominator
Abstract.

View File

@ -259,14 +259,14 @@ The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
: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.
.. 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
@ -310,20 +310,21 @@ instance. If the same object is pickled by multiple :meth:`dump` calls, the
: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
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

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

@ -26,52 +26,54 @@ The :mod:`SimpleHTTPServer` module defines the following class:
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:
.. 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
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.
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.

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

@ -263,34 +263,34 @@ The :mod:`struct` module also defines the following type:
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`.)
.. 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.
.. method:: Struct.unpack(string)
.. method:: unpack(string)
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`).
.. attribute:: Struct.format
.. attribute:: format
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`.

View File

@ -91,21 +91,21 @@ 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`,
(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
@ -113,43 +113,44 @@ constructor) are as follows:
.. 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.
.. 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 [...]
@ -159,34 +160,34 @@ constructor) are as follows:
: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
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:
.. 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.
: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.
.. 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,25 +421,25 @@ 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.
.. 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.
@ -457,18 +459,18 @@ XMLTreeBuilder Objects
instance of the standard TreeBuilder class.
.. method:: XMLTreeBuilder.close()
.. method:: close()
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.

View File

@ -31,211 +31,220 @@ parsing text files formatted in XML (Extensible Markup Language).
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`.
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'``.
.. 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).
.. 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.
.. 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.
.. 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
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.
.. 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
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.
.. 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,52 +76,54 @@ 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.
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.
.. 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
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.
.. attribute:: zipimporter.prefix
.. attribute:: prefix
The path within the ZIP file where modules are searched; see
:class:`zipimporter` for details.