diff options
author | Benjamin Peterson <benjamin@python.org> | 2008-04-25 01:59:09 (GMT) |
---|---|---|
committer | Benjamin Peterson <benjamin@python.org> | 2008-04-25 01:59:09 (GMT) |
commit | e41251e864e94885d785b5a9bf8f824753316296 (patch) | |
tree | f530db7682d71f4920b22b8d7f84c89727647ab5 /Doc/library | |
parent | 768db92b438038586c1580b711c528363a97d3f4 (diff) | |
download | cpython-e41251e864e94885d785b5a9bf8f824753316296.zip cpython-e41251e864e94885d785b5a9bf8f824753316296.tar.gz cpython-e41251e864e94885d785b5a9bf8f824753316296.tar.bz2 |
Merged revisions 62490 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r62490 | benjamin.peterson | 2008-04-24 20:29:10 -0500 (Thu, 24 Apr 2008) | 2 lines
reformat some documentation of classes so methods and attributes are under the class directive
........
Diffstat (limited to 'Doc/library')
40 files changed, 3443 insertions, 3380 deletions
diff --git a/Doc/library/asynchat.rst b/Doc/library/asynchat.rst index 8e9437d..6f15441 100644 --- a/Doc/library/asynchat.rst +++ b/Doc/library/asynchat.rst @@ -197,10 +197,10 @@ asynchat - Auxiliary Classes and Functions the data no larger than *buffer_size*. -.. method:: simple_producer.more() + .. method:: more() - Produces the next chunk of information from the producer, or returns the - empty string. + Produces the next chunk of information from the producer, or returns the + empty string. .. class:: fifo([list=None]) @@ -212,26 +212,26 @@ asynchat - Auxiliary Classes and Functions producers or data items to be written to the channel. -.. method:: fifo.is_empty() + .. method:: is_empty() - Returns ``True`` if and only if the fifo is empty. + Returns ``True`` if and only if the fifo is empty. -.. method:: fifo.first() + .. method:: first() - Returns the least-recently :meth:`push`\ ed item from the fifo. + Returns the least-recently :meth:`push`\ ed item from the fifo. -.. method:: fifo.push(data) + .. method:: push(data) - Adds the given data (which may be a string or a producer object) to the - producer fifo. + Adds the given data (which may be a string or a producer object) to the + producer fifo. -.. method:: fifo.pop() + .. method:: pop() - If the fifo is not empty, returns ``True, first()``, deleting the popped - item. Returns ``False, None`` for an empty fifo. + If the fifo is not empty, returns ``True, first()``, deleting the popped + item. Returns ``False, None`` for an empty fifo. The :mod:`asynchat` module also defines one utility function, which may be of use in network and textual analysis operations. diff --git a/Doc/library/asyncore.rst b/Doc/library/asyncore.rst index 6830bae..7242e73 100644 --- a/Doc/library/asyncore.rst +++ b/Doc/library/asyncore.rst @@ -95,132 +95,132 @@ any that have been added to the map during asynchronous service) is closed. should be added to the list of channels :cfunc:`select`\ ed or :cfunc:`poll`\ ed for read and write events. -Thus, the set of channel events is larger than the basic socket events. The -full set of methods that can be overridden in your subclass follows: + Thus, the set of channel events is larger than the basic socket events. The + full set of methods that can be overridden in your subclass follows: -.. method:: dispatcher.handle_read() + .. method:: handle_read() - Called when the asynchronous loop detects that a :meth:`read` call on the - channel's socket will succeed. + Called when the asynchronous loop detects that a :meth:`read` call on the + channel's socket will succeed. -.. method:: dispatcher.handle_write() + .. method:: handle_write() - Called when the asynchronous loop detects that a writable socket can be - written. Often this method will implement the necessary buffering for - performance. For example:: + Called when the asynchronous loop detects that a writable socket can be + written. Often this method will implement the necessary buffering for + performance. For example:: - def handle_write(self): - sent = self.send(self.buffer) - self.buffer = self.buffer[sent:] + def handle_write(self): + sent = self.send(self.buffer) + self.buffer = self.buffer[sent:] -.. method:: dispatcher.handle_expt() + .. method:: handle_expt() - Called when there is out of band (OOB) data for a socket connection. This - will almost never happen, as OOB is tenuously supported and rarely used. + Called when there is out of band (OOB) data for a socket connection. This + will almost never happen, as OOB is tenuously supported and rarely used. -.. method:: dispatcher.handle_connect() + .. method:: handle_connect() - Called when the active opener's socket actually makes a connection. Might - send a "welcome" banner, or initiate a protocol negotiation with the remote - endpoint, for example. + Called when the active opener's socket actually makes a connection. Might + send a "welcome" banner, or initiate a protocol negotiation with the + remote endpoint, for example. -.. method:: dispatcher.handle_close() + .. method:: handle_close() - Called when the socket is closed. + Called when the socket is closed. -.. method:: dispatcher.handle_error() + .. method:: handle_error() - Called when an exception is raised and not otherwise handled. The default - version prints a condensed traceback. + Called when an exception is raised and not otherwise handled. The default + version prints a condensed traceback. -.. method:: dispatcher.handle_accept() + .. method:: handle_accept() - Called on listening channels (passive openers) when a connection can be - established with a new remote endpoint that has issued a :meth:`connect` - call for the local endpoint. + Called on listening channels (passive openers) when a connection can be + established with a new remote endpoint that has issued a :meth:`connect` + call for the local endpoint. -.. method:: dispatcher.readable() + .. method:: readable() - Called each time around the asynchronous loop to determine whether a - channel's socket should be added to the list on which read events can - occur. The default method simply returns ``True``, indicating that by - default, all channels will be interested in read events. + Called each time around the asynchronous loop to determine whether a + channel's socket should be added to the list on which read events can + occur. The default method simply returns ``True``, indicating that by + default, all channels will be interested in read events. -.. method:: dispatcher.writable() + .. method:: writable() - Called each time around the asynchronous loop to determine whether a - channel's socket should be added to the list on which write events can - occur. The default method simply returns ``True``, indicating that by - default, all channels will be interested in write events. + 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. + In addition, each channel delegates or extends many of the socket methods. + Most of these are nearly identical to their socket partners. -.. method:: dispatcher.create_socket(family, type) - This is identical to the creation of a normal socket, and will use the same - options for creation. Refer to the :mod:`socket` documentation for - information on creating sockets. + .. 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 + information on creating sockets. -.. method:: dispatcher.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:: 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) - Send *data* to the remote end-point of the socket. + .. method:: send(data) + Send *data* to the remote end-point of the socket. -.. method:: dispatcher.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. + .. 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. -.. method:: dispatcher.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:: 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) - Bind the socket to *address*. The socket must not already be bound. (The - format of *address* depends on the address family --- see above.) To mark - the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call - the :class:`dispatcher` object's :meth:`set_reuse_addr` method. + .. method:: 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 + the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call + the :class:`dispatcher` object's :meth:`set_reuse_addr` method. -.. method:: dispatcher.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 - *conn* is a *new* socket object usable to send and receive data on the - connection, and *address* is the address bound to the socket on the other - end of the connection. + .. method:: 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 + *conn* is a *new* socket object usable to send and receive data on the + connection, and *address* is the address bound to the socket on the other + end of the connection. -.. method:: dispatcher.close() - Close the socket. All future operations on the socket object will fail. - The remote end-point will receive no more data (after queued data is - flushed). Sockets are automatically closed when they are - garbage-collected. + .. method:: close() + + Close the socket. All future operations on the socket object will fail. + The remote end-point will receive no more data (after queued data is + flushed). Sockets are automatically closed when they are + garbage-collected. .. _asyncore-example: diff --git a/Doc/library/basehttpserver.rst b/Doc/library/basehttpserver.rst index b527163..14f32e7 100644 --- a/Doc/library/basehttpserver.rst +++ b/Doc/library/basehttpserver.rst @@ -34,216 +34,224 @@ to a handler. Code to create and run the server looks like this:: .. class:: HTTPServer(server_address, RequestHandlerClass) - This class builds on the :class:`TCPServer` class by storing the server address - as instance variables named :attr:`server_name` and :attr:`server_port`. The - server is accessible by the handler, typically through the handler's - :attr:`server` instance variable. + This class builds on the :class:`TCPServer` class by storing the server + address as instance variables named :attr:`server_name` and + :attr:`server_port`. The server is accessible by the handler, typically + through the handler's :attr:`server` instance variable. .. class:: BaseHTTPRequestHandler(request, client_address, server) This class is used to handle the HTTP requests that arrive at the server. By - itself, it cannot respond to any actual HTTP requests; it must be subclassed to - handle each request method (e.g. GET or POST). :class:`BaseHTTPRequestHandler` - provides a number of class and instance variables, and methods for use by - subclasses. + itself, it cannot respond to any actual HTTP requests; it must be subclassed + to handle each request method (e.g. GET or + POST). :class:`BaseHTTPRequestHandler` provides a number of class and + instance variables, and methods for use by subclasses. - The handler will parse the request and the headers, then call a method specific - to the request type. The method name is constructed from the request. For - example, for the request method ``SPAM``, the :meth:`do_SPAM` method will be - called with no arguments. All of the relevant information is stored in instance - variables of the handler. Subclasses should not need to override or extend the - :meth:`__init__` method. + The handler will parse the request and the headers, then call a method + specific to the request type. The method name is constructed from the + request. For example, for the request method ``SPAM``, the :meth:`do_SPAM` + method will be called with no arguments. All of the relevant information is + stored in instance variables of the handler. Subclasses should not need to + override or extend the :meth:`__init__` method. -:class:`BaseHTTPRequestHandler` has the following instance variables: + :class:`BaseHTTPRequestHandler` has the following instance variables: -.. attribute:: BaseHTTPRequestHandler.client_address + .. attribute:: client_address - Contains a tuple of the form ``(host, port)`` referring to the client's address. + Contains a tuple of the form ``(host, port)`` referring to the client's + address. -.. attribute:: BaseHTTPRequestHandler.command + .. attribute:: command - Contains the command (request type). For example, ``'GET'``. + Contains the command (request type). For example, ``'GET'``. -.. attribute:: BaseHTTPRequestHandler.path + .. attribute:: path - Contains the request path. + Contains the request path. -.. attribute:: BaseHTTPRequestHandler.request_version + .. attribute:: request_version - Contains the version string from the request. For example, ``'HTTP/1.0'``. + Contains the version string from the request. For example, ``'HTTP/1.0'``. -.. attribute:: BaseHTTPRequestHandler.headers + .. attribute:: headers - Holds an instance of the class specified by the :attr:`MessageClass` class - variable. This instance parses and manages the headers in the HTTP request. + Holds an instance of the class specified by the :attr:`MessageClass` class + variable. This instance parses and manages the headers in the HTTP + request. -.. attribute:: BaseHTTPRequestHandler.rfile + .. attribute:: rfile - Contains an input stream, positioned at the start of the optional input data. + Contains an input stream, positioned at the start of the optional input + data. -.. attribute:: BaseHTTPRequestHandler.wfile + .. attribute:: wfile - Contains the output stream for writing a response back to the client. Proper - adherence to the HTTP protocol must be used when writing to this stream. + Contains the output stream for writing a response back to the + client. Proper adherence to the HTTP protocol must be used when writing to + this stream. -:class:`BaseHTTPRequestHandler` has the following class variables: + :class:`BaseHTTPRequestHandler` has the following class variables: -.. attribute:: BaseHTTPRequestHandler.server_version - Specifies the server software version. You may want to override this. The - format is multiple whitespace-separated strings, where each string is of the - form name[/version]. For example, ``'BaseHTTP/0.2'``. + .. attribute:: server_version + Specifies the server software version. You may want to override this. The + format is multiple whitespace-separated strings, where each string is of + the form name[/version]. For example, ``'BaseHTTP/0.2'``. -.. attribute:: BaseHTTPRequestHandler.sys_version - Contains the Python system version, in a form usable by the - :attr:`version_string` method and the :attr:`server_version` class variable. For - example, ``'Python/1.4'``. + .. attribute:: sys_version + Contains the Python system version, in a form usable by the + :attr:`version_string` method and the :attr:`server_version` class + variable. For example, ``'Python/1.4'``. -.. attribute:: BaseHTTPRequestHandler.error_message_format - Specifies a format string for building an error response to the client. It uses - parenthesized, keyed format specifiers, so the format operand must be a - dictionary. The *code* key should be an integer, specifying the numeric HTTP - error code value. *message* should be a string containing a (detailed) error - message of what occurred, and *explain* should be an explanation of the error - code number. Default *message* and *explain* values can found in the *responses* - class variable. + .. attribute:: error_message_format + Specifies a format string for building an error response to the client. It + uses parenthesized, keyed format specifiers, so the format operand must be + a dictionary. The *code* key should be an integer, specifying the numeric + HTTP error code value. *message* should be a string containing a + (detailed) error message of what occurred, and *explain* should be an + explanation of the error code number. Default *message* and *explain* + values can found in the *responses* class variable. -.. attribute:: BaseHTTPRequestHandler.error_content_type - Specifies the Content-Type HTTP header of error responses sent to the client. - The default value is ``'text/html'``. + .. attribute:: error_content_type + Specifies the Content-Type HTTP header of error responses sent to the + client. The default value is ``'text/html'``. -.. attribute:: BaseHTTPRequestHandler.protocol_version - This specifies the HTTP protocol version used in responses. If set to - ``'HTTP/1.1'``, the server will permit HTTP persistent connections; however, - your server *must* then include an accurate ``Content-Length`` header (using - :meth:`send_header`) in all of its responses to clients. For backwards - compatibility, the setting defaults to ``'HTTP/1.0'``. + .. attribute:: protocol_version + This specifies the HTTP protocol version used in responses. If set to + ``'HTTP/1.1'``, the server will permit HTTP persistent connections; + however, your server *must* then include an accurate ``Content-Length`` + header (using :meth:`send_header`) in all of its responses to clients. + For backwards compatibility, the setting defaults to ``'HTTP/1.0'``. -.. attribute:: BaseHTTPRequestHandler.MessageClass - .. index:: single: Message (in module mimetools) + .. attribute:: MessageClass - Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. - Typically, this is not overridden, and it defaults to - :class:`mimetools.Message`. + .. index:: single: Message (in module mimetools) + Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. + Typically, this is not overridden, and it defaults to + :class:`mimetools.Message`. -.. attribute:: BaseHTTPRequestHandler.responses - This variable contains a mapping of error code integers to two-element tuples - containing a short and long message. For example, ``{code: (shortmessage, - longmessage)}``. The *shortmessage* is usually used as the *message* key in an - error response, and *longmessage* as the *explain* key (see the - :attr:`error_message_format` class variable). + .. attribute:: responses -A :class:`BaseHTTPRequestHandler` instance has the following methods: + This variable contains a mapping of error code integers to two-element tuples + containing a short and long message. For example, ``{code: (shortmessage, + longmessage)}``. The *shortmessage* is usually used as the *message* key in an + error response, and *longmessage* as the *explain* key (see the + :attr:`error_message_format` class variable). -.. method:: BaseHTTPRequestHandler.handle() + A :class:`BaseHTTPRequestHandler` instance has the following methods: - Calls :meth:`handle_one_request` once (or, if persistent connections are - enabled, multiple times) to handle incoming HTTP requests. You should never need - to override it; instead, implement appropriate :meth:`do_\*` methods. + .. method:: handle() -.. method:: BaseHTTPRequestHandler.handle_one_request() + Calls :meth:`handle_one_request` once (or, if persistent connections are + enabled, multiple times) to handle incoming HTTP requests. You should + never need to override it; instead, implement appropriate :meth:`do_\*` + methods. - This method will parse and dispatch the request to the appropriate :meth:`do_\*` - method. You should never need to override it. + .. method:: handle_one_request() -.. method:: BaseHTTPRequestHandler.send_error(code[, message]) + This method will parse and dispatch the request to the appropriate + :meth:`do_\*` method. You should never need to override it. - Sends and logs a complete error reply to the client. The numeric *code* - specifies the HTTP error code, with *message* as optional, more specific text. A - complete set of headers is sent, followed by text composed using the - :attr:`error_message_format` class variable. + .. method:: send_error(code[, message]) -.. method:: BaseHTTPRequestHandler.send_response(code[, message]) + Sends and logs a complete error reply to the client. The numeric *code* + specifies the HTTP error code, with *message* as optional, more specific text. A + complete set of headers is sent, followed by text composed using the + :attr:`error_message_format` class variable. - Sends a response header and logs the accepted request. The HTTP response line is - sent, followed by *Server* and *Date* headers. The values for these two headers - are picked up from the :meth:`version_string` and :meth:`date_time_string` - methods, respectively. + .. method:: send_response(code[, message]) -.. method:: BaseHTTPRequestHandler.send_header(keyword, value) + Sends a response header and logs the accepted request. The HTTP response + line is sent, followed by *Server* and *Date* headers. The values for + these two headers are picked up from the :meth:`version_string` and + :meth:`date_time_string` methods, respectively. - Writes a specific HTTP header to the output stream. *keyword* should specify the - header keyword, with *value* specifying its value. + .. method:: send_header(keyword, value) -.. method:: BaseHTTPRequestHandler.end_headers() + Writes a specific HTTP header to the output stream. *keyword* should + specify the header keyword, with *value* specifying its value. - Sends a blank line, indicating the end of the HTTP headers in the response. + .. method:: end_headers() -.. method:: BaseHTTPRequestHandler.log_request([code[, size]]) + Sends a blank line, indicating the end of the HTTP headers in the + response. - Logs an accepted (successful) request. *code* should specify the numeric HTTP - code associated with the response. If a size of the response is available, then - it should be passed as the *size* parameter. + .. method:: log_request([code[, size]]) -.. method:: BaseHTTPRequestHandler.log_error(...) + Logs an accepted (successful) request. *code* should specify the numeric + HTTP code associated with the response. If a size of the response is + available, then it should be passed as the *size* parameter. - Logs an error when a request cannot be fulfilled. By default, it passes the - message to :meth:`log_message`, so it takes the same arguments (*format* and - additional values). + .. method:: log_error(...) -.. method:: BaseHTTPRequestHandler.log_message(format, ...) + Logs an error when a request cannot be fulfilled. By default, it passes + the message to :meth:`log_message`, so it takes the same arguments + (*format* and additional values). - Logs an arbitrary message to ``sys.stderr``. This is typically overridden to - create custom error logging mechanisms. The *format* argument is a standard - printf-style format string, where the additional arguments to - :meth:`log_message` are applied as inputs to the formatting. The client address - and current date and time are prefixed to every message logged. + .. method:: log_message(format, ...) -.. method:: BaseHTTPRequestHandler.version_string() + Logs an arbitrary message to ``sys.stderr``. This is typically overridden + to create custom error logging mechanisms. The *format* argument is a + standard printf-style format string, where the additional arguments to + :meth:`log_message` are applied as inputs to the formatting. The client + address and current date and time are prefixed to every message logged. - Returns the server software's version string. This is a combination of the - :attr:`server_version` and :attr:`sys_version` class variables. + .. method:: version_string() -.. method:: BaseHTTPRequestHandler.date_time_string([timestamp]) + Returns the server software's version string. This is a combination of the + :attr:`server_version` and :attr:`sys_version` class variables. - Returns the date and time given by *timestamp* (which must be in the format - returned by :func:`time.time`), formatted for a message header. If *timestamp* - is omitted, it uses the current date and time. - The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. + .. method:: date_time_string([timestamp]) + 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. -.. method:: BaseHTTPRequestHandler.log_date_time_string() + The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. - Returns the current date and time, formatted for logging. + .. method:: log_date_time_string() -.. method:: BaseHTTPRequestHandler.address_string() + Returns the current date and time, formatted for logging. - Returns the client address, formatted for logging. A name lookup is performed on - the client's IP address. + + .. method:: address_string() + + Returns the client address, formatted for logging. A name lookup is + performed on the client's IP address. .. seealso:: diff --git a/Doc/library/bdb.rst b/Doc/library/bdb.rst index 84ea0ae..f04b671 100644 --- a/Doc/library/bdb.rst +++ b/Doc/library/bdb.rst @@ -31,32 +31,35 @@ The :mod:`bdb` module also defines two classes: first line of that function is executed. A conditional breakpoint always counts a hit. -:class:`Breakpoint` instances have the following methods: + :class:`Breakpoint` instances have the following methods: -.. method:: Breakpoint.deleteMe() + .. method:: deleteMe() - Delete the breakpoint from the list associated to a file/line. If it is the - last breakpoint in that position, it also deletes the entry for the - file/line. + Delete the breakpoint from the list associated to a file/line. If it is + the last breakpoint in that position, it also deletes the entry for the + file/line. -.. method:: Breakpoint.enable() - Mark the breakpoint as enabled. + .. method:: enable() -.. method:: Breakpoint.disable() + Mark the breakpoint as enabled. - Mark the breakpoint as disabled. -.. method:: Breakpoint.bpprint([out]) + .. method:: disable() - Print all the information about the breakpoint: + Mark the breakpoint as disabled. - * The breakpoint number. - * If it is temporary or not. - * Its file,line position. - * The condition that causes a break. - * If it must be ignored the next N times. - * The breakpoint hit count. + + .. method:: pprint([out]) + + Print all the information about the breakpoint: + + * The breakpoint number. + * If it is temporary or not. + * Its file,line position. + * The condition that causes a break. + * If it must be ignored the next N times. + * The breakpoint hit count. .. class:: Bdb() @@ -68,247 +71,246 @@ The :mod:`bdb` module also defines two classes: (:class:`pdb.Pdb`) is an example. -The following methods of :class:`Bdb` normally don't need to be overridden. - -.. method:: Bdb.canonic(filename) + The following methods of :class:`Bdb` normally don't need to be overridden. - 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:: canonic(filename) -.. method:: Bdb.reset() + 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. - Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and - :attr:`quitting` attributes with values ready to start debugging. + .. 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). + This function is installed as the trace function of debugged frames. Its + return value is the new trace function (in most cases, that is, itself). - The default implementation decides how to dispatch a frame, depending on the - type of event (passed as a string) that is about to be executed. *event* can - be one of the following: + The default implementation decides how to dispatch a frame, depending on + the type of event (passed as a string) that is about to be executed. + *event* can be one of the following: - * ``"line"``: A new line of code is going to be executed. - * ``"call"``: A function is about to be called, or another code block - entered. - * ``"return"``: A function or other code block is about to return. - * ``"exception"``: An exception has occurred. - * ``"c_call"``: A C function is about to be called. - * ``"c_return"``: A C function has returned. - * ``"c_exception"``: A C function has thrown an exception. + * ``"line"``: A new line of code is going to be executed. + * ``"call"``: A function is about to be called, or another code block + entered. + * ``"return"``: A function or other code block is about to return. + * ``"exception"``: An exception has occurred. + * ``"c_call"``: A C function is about to be called. + * ``"c_return"``: A C function has returned. + * ``"c_exception"``: A C function has thrown an exception. - For the Python events, specialized functions (see below) are called. For the - C events, no action is taken. + For the Python events, specialized functions (see below) are called. For + the C events, no action is taken. - The *arg* parameter depends on the previous event. + The *arg* parameter depends on the previous event. - For more information on trace functions, see :ref:`debugger-hooks`. For more - information on code and frame objects, refer to :ref:`types`. + For more information on trace functions, see :ref:`debugger-hooks`. For + more information on code and frame objects, refer to :ref:`types`. -.. method:: 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:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop on this function call, invoke the + :meth:`user_call` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_call`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: 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:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop on this function return, invoke the + :meth:`user_return` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_return`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -.. method:: 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). - Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set - (which can be set from :meth:`user_exception`). Return a reference to the - :meth:`trace_dispatch` method for further tracing in that scope. + If the debugger should stop at this exception, invokes the + :meth:`user_exception` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_exception`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. -Normally derived classes don't override the following methods, but they may if -they want to redefine the definition of stopping and breakpoints. + Normally derived classes don't override the following methods, but they may + if they want to redefine the definition of stopping and breakpoints. -.. method:: 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. + 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. + This method checks if there is a breakpoint in the filename of the current + frame. -Derived classes should override these methods to gain control over debugger -operation. + Derived classes should override these methods to gain control over debugger + operation. -.. method:: 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. + 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. + 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. + 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. + Handle how a breakpoint must be removed when it is a temporary one. - This method must be implemented by derived classes. + This method must be implemented by derived classes. -Derived classes and clients can call the following methods to affect the -stepping state. + Derived classes and clients can call the following methods to affect the + stepping state. -.. method:: Bdb.set_step() + .. method:: set_step() - Stop after one line of code. + Stop after one line of code. -.. method:: Bdb.set_next(frame) + .. method:: set_next(frame) - Stop on the next line in or below the given frame. + Stop on the next line in or below the given frame. -.. method:: Bdb.set_return(frame) + .. method:: set_return(frame) - Stop when returning from the given frame. + Stop when returning from the given frame. -.. method:: Bdb.set_trace([frame]) + .. method:: set_trace([frame]) - Start debugging from *frame*. If *frame* is not specified, debugging starts - 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. + Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in + the next call to one of the :meth:`dispatch_\*` methods. -Derived classes and clients can call the following methods to manipulate -breakpoints. These methods return a string containing an error message if -something went wrong, or ``None`` if all is well. + Derived classes and clients can call the following methods to manipulate + breakpoints. These methods return a string containing an error message if + something went wrong, or ``None`` if all is well. -.. method:: 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. + 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. + 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. + Delete all existing breakpoints. -.. method:: Bdb.get_break(filename, lineno) + .. method:: get_break(filename, lineno) - Check if there is a breakpoint for *lineno* of *filename*. + Check if there is a breakpoint for *lineno* of *filename*. -.. method:: Bdb.get_breaks(filename, lineno) + .. method:: get_breaks(filename, lineno) - Return all breakpoints for *lineno* in *filename*, or an empty list if none - 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. + Return all breakpoints in *filename*, or an empty list if none are set. -.. method:: Bdb.get_all_breaks() + .. method:: get_all_breaks() - Return all breakpoints that are set. + Return all breakpoints that are set. -Derived classes and clients can call the following methods to get a data -structure representing a stack trace. + 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: + Return a string with information about a stack entry, identified by a + ``(frame, lineno)`` tuple: - * The canonical form of the filename which contains the frame. - * The function name, or ``"<lambda>"``. - * The input arguments. - * The return value. - * The line of code (if it exists). + * The canonical form of the filename which contains the frame. + * The function name, or ``"<lambda>"``. + * The input arguments. + * The return value. + * The line of code (if it exists). -The following two methods can be called by clients to use a debugger to debug a -:term:`statement`, given as a string. + The following two methods can be called by clients to use a debugger to debug + a :term:`statement`, given as a string. -.. method:: Bdb.run(cmd, [globals, [locals]]) + .. method:: run(cmd, [globals, [locals]]) - Debug a statement executed via the :func:`exec` function. *globals* - defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. + Debug a statement executed via the :func:`exec` function. *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`. + 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. + For backwards compatibility. Calls the :meth:`run` method. -.. method:: Bdb.runcall(func, *args, **kwds) + .. method:: runcall(func, *args, **kwds) - Debug a single function call, and return its result. + Debug a single function call, and return its result. Finally, the module defines the following functions: diff --git a/Doc/library/bz2.rst b/Doc/library/bz2.rst index ac1695b..cde5749 100644 --- a/Doc/library/bz2.rst +++ b/Doc/library/bz2.rst @@ -44,75 +44,77 @@ Handling of compressed files is offered by the :class:`BZ2File` class. .. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]]) - Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) + Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default) or writing. When opened for writing, the file will be created if it doesn't - exist, and truncated otherwise. If *buffering* is given, ``0`` means unbuffered, - and larger numbers specify the buffer size; the default is ``0``. If - *compresslevel* is given, it must be a number between ``1`` and ``9``; the - default is ``9``. Add a ``'U'`` to mode to open the file for input with - universal newline support. Any line ending in the input file will be seen as a - ``'\n'`` in Python. Also, a file so opened gains the attribute + exist, and truncated otherwise. If *buffering* is given, ``0`` means + unbuffered, and larger numbers specify the buffer size; the default is + ``0``. If *compresslevel* is given, it must be a number between ``1`` and + ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input + with universal newline support. Any line ending in the input file will be + seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute :attr:`newlines`; the value for this attribute is one of ``None`` (no newline - read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the newline - types seen. Universal newlines are available only when reading. Instances - support iteration in the same way as normal :class:`file` instances. + read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the + newline types seen. Universal newlines are available only when + reading. Instances support iteration in the same way as normal :class:`file` + instances. -.. method:: BZ2File.close() + .. method:: close() - Close the file. Sets data attribute :attr:`closed` to true. A closed file cannot - be used for further I/O operations. :meth:`close` may be called more than once - without error. + Close the file. Sets data attribute :attr:`closed` to true. A closed file + cannot be used for further I/O operations. :meth:`close` may be called + more than once without error. -.. method:: BZ2File.read([size]) + .. method:: read([size]) - Read at most *size* uncompressed bytes, returned as a string. If the *size* - argument is negative or omitted, read until EOF is reached. + Read at most *size* uncompressed bytes, returned as a string. If the + *size* argument is negative or omitted, read until EOF is reached. -.. method:: BZ2File.readline([size]) + .. method:: readline([size]) - Return the next line from the file, as a string, retaining newline. A - non-negative *size* argument limits the maximum number of bytes to return (an - incomplete line may be returned then). Return an empty string at EOF. + Return the next line from the file, as a string, retaining newline. A + non-negative *size* argument limits the maximum number of bytes to return + (an incomplete line may be returned then). Return an empty string at EOF. -.. method:: BZ2File.readlines([size]) + .. method:: readlines([size]) - Return a list of lines read. The optional *size* argument, if given, is an - approximate bound on the total number of bytes in the lines returned. + Return a list of lines read. The optional *size* argument, if given, is an + approximate bound on the total number of bytes in the lines returned. -.. method:: BZ2File.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. + Return the current file position, an integer. -.. method:: BZ2File.write(data) + .. method:: write(data) - Write string *data* to file. Note that due to buffering, :meth:`close` may be - 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 @@ -125,23 +127,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() @@ -151,12 +153,13 @@ Sequential compression and decompression is done using the classes :func:`decompress` function instead. -.. method:: BZ2Decompressor.decompress(data) + .. method:: decompress(data) - Provide more data to the decompressor object. It will return chunks of - decompressed data whenever possible. If you try to decompress data after the end - of stream is found, :exc:`EOFError` will be raised. If any data was found after - the end of stream, it'll be ignored and saved in :attr:`unused_data` attribute. + Provide more data to the decompressor object. It will return chunks of + decompressed data whenever possible. If you try to decompress data after + the end of stream is found, :exc:`EOFError` will be raised. If any data + was found after the end of stream, it'll be ignored and saved in + :attr:`unused_data` attribute. One-shot (de)compression @@ -168,13 +171,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. diff --git a/Doc/library/calendar.rst b/Doc/library/calendar.rst index 33b2ad7..112a672 100644 --- a/Doc/library/calendar.rst +++ b/Doc/library/calendar.rst @@ -33,74 +33,75 @@ it's the base calendar for all computations. itself. This is the job of subclasses. -:class:`Calendar` instances have the following methods: + :class:`Calendar` instances have the following methods: -.. method:: Calendar.iterweekdays(weekday) + .. method:: iterweekdays(weekday) - Return an iterator for the week day numbers that will be used for one week. - The first value from the iterator will be the same as the value of the - :attr:`firstweekday` property. + Return an iterator for the week day numbers that will be used for one + week. The first value from the iterator will be the same as the value of + the :attr:`firstweekday` property. -.. method:: Calendar.itermonthdates(year, month) + .. method:: itermonthdates(year, month) - Return an iterator for the month *month* (1-12) in the year *year*. This - iterator will return all days (as :class:`datetime.date` objects) for the month - and all days before the start of the month or after the end of the month that - are required to get a complete week. + Return an iterator for the month *month* (1-12) in the year *year*. This + iterator will return all days (as :class:`datetime.date` objects) for the + month and all days before the start of the month or after the end of the + month that are required to get a complete week. -.. method:: Calendar.itermonthdays2(year, month) + .. method:: itermonthdays2(year, month) - Return an iterator for the month *month* in the year *year* similar to - :meth:`itermonthdates`. Days returned will be tuples consisting of a day number - and a week day number. + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`. Days returned will be tuples consisting of a day + number and a week day number. -.. method:: Calendar.itermonthdays(year, month) + .. method:: itermonthdays(year, month) - Return an iterator for the month *month* in the year *year* similar to - :meth:`itermonthdates`. Days returned will simply be day numbers. + Return an iterator for the month *month* in the year *year* similar to + :meth:`itermonthdates`. Days returned will simply be day numbers. -.. method:: Calendar.monthdatescalendar(year, month) + .. method:: monthdatescalendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven :class:`datetime.date` objects. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven :class:`datetime.date` objects. -.. method:: Calendar.monthdays2calendar(year, month) + .. method:: monthdays2calendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven tuples of day numbers and weekday numbers. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven tuples of day numbers and weekday + numbers. -.. method:: Calendar.monthdayscalendar(year, month) + .. method:: monthdayscalendar(year, month) - Return a list of the weeks in the month *month* of the *year* as full weeks. - Weeks are lists of seven day numbers. + Return a list of the weeks in the month *month* of the *year* as full + weeks. Weeks are lists of seven day numbers. -.. method:: Calendar.yeardatescalendar(year[, width]) + .. method:: yeardatescalendar(year[, width]) - Return the data for the specified year ready for formatting. The return value - is a list of month rows. Each month row contains up to *width* months - (defaulting to 3). Each month contains between 4 and 6 weeks and each week - contains 1--7 days. Days are :class:`datetime.date` objects. + Return the data for the specified year ready for formatting. The return + value is a list of month rows. Each month row contains up to *width* + months (defaulting to 3). Each month contains between 4 and 6 weeks and + each week contains 1--7 days. Days are :class:`datetime.date` objects. -.. method:: Calendar.yeardays2calendar(year[, width]) + .. method:: yeardays2calendar(year[, width]) - Return the data for the specified year ready for formatting (similar to - :meth:`yeardatescalendar`). Entries in the week lists are tuples of day - numbers and weekday numbers. Day numbers outside this month are zero. + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are tuples of day + numbers and weekday numbers. Day numbers outside this month are zero. -.. method:: Calendar.yeardayscalendar(year[, width]) + .. method:: yeardayscalendar(year[, width]) - Return the data for the specified year ready for formatting (similar to - :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day - numbers outside this month are zero. + Return the data for the specified year ready for formatting (similar to + :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day + numbers outside this month are zero. .. class:: TextCalendar([firstweekday]) @@ -108,35 +109,35 @@ it's the base calendar for all computations. This class can be used to generate plain text calendars. -:class:`TextCalendar` instances have the following methods: + :class:`TextCalendar` instances have the following methods: -.. method:: TextCalendar.formatmonth(theyear, themonth[, w[, l]]) + .. method:: formatmonth(theyear, themonth[, w[, l]]) - Return a month's calendar in a multi-line string. If *w* is provided, it - specifies the width of the date columns, which are centered. If *l* is given, - it specifies the number of lines that each week will use. Depends on the - first weekday as specified in the constructor or set by the - :meth:`setfirstweekday` method. + Return a month's calendar in a multi-line string. If *w* is provided, it + specifies the width of the date columns, which are centered. If *l* is + given, it specifies the number of lines that each week will use. Depends + on the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. -.. method:: TextCalendar.prmonth(theyear, themonth[, w[, l]]) + .. method:: prmonth(theyear, themonth[, w[, l]]) - Print a month's calendar as returned by :meth:`formatmonth`. + Print a month's calendar as returned by :meth:`formatmonth`. -.. method:: TextCalendar.formatyear(theyear, themonth[, w[, l[, c[, m]]]]) + .. method:: formatyear(theyear, themonth[, w[, l[, c[, m]]]]) - Return a *m*-column calendar for an entire year as a multi-line string. - Optional parameters *w*, *l*, and *c* are for date column width, lines per - week, and number of spaces between month columns, respectively. Depends on - the first weekday as specified in the constructor or set by the - :meth:`setfirstweekday` method. The earliest year for which a calendar can - be generated is platform-dependent. + Return a *m*-column calendar for an entire year as a multi-line string. + Optional parameters *w*, *l*, and *c* are for date column width, lines per + week, and number of spaces between month columns, respectively. Depends on + the first weekday as specified in the constructor or set by the + :meth:`setfirstweekday` method. The earliest year for which a calendar + can be generated is platform-dependent. -.. method:: TextCalendar.pryear(theyear[, w[, l[, c[, m]]]]) + .. method:: pryear(theyear[, w[, l[, c[, m]]]]) - Print the calendar for an entire year as returned by :meth:`formatyear`. + Print the calendar for an entire year as returned by :meth:`formatyear`. .. class:: HTMLCalendar([firstweekday]) @@ -144,43 +145,44 @@ it's the base calendar for all computations. This class can be used to generate HTML calendars. -:class:`HTMLCalendar` instances have the following methods: + :class:`HTMLCalendar` instances have the following methods: -.. method:: HTMLCalendar.formatmonth(theyear, themonth[, withyear]) + .. method:: formatmonth(theyear, themonth[, withyear]) - Return a month's calendar as an HTML table. If *withyear* is true the year will - 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. .. 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. For simple text calendars this module provides the following functions. diff --git a/Doc/library/cgihttpserver.rst b/Doc/library/cgihttpserver.rst index 4f27627..6275c1a 100644 --- a/Doc/library/cgihttpserver.rst +++ b/Doc/library/cgihttpserver.rst @@ -43,22 +43,22 @@ The :mod:`CGIHTTPServer` module defines the following class: and serve the output, instead of serving files, if the request leads to somewhere below the ``cgi_directories`` path. -The :class:`CGIHTTPRequestHandler` defines the following data member: + The :class:`CGIHTTPRequestHandler` defines the following data member: -.. attribute:: CGIHTTPRequestHandler.cgi_directories + .. attribute:: cgi_directories - This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to treat - as containing CGI scripts. + This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to + treat as containing CGI scripts. -The :class:`CGIHTTPRequestHandler` defines the following methods: + The :class:`CGIHTTPRequestHandler` defines the following methods: -.. method:: CGIHTTPRequestHandler.do_POST() + .. method:: do_POST() - This method serves the ``'POST'`` request type, only allowed for CGI scripts. - Error 501, "Can only POST to CGI scripts", is output when trying to POST to a - non-CGI url. + This method serves the ``'POST'`` request type, only allowed for CGI + scripts. Error 501, "Can only POST to CGI scripts", is output when trying + to POST to a non-CGI url. Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403. diff --git a/Doc/library/chunk.rst b/Doc/library/chunk.rst index 2e1798d..64ce4e2 100644 --- a/Doc/library/chunk.rst +++ b/Doc/library/chunk.rst @@ -66,62 +66,64 @@ instance will fail with a :exc:`EOFError` exception. optional argument *inclheader* is true, the size given in the chunk header includes the size of the header. The default value is false. -A :class:`Chunk` object supports the following methods: + A :class:`Chunk` object supports the following methods: -.. method:: Chunk.getname() + .. method:: getname() - Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. + Returns the name (ID) of the chunk. This is the first 4 bytes of the + chunk. -.. method:: Chunk.getsize() + .. method:: getsize() - Returns the size of the chunk. + Returns the size of the chunk. -.. method:: Chunk.close() + .. method:: close() - Close and skip to the end of the chunk. This does not close the underlying - file. + Close and skip to the end of the chunk. This does not close the + underlying file. -The remaining methods will raise :exc:`IOError` if called after the -:meth:`close` method has been called. + The remaining methods will raise :exc:`IOError` if called after the + :meth:`close` method has been called. -.. method:: Chunk.isatty() + .. method:: isatty() - Returns ``False``. + Returns ``False``. -.. method:: Chunk.seek(pos[, whence]) + .. method:: seek(pos[, whence]) - Set the chunk's current position. The *whence* argument is optional and - defaults to ``0`` (absolute file positioning); other values are ``1`` (seek - relative to the current position) and ``2`` (seek relative to the file's end). - There is no return value. If the underlying file does not allow seek, only - forward seeks are allowed. + Set the chunk's current position. The *whence* argument is optional and + defaults to ``0`` (absolute file positioning); other values are ``1`` + (seek relative to the current position) and ``2`` (seek relative to the + file's end). There is no return value. If the underlying file does not + allow seek, only forward seeks are allowed. -.. method:: Chunk.tell() + .. method:: tell() - Return the current position into the chunk. + Return the current position into the chunk. -.. method:: Chunk.read([size]) + .. method:: read([size]) - Read at most *size* bytes from the chunk (less if the read hits the end of the - chunk before obtaining *size* bytes). If the *size* argument is negative or - omitted, read all data until the end of the chunk. The bytes are returned as a - string object. An empty string is returned when the end of the chunk is - encountered immediately. + Read at most *size* bytes from the chunk (less if the read hits the end of + the chunk before obtaining *size* bytes). If the *size* argument is + negative or omitted, read all data until the end of the chunk. The bytes + are returned as a string object. An empty string is returned when the end + of the chunk is encountered immediately. -.. method:: Chunk.skip() + .. method:: skip() + + Skip to the end of the chunk. All further calls to :meth:`read` for the + chunk will return ``''``. If you are not interested in the contents of + the chunk, this method should be called so that the file points to the + start of the next chunk. - Skip to the end of the chunk. All further calls to :meth:`read` for the chunk - will return ``''``. If you are not interested in the contents of the chunk, - this method should be called so that the file points to the start of the next - chunk. .. rubric:: Footnotes diff --git a/Doc/library/codecs.rst b/Doc/library/codecs.rst index f00c873..2acf76b 100644 --- a/Doc/library/codecs.rst +++ b/Doc/library/codecs.rst @@ -425,16 +425,16 @@ define in order to be compatible with the Python codec registry. :func:`register_error`. -.. method:: IncrementalEncoder.encode(object[, final]) + .. method:: encode(object[, final]) - Encodes *object* (taking the current state of the encoder into account) and - returns the resulting encoded object. If this is the last call to :meth:`encode` - *final* must be true (the default is false). + Encodes *object* (taking the current state of the encoder into account) + and returns the resulting encoded object. If this is the last call to + :meth:`encode` *final* must be true (the default is false). -.. method:: IncrementalEncoder.reset() + .. method:: reset() - Reset the encoder to the initial state. + Reset the encoder to the initial state. .. method:: IncrementalEncoder.getstate() @@ -488,41 +488,42 @@ define in order to be compatible with the Python codec registry. :func:`register_error`. -.. method:: IncrementalDecoder.decode(object[, final]) + .. method:: decode(object[, final]) - Decodes *object* (taking the current state of the decoder into account) and - returns the resulting decoded object. If this is the last call to :meth:`decode` - *final* must be true (the default is false). If *final* is true the decoder must - decode the input completely and must flush all buffers. If this isn't possible - (e.g. because of incomplete byte sequences at the end of the input) it must - initiate error handling just like in the stateless case (which might raise an - exception). + Decodes *object* (taking the current state of the decoder into account) + and returns the resulting decoded object. If this is the last call to + :meth:`decode` *final* must be true (the default is false). If *final* is + true the decoder must decode the input completely and must flush all + buffers. If this isn't possible (e.g. because of incomplete byte sequences + at the end of the input) it must initiate error handling just like in the + stateless case (which might raise an exception). -.. method:: IncrementalDecoder.reset() + .. method:: reset() - Reset the decoder to the initial state. + Reset the decoder to the initial state. -.. method:: IncrementalDecoder.getstate() + .. method:: getstate() - Return the current state of the decoder. This must be a tuple with two items, - the first must be the buffer containing the still undecoded input. The second - must be an integer and can be additional state info. (The implementation should - make sure that ``0`` is the most common additional state info.) If this - additional state info is ``0`` it must be possible to set the decoder to the - state which has no input buffered and ``0`` as the additional state info, so - that feeding the previously buffered input to the decoder returns it to the - previous state without producing any output. (Additional state info that is more - complicated than integers can be converted into an integer by - marshaling/pickling the info and encoding the bytes of the resulting string into - an integer.) + Return the current state of the decoder. This must be a tuple with two + items, the first must be the buffer containing the still undecoded + input. The second must be an integer and can be additional state + info. (The implementation should make sure that ``0`` is the most common + additional state info.) If this additional state info is ``0`` it must be + possible to set the decoder to the state which has no input buffered and + ``0`` as the additional state info, so that feeding the previously + buffered input to the decoder returns it to the previous state without + producing any output. (Additional state info that is more complicated than + integers can be converted into an integer by marshaling/pickling the info + and encoding the bytes of the resulting string into an integer.) -.. method:: IncrementalDecoder.setstate(state) + .. method:: setstate(state) + + Set the state of the encoder to *state*. *state* must be a decoder state + returned by :meth:`getstate`. - Set the state of the encoder to *state*. *state* must be a decoder state - returned by :meth:`getstate`. The :class:`StreamWriter` and :class:`StreamReader` classes provide generic working interfaces which can be used to implement new encoding submodules very @@ -570,24 +571,25 @@ compatible with the Python codec registry. :func:`register_error`. -.. method:: StreamWriter.write(object) + .. method:: write(object) + + Writes the object's contents encoded to the stream. - Writes the object's contents encoded to the stream. + .. method:: writelines(list) -.. method:: StreamWriter.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:: reset() -.. method:: StreamWriter.reset() + Flushes and resets the codec buffers used for keeping state. - Flushes and resets the codec buffers used for keeping state. + Calling this method should ensure that the data on the output is put into + a clean state that allows appending of new fresh data without having to + rescan the whole stream to recover state. - Calling this method should ensure that the data on the output is put into a - clean state that allows appending of new fresh data without having to rescan the - whole stream to recover state. In addition to the above methods, the :class:`StreamWriter` must also inherit all other methods and attributes from the underlying stream. @@ -630,55 +632,59 @@ compatible with the Python codec registry. :func:`register_error`. -.. method:: StreamReader.read([size[, chars, [firstline]]]) + .. method:: read([size[, chars, [firstline]]]) - Decodes data from the stream and returns the resulting object. + Decodes data from the stream and returns the resulting object. - *chars* indicates the number of characters to read from the stream. :func:`read` - will never return more than *chars* characters, but it might return less, if - there are not enough characters available. + *chars* indicates the number of characters to read from the + stream. :func:`read` will never return more than *chars* characters, but + it might return less, if there are not enough characters available. - *size* indicates the approximate maximum number of bytes to read from the stream - for decoding purposes. The decoder can modify this setting as appropriate. The - default value -1 indicates to read and decode as much as possible. *size* is - intended to prevent having to decode huge files in one step. + *size* indicates the approximate maximum number of bytes to read from the + stream for decoding purposes. The decoder can modify this setting as + appropriate. The default value -1 indicates to read and decode as much as + possible. *size* is intended to prevent having to decode huge files in + one step. - *firstline* indicates that it would be sufficient to only return the first line, - if there are decoding errors on later lines. + *firstline* indicates that it would be sufficient to only return the first + line, if there are decoding errors on later lines. - The method should use a greedy read strategy meaning that it should read as much - data as is allowed within the definition of the encoding and the given size, - e.g. if optional encoding endings or state markers are available on the stream, - these should be read too. + The method should use a greedy read strategy meaning that it should read + as much data as is allowed within the definition of the encoding and the + given size, e.g. if optional encoding endings or state markers are + available on the stream, these should be read too. -.. method:: StreamReader.readline([size[, keepends]]) + .. method:: readline([size[, keepends]]) - Read one line from the input stream and return the decoded data. + Read one line from the input stream and return the decoded data. - *size*, if given, is passed as size argument to the stream's :meth:`readline` - method. + *size*, if given, is passed as size argument to the stream's + :meth:`readline` method. - If *keepends* is false line-endings will be stripped from the lines returned. + If *keepends* is false line-endings will be stripped from the lines + returned. -.. method:: StreamReader.readlines([sizehint[, keepends]]) + .. method:: readlines([sizehint[, keepends]]) - Read all lines available on the input stream and return them as a list of lines. + Read all lines available on the input stream and return them as a list of + lines. - Line-endings are implemented using the codec's decoder method and are included - in the list entries if *keepends* is true. + Line-endings are implemented using the codec's decoder method and are + included in the list entries if *keepends* is true. - *sizehint*, if given, is passed as the *size* argument to the stream's - :meth:`read` method. + *sizehint*, if given, is passed as the *size* argument to the stream's + :meth:`read` method. -.. method:: StreamReader.reset() + .. method:: reset() - Resets the codec buffers used for keeping state. + Resets the codec buffers used for keeping state. + + Note that no stream repositioning should take place. This method is + primarily intended to be able to recover from decoding errors. - Note that no stream repositioning should take place. This method is primarily - intended to be able to recover from decoding errors. In addition to the above methods, the :class:`StreamReader` must also inherit all other methods and attributes from the underlying stream. @@ -747,6 +753,7 @@ The design is such that one can use the factory functions returned by the Error handling is done in the same way as defined for the stream readers and 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. diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 7827700..cff07b9 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -166,59 +166,60 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin: where only the most recent activity is of interest. -Deque objects support the following methods: + Deque objects support the following methods: -.. method:: deque.append(x) + .. method:: append(x) - Add *x* to the right side of the deque. + Add *x* to the right side of the deque. -.. method:: deque.appendleft(x) + .. method:: appendleft(x) - Add *x* to the left side of the deque. + Add *x* to the left side of the deque. -.. method:: deque.clear() + .. method:: clear() - Remove all elements from the deque leaving it with length 0. + Remove all elements from the deque leaving it with length 0. -.. method:: deque.extend(iterable) + .. method:: extend(iterable) - Extend the right side of the deque by appending elements from the iterable - argument. + Extend the right side of the deque by appending elements from the iterable + argument. -.. method:: deque.extendleft(iterable) + .. method:: extendleft(iterable) - Extend the left side of the deque by appending elements from *iterable*. Note, - the series of left appends results in reversing the order of elements in the - iterable argument. + Extend the left side of the deque by appending elements from *iterable*. + Note, the series of left appends results in reversing the order of + elements in the iterable argument. -.. method:: deque.pop() + .. method:: pop() - Remove and return an element from the right side of the deque. If no elements - are present, raises an :exc:`IndexError`. + Remove and return an element from the right side of the deque. If no + elements are present, raises an :exc:`IndexError`. -.. method:: deque.popleft() + .. method:: popleft() - Remove and return an element from the left side of the deque. If no elements are - present, raises an :exc:`IndexError`. + Remove and return an element from the left side of the deque. If no + elements are present, raises an :exc:`IndexError`. -.. method:: deque.remove(value) + .. method:: remove(value) - Removed the first occurrence of *value*. If not found, raises a - :exc:`ValueError`. + Removed the first occurrence of *value*. If not found, raises a + :exc:`ValueError`. -.. method:: deque.rotate(n) + .. method:: rotate(n) + + Rotate the deque *n* steps to the right. If *n* is negative, rotate to + the left. Rotating one step to the right is equivalent to: + ``d.appendleft(d.pop())``. - Rotate the deque *n* steps to the right. If *n* is negative, rotate to the - left. Rotating one step to the right is equivalent to: - ``d.appendleft(d.pop())``. In addition to the above, deques support iteration, pickling, ``len(d)``, ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with @@ -348,32 +349,34 @@ in Unix:: arguments. -:class:`defaultdict` objects support the following method in addition to the -standard :class:`dict` operations: + :class:`defaultdict` objects support the following method in addition to the + standard :class:`dict` operations: + + .. method:: defaultdict.__missing__(key) -.. method:: defaultdict.__missing__(key) + If the :attr:`default_factory` attribute is ``None``, this raises an + :exc:`KeyError` exception with the *key* as argument. - If the :attr:`default_factory` attribute is ``None``, this raises an - :exc:`KeyError` exception with the *key* as argument. + If :attr:`default_factory` is not ``None``, it is called without arguments + to provide a default value for the given *key*, this value is inserted in + the dictionary for the *key*, and returned. - If :attr:`default_factory` is not ``None``, it is called without arguments to - provide a default value for the given *key*, this value is inserted in the - dictionary for the *key*, and returned. + If calling :attr:`default_factory` raises an exception this exception is + propagated unchanged. - If calling :attr:`default_factory` raises an exception this exception is - propagated unchanged. + This method is called by the :meth:`__getitem__` method of the + :class:`dict` class when the requested key is not found; whatever it + returns or raises is then returned or raised by :meth:`__getitem__`. - 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: + :class:`defaultdict` objects support the following instance variable: -.. attribute:: defaultdict.default_factory + .. attribute:: defaultdict.default_factory - This attribute is used by the :meth:`__missing__` method; it is initialized from - 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: diff --git a/Doc/library/csv.rst b/Doc/library/csv.rst index ffdb3cb..6beadc5 100644 --- a/Doc/library/csv.rst +++ b/Doc/library/csv.rst @@ -209,19 +209,20 @@ The :mod:`csv` module defines the following classes: The :class:`Sniffer` class is used to deduce the format of a CSV file. -The :class:`Sniffer` class provides two methods: + The :class:`Sniffer` class provides two methods: -.. method:: Sniffer.sniff(sample[, delimiters=None]) + .. method:: sniff(sample[, delimiters=None]) - Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the - parameters found. If the optional *delimiters* parameter is given, it is - interpreted as a string containing possible valid delimiter characters. + Analyze the given *sample* and return a :class:`Dialect` subclass + reflecting the parameters found. If the optional *delimiters* parameter + is given, it is interpreted as a string containing possible valid + delimiter characters. -.. method:: Sniffer.has_header(sample) + .. method:: has_header(sample) - Analyze the sample text (presumed to be in CSV format) and return :const:`True` - if the first row appears to be a series of column headers. + Analyze the sample text (presumed to be in CSV format) and return + :const:`True` if the first row appears to be a series of column headers. An example for :class:`Sniffer` use:: diff --git a/Doc/library/ctypes.rst b/Doc/library/ctypes.rst index 7b95ba1..8d38050 100644 --- a/Doc/library/ctypes.rst +++ b/Doc/library/ctypes.rst @@ -1441,10 +1441,10 @@ loader instance. so repeated attribute accesses return the same library each time. -.. method:: LibraryLoader.LoadLibrary(name) + .. method:: LoadLibrary(name) - Load a shared library into the process and return it. This method always - returns a new instance of the library. + Load a shared library into the process and return it. This method always + returns a new instance of the library. These prefabricated library loaders are available: @@ -1501,50 +1501,51 @@ They are instances of a private class: Base class for C callable foreign functions. -Instances of foreign functions are also C compatible data types; they represent -C function pointers. + Instances of foreign functions are also C compatible data types; they + represent C function pointers. -This behavior can be customized by assigning to special attributes of the -foreign function object. + This behavior can be customized by assigning to special attributes of the + foreign function object. -.. attribute:: _FuncPtr.restype + .. attribute:: restype - Assign a ctypes type to specify the result type of the foreign function. Use - ``None`` for ``void`` a function not returning anything. + Assign a ctypes type to specify the result type of the foreign function. + Use ``None`` for ``void`` a function not returning anything. - It is possible to assign a callable Python object that is not a ctypes type, in - this case the function is assumed to return a C ``int``, and the callable will - be called with this integer, allowing to do further processing or error - checking. Using this is deprecated, for more flexible post processing or error - checking use a ctypes data type as :attr:`restype` and assign a callable to the - :attr:`errcheck` attribute. + It is possible to assign a callable Python object that is not a ctypes + type, in this case the function is assumed to return a C ``int``, and the + callable will be called with this integer, allowing to do further + processing or error checking. Using this is deprecated, for more flexible + post processing or error checking use a ctypes data type as + :attr:`restype` and assign a callable to the :attr:`errcheck` attribute. -.. attribute:: _FuncPtr.argtypes + .. attribute:: argtypes - Assign a tuple of ctypes types to specify the argument types that the function - accepts. Functions using the ``stdcall`` calling convention can only be called - with the same number of arguments as the length of this tuple; functions using - the C calling convention accept additional, unspecified arguments as well. + Assign a tuple of ctypes types to specify the argument types that the + function accepts. Functions using the ``stdcall`` calling convention can + only be called with the same number of arguments as the length of this + tuple; functions using the C calling convention accept additional, + unspecified arguments as well. - When a foreign function is called, each actual argument is passed to the - :meth:`from_param` class method of the items in the :attr:`argtypes` tuple, this - method allows to adapt the actual argument to an object that the foreign - function accepts. For example, a :class:`c_char_p` item in the :attr:`argtypes` - tuple will convert a unicode string passed as argument into an byte string using - ctypes conversion rules. + When a foreign function is called, each actual argument is passed to the + :meth:`from_param` class method of the items in the :attr:`argtypes` + tuple, this method allows to adapt the actual argument to an object that + the foreign function accepts. For example, a :class:`c_char_p` item in + the :attr:`argtypes` tuple will convert a unicode string passed as + argument into an byte string using ctypes conversion rules. - New: It is now possible to put items in argtypes which are not ctypes types, but - each item must have a :meth:`from_param` method which returns a value usable as - argument (integer, string, ctypes instance). This allows to define adapters - that can adapt custom objects as function parameters. + New: It is now possible to put items in argtypes which are not ctypes + types, but each item must have a :meth:`from_param` method which returns a + value usable as argument (integer, string, ctypes instance). This allows + to define adapters that can adapt custom objects as function parameters. -.. attribute:: _FuncPtr.errcheck + .. attribute:: errcheck - Assign a Python function or another callable to this attribute. The callable - will be called with three or more arguments: + Assign a Python function or another callable to this attribute. The + callable will be called with three or more arguments: .. function:: callable(result, func, arguments) @@ -1559,9 +1560,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() @@ -1943,57 +1944,58 @@ Data types :attr:`_objects`; this contains other Python objects that need to be kept alive in case the memory block contains pointers. -Common methods of ctypes data types, these are all class methods (to be exact, -they are methods of the :term:`metaclass`): + Common methods of ctypes data types, these are all class methods (to be + exact, they are methods of the :term:`metaclass`): -.. method:: _CData.from_address(address) + .. method:: from_address(address) - This method returns a ctypes type instance using the memory specified by address - which must be an integer. + This method returns a ctypes type instance using the memory specified by + address which must be an integer. -.. method:: _CData.from_param(obj) + .. method:: from_param(obj) - This method adapts obj to a ctypes type. It is called with the actual object - used in a foreign function call, when the type is present in the foreign - functions :attr:`argtypes` tuple; it must return an object that can be used as - function call parameter. + This method adapts obj to a ctypes type. It is called with the actual + object used in a foreign function call, when the type is present in the + foreign functions :attr:`argtypes` tuple; it must return an object that + can be used as function call parameter. - All ctypes data types have a default implementation of this classmethod, - normally it returns ``obj`` if that is an instance of the type. Some types - accept other objects as well. + All ctypes data types have a default implementation of this classmethod, + normally it returns ``obj`` if that is an instance of the type. Some + types accept other objects as well. -.. method:: _CData.in_dll(library, name) + .. method:: in_dll(library, name) - This method returns a ctypes type instance exported by a shared library. *name* - is the name of the symbol that exports the data, *library* is the loaded shared - library. + 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: + Common instance variables of ctypes data types: -.. attribute:: _CData._b_base_ - Sometimes ctypes data instances do not own the memory block they contain, - instead they share part of the memory block of a base object. The - :attr:`_b_base_` read-only member is the root ctypes object that owns the memory - block. + .. 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. -.. attribute:: _CData._b_needsfree_ - This read-only variable is true when the ctypes data instance has allocated the - memory block itself, false otherwise. + .. attribute:: _b_needsfree_ + This read-only variable is true when the ctypes data instance has + allocated the memory block itself, false otherwise. -.. attribute:: _CData._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. + .. attribute:: _objects + + This member is either ``None`` or a dictionary containing Python objects + that need to be kept alive so that the memory block contents is kept + valid. This object is only exposed for debugging; never modify the + contents of this dictionary. .. _ctypes-fundamental-data-types-2: @@ -2010,19 +2012,20 @@ Fundamental data types so it inherits their methods and attributes. ctypes data types that are not and do not contain pointers can now be pickled. -Instances have a single attribute: + Instances have a single attribute: -.. attribute:: _SimpleCData.value + .. attribute:: value - This attribute contains the actual value of the instance. For integer and - pointer types, it is an integer, for character types, it is a single character - string, for character pointer types it is a Python string or unicode string. + This attribute contains the actual value of the instance. For integer and + pointer types, it is an integer, for character types, it is a single + character string, for character pointer types it is a Python string or + unicode string. - When the ``value`` attribute is retrieved from a ctypes instance, usually a new - object is returned each time. ``ctypes`` does *not* implement original object - return, always a new object is constructed. The same is true for all other - ctypes object instances. + When the ``value`` attribute is retrieved from a ctypes instance, usually + a new object is returned each time. ``ctypes`` does *not* implement + original object return, always a new object is constructed. The same is + true for all other ctypes object instances. Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently @@ -2258,90 +2261,92 @@ other data types containing pointer type fields. Abstract base class for structures in *native* byte order. -Concrete structure and union types must be created by subclassing one of these -types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will -create :term:`descriptor`\s which allow reading and writing the fields by direct -attribute accesses. These are the + Concrete structure and union types must be created by subclassing one of these + types, and at least define a :attr:`_fields_` class variable. ``ctypes`` will + create :term:`descriptor`\s which allow reading and writing the fields by direct + attribute accesses. These are the -.. attribute:: Structure._fields_ + .. attribute:: _fields_ - A sequence defining the structure fields. The items must be 2-tuples or - 3-tuples. The first item is the name of the field, the second item specifies - the type of the field; it can be any ctypes data type. + A sequence defining the structure fields. The items must be 2-tuples or + 3-tuples. The first item is the name of the field, the second item + specifies the type of the field; it can be any ctypes data type. - For integer type fields like :class:`c_int`, a third optional item can be given. - It must be a small positive integer defining the bit width of the field. + For integer type fields like :class:`c_int`, a third optional item can be + given. It must be a small positive integer defining the bit width of the + field. - Field names must be unique within one structure or union. This is not checked, - only one field can be accessed when names are repeated. + Field names must be unique within one structure or union. This is not + checked, only one field can be accessed when names are repeated. - It is possible to define the :attr:`_fields_` class variable *after* the class - statement that defines the Structure subclass, this allows to create data types - that directly or indirectly reference themselves:: + It is possible to define the :attr:`_fields_` class variable *after* the + class statement that defines the Structure subclass, this allows to create + data types that directly or indirectly reference themselves:: - class List(Structure): - pass - List._fields_ = [("pnext", POINTER(List)), - ... - ] + class List(Structure): + pass + List._fields_ = [("pnext", POINTER(List)), + ... + ] - The :attr:`_fields_` class variable must, however, be defined before the type is - first used (an instance is created, ``sizeof()`` is called on it, and so on). - Later assignments to the :attr:`_fields_` class variable will raise an - AttributeError. + The :attr:`_fields_` class variable must, however, be defined before the + type is first used (an instance is created, ``sizeof()`` is called on it, + and so on). Later assignments to the :attr:`_fields_` class variable will + raise an AttributeError. - Structure and union subclass constructors accept both positional and named - arguments. Positional arguments are used to initialize the fields in the same - order as they appear in the :attr:`_fields_` definition, named arguments are - used to initialize the fields with the corresponding name. + Structure and union subclass constructors accept both positional and named + arguments. Positional arguments are used to initialize the fields in the + same order as they appear in the :attr:`_fields_` definition, named + arguments are used to initialize the fields with the corresponding name. - It is possible to defined sub-subclasses of structure types, they inherit the - fields of the base class plus the :attr:`_fields_` defined in the sub-subclass, - if any. + It is possible to defined sub-subclasses of structure types, they inherit + the fields of the base class plus the :attr:`_fields_` defined in the + sub-subclass, if any. -.. attribute:: Structure._pack_ + .. attribute:: _pack_ - An optional small integer that allows to override the alignment of structure - fields in the instance. :attr:`_pack_` must already be defined when - :attr:`_fields_` is assigned, otherwise it will have no effect. + An optional small integer that allows to override the alignment of + structure fields in the instance. :attr:`_pack_` must already be defined + when :attr:`_fields_` is assigned, otherwise it will have no effect. -.. attribute:: Structure._anonymous_ + .. attribute:: _anonymous_ - An optional sequence that lists the names of unnamed (anonymous) fields. - ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, - otherwise it will have no effect. + An optional sequence that lists the names of unnamed (anonymous) fields. + ``_anonymous_`` must be already defined when :attr:`_fields_` is assigned, + otherwise it will have no effect. - The fields listed in this variable must be structure or union type fields. - ``ctypes`` will create descriptors in the structure type that allows to access - the nested fields directly, without the need to create the structure or union - field. + The fields listed in this variable must be structure or union type fields. + ``ctypes`` will create descriptors in the structure type that allows to + access the nested fields directly, without the need to create the + structure or union field. - Here is an example type (Windows):: + Here is an example type (Windows):: - class _U(Union): - _fields_ = [("lptdesc", POINTER(TYPEDESC)), - ("lpadesc", POINTER(ARRAYDESC)), - ("hreftype", HREFTYPE)] + class _U(Union): + _fields_ = [("lptdesc", POINTER(TYPEDESC)), + ("lpadesc", POINTER(ARRAYDESC)), + ("hreftype", HREFTYPE)] - class TYPEDESC(Structure): - _fields_ = [("u", _U), - ("vt", VARTYPE)] + class TYPEDESC(Structure): + _fields_ = [("u", _U), + ("vt", VARTYPE)] - _anonymous_ = ("u",) + _anonymous_ = ("u",) - The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies - which one of the union fields is valid. Since the ``u`` field is defined as - anonymous field, it is now possible to access the members directly off the - TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the - former is faster since it does not need to create a temporary union instance:: + The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field + specifies which one of the union fields is valid. Since the ``u`` field + is defined as anonymous field, it is now possible to access the members + directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` + are equivalent, but the former is faster since it does not need to create + a temporary union instance:: - td = TYPEDESC() - td.vt = VT_PTR - td.lptdesc = POINTER(some_type) - td.u.lptdesc = POINTER(some_type) + td = TYPEDESC() + td.vt = VT_PTR + td.lptdesc = POINTER(some_type) + td.u.lptdesc = POINTER(some_type) It is possible to defined sub-subclasses of structures, they inherit the fields of the base class. If the subclass definition has a separate :attr:`_fields_` diff --git a/Doc/library/curses.rst b/Doc/library/curses.rst index 4135182..21c3176 100644 --- a/Doc/library/curses.rst +++ b/Doc/library/curses.rst @@ -1567,92 +1567,94 @@ You can instantiate a :class:`Textbox` object as follows: containing window, with coordinates ``(0, 0)``. The instance's :attr:`stripspaces` flag is initially on. -:class:`Textbox` objects have the following methods: - - -.. method:: Textbox.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. - - -.. method:: Textbox.do_command(ch) - - Process a single command keystroke. Here are the supported special keystrokes: - - +------------------+-------------------------------------------+ - | Keystroke | Action | - +==================+===========================================+ - | :kbd:`Control-A` | Go to left edge of window. | - +------------------+-------------------------------------------+ - | :kbd:`Control-B` | Cursor left, wrapping to previous line if | - | | appropriate. | - +------------------+-------------------------------------------+ - | :kbd:`Control-D` | Delete character under cursor. | - +------------------+-------------------------------------------+ - | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | - | | of line (stripspaces on). | - +------------------+-------------------------------------------+ - | :kbd:`Control-F` | Cursor right, wrapping to next line when | - | | appropriate. | - +------------------+-------------------------------------------+ - | :kbd:`Control-G` | Terminate, returning the window contents. | - +------------------+-------------------------------------------+ - | :kbd:`Control-H` | Delete character backward. | - +------------------+-------------------------------------------+ - | :kbd:`Control-J` | Terminate if the window is 1 line, | - | | otherwise insert newline. | - +------------------+-------------------------------------------+ - | :kbd:`Control-K` | If line is blank, delete it, otherwise | - | | clear to end of line. | - +------------------+-------------------------------------------+ - | :kbd:`Control-L` | Refresh screen. | - +------------------+-------------------------------------------+ - | :kbd:`Control-N` | Cursor down; move down one line. | - +------------------+-------------------------------------------+ - | :kbd:`Control-O` | Insert a blank line at cursor location. | - +------------------+-------------------------------------------+ - | :kbd:`Control-P` | Cursor up; move up one line. | - +------------------+-------------------------------------------+ - - Move operations do nothing if the cursor is at an edge where the movement is not - possible. The following synonyms are supported where possible: - - +------------------------+------------------+ - | Constant | Keystroke | - +========================+==================+ - | :const:`KEY_LEFT` | :kbd:`Control-B` | - +------------------------+------------------+ - | :const:`KEY_RIGHT` | :kbd:`Control-F` | - +------------------------+------------------+ - | :const:`KEY_UP` | :kbd:`Control-P` | - +------------------------+------------------+ - | :const:`KEY_DOWN` | :kbd:`Control-N` | - +------------------------+------------------+ - | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | - +------------------------+------------------+ - - All other keystrokes are treated as a command to insert the given character and - move right (with line wrapping). - - -.. method:: Textbox.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 - - 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. + :class:`Textbox` objects have the following methods: + + + .. 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. + + + .. method:: do_command(ch) + + Process a single command keystroke. Here are the supported special + keystrokes: + + +------------------+-------------------------------------------+ + | Keystroke | Action | + +==================+===========================================+ + | :kbd:`Control-A` | Go to left edge of window. | + +------------------+-------------------------------------------+ + | :kbd:`Control-B` | Cursor left, wrapping to previous line if | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-D` | Delete character under cursor. | + +------------------+-------------------------------------------+ + | :kbd:`Control-E` | Go to right edge (stripspaces off) or end | + | | of line (stripspaces on). | + +------------------+-------------------------------------------+ + | :kbd:`Control-F` | Cursor right, wrapping to next line when | + | | appropriate. | + +------------------+-------------------------------------------+ + | :kbd:`Control-G` | Terminate, returning the window contents. | + +------------------+-------------------------------------------+ + | :kbd:`Control-H` | Delete character backward. | + +------------------+-------------------------------------------+ + | :kbd:`Control-J` | Terminate if the window is 1 line, | + | | otherwise insert newline. | + +------------------+-------------------------------------------+ + | :kbd:`Control-K` | If line is blank, delete it, otherwise | + | | clear to end of line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-L` | Refresh screen. | + +------------------+-------------------------------------------+ + | :kbd:`Control-N` | Cursor down; move down one line. | + +------------------+-------------------------------------------+ + | :kbd:`Control-O` | Insert a blank line at cursor location. | + +------------------+-------------------------------------------+ + | :kbd:`Control-P` | Cursor up; move up one line. | + +------------------+-------------------------------------------+ + + Move operations do nothing if the cursor is at an edge where the movement + is not possible. The following synonyms are supported where possible: + + +------------------------+------------------+ + | Constant | Keystroke | + +========================+==================+ + | :const:`KEY_LEFT` | :kbd:`Control-B` | + +------------------------+------------------+ + | :const:`KEY_RIGHT` | :kbd:`Control-F` | + +------------------------+------------------+ + | :const:`KEY_UP` | :kbd:`Control-P` | + +------------------------+------------------+ + | :const:`KEY_DOWN` | :kbd:`Control-N` | + +------------------------+------------------+ + | :const:`KEY_BACKSPACE` | :kbd:`Control-h` | + +------------------------+------------------+ + + All other keystrokes are treated as a command to insert the given + character and move right (with line wrapping). + + + .. 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:: 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. :mod:`curses.wrapper` --- Terminal handler for curses programs diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst index 6f4821b..b7dd32f 100644 --- a/Doc/library/decimal.rst +++ b/Doc/library/decimal.rst @@ -340,442 +340,394 @@ Decimal objects Once constructed, :class:`Decimal` objects are immutable. + Decimal floating point objects share many properties with the other built-in + numeric types such as :class:`float` and :class:`int`. All of the usual math + operations and special methods apply. Likewise, decimal objects can be + copied, pickled, printed, used as dictionary keys, used as set elements, + compared, sorted, and coerced to another type (such as :class:`float` or + :class:`long`). -Decimal floating point objects share many properties with the other built-in -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 converted to another type (such as :class:`float` or :class:`int`). + In addition to the standard numeric properties, decimal floating point + objects also have a number of specialized methods: -In addition to the standard numeric properties, decimal floating point objects -also have a number of specialized methods: + .. method:: adjusted() -.. method:: Decimal.adjusted() + Return the adjusted exponent after shifting out the coefficient's + rightmost digits until only the lead digit remains: + ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the + position of the most significant digit with respect to the decimal point. - Return the adjusted exponent after shifting out the coefficient's rightmost - digits until only the lead digit remains: ``Decimal('321e+5').adjusted()`` - returns seven. Used for determining the position of the most significant digit - with respect to the decimal point. + .. method:: as_tuple() -.. method:: Decimal.as_tuple() + Return a :term:`named tuple` representation of the number: + ``DecimalTuple(sign, digits, exponent)``. - Return a :term:`named tuple` representation of the number: - ``DecimalTuple(sign, digits, exponent)``. + .. method:: canonical() -.. method:: Decimal.canonical() + Return the canonical encoding of the argument. Currently, the encoding of + a :class:`Decimal` instance is always canonical, so this operation returns + its argument unchanged. - Return the canonical encoding of the argument. Currently, the - encoding of a :class:`Decimal` instance is always canonical, so - this operation returns its argument unchanged. + .. method:: 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:: -.. method:: Decimal.compare(other[, context]) + a or b is a NaN ==> Decimal('NaN') + a < b ==> Decimal('-1') + a == b ==> Decimal('0') + a > b ==> Decimal('1') - 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:: + .. method:: compare_signal(other[, context]) - a or b is a NaN ==> Decimal('NaN') - a < b ==> Decimal('-1') - a == b ==> Decimal('0') - a > b ==> Decimal('1') + 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. -.. method:: Decimal.compare_signal(other[, context]) + .. method:: compare_total(other) - 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. + 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') -.. method:: Decimal.compare_total(other) + 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. - 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') + .. method:: compare_total_mag(other) - 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. + 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())``. + .. method:: copy_abs() -.. method:: Decimal.compare_total_mag(other) + 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. - 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())``. + .. 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. -.. method:: Decimal.copy_abs() + .. method:: copy_sign(other) - 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 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') -.. method:: Decimal.copy_negate() + 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. + .. method:: exp([context]) + Return the value of the (natural) exponential function ``e**x`` at the + given number. The result is correctly rounded using the + :const:`ROUND_HALF_EVEN` rounding mode. -.. method:: Decimal.copy_sign(other) + >>> Decimal(1).exp() + Decimal('2.718281828459045235360287471') + >>> Decimal(321).exp() + Decimal('2.561702493119680037517373933E+139') - Return a copy of the first operand with the sign set to be the - same as the sign of the second operand. For example: + .. method:: fma(other, third[, context]) - >>> 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. + Fused multiply-add. Return self*other+third with no rounding of the + intermediate product self*other. + >>> Decimal(2).fma(3, 5) + Decimal('11') -.. method:: Decimal.exp([context]) + .. method:: is_canonical() - Return the value of the (natural) exponential function ``e**x`` at the - given number. The result is correctly rounded using the - :const:`ROUND_HALF_EVEN` rounding mode. + 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`. - >>> Decimal(1).exp() - Decimal('2.718281828459045235360287471') - >>> Decimal(321).exp() - Decimal('2.561702493119680037517373933E+139') - - -.. method:: Decimal.fma(other, third[, context]) - - Fused multiply-add. Return self*other+third with no rounding of - the intermediate product self*other. - - >>> Decimal(2).fma(3, 5) - Decimal('11') - - -.. method:: Decimal.is_canonical() - - Return :const:`True` if the argument is canonical and - :const:`False` otherwise. Currently, a :class:`Decimal` instance - is always canonical, so this operation always returns - :const:`True`. - - -.. method:: is_finite() + .. method:: is_finite() - Return :const:`True` if the argument is a finite number, and - :const:`False` if the argument is an infinity or a NaN. + Return :const:`True` if the argument is a finite number, and + :const:`False` if the argument is an infinity or a NaN. + .. method:: is_infinite() -.. method:: is_infinite() + Return :const:`True` if the argument is either positive or negative + infinity and :const:`False` otherwise. - Return :const:`True` if the argument is either positive or - negative infinity and :const:`False` otherwise. + .. method:: is_nan() + Return :const:`True` if the argument is a (quiet or signaling) NaN and + :const:`False` otherwise. -.. method:: is_nan() + .. method:: is_normal() - Return :const:`True` if the argument is a (quiet or signaling) - NaN and :const:`False` otherwise. + Return :const:`True` if the argument is a *normal* finite number. Return + :const:`False` if the argument is zero, subnormal, infinite or a NaN. + .. method:: is_qnan() -.. method:: is_normal() + Return :const:`True` if the argument is a quiet NaN, and + :const:`False` otherwise. - Return :const:`True` if the argument is a *normal* finite number. - Return :const:`False` if the argument is zero, subnormal, infinite - or a NaN. + .. method:: is_signed() + Return :const:`True` if the argument has a negative sign and + :const:`False` otherwise. Note that zeros and NaNs can both carry signs. -.. method:: is_qnan() + .. method:: is_snan() - Return :const:`True` if the argument is a quiet NaN, and - :const:`False` otherwise. + Return :const:`True` if the argument is a signaling NaN and :const:`False` + otherwise. + .. method:: is_subnormal() -.. method:: is_signed() + Return :const:`True` if the argument is subnormal, and :const:`False` + otherwise. - Return :const:`True` if the argument has a negative sign and - :const:`False` otherwise. Note that zeros and NaNs can both carry - signs. + .. method:: is_zero() + Return :const:`True` if the argument is a (positive or negative) zero and + :const:`False` otherwise. -.. method:: is_snan() + .. method:: ln([context]) - Return :const:`True` if the argument is a signaling NaN and - :const:`False` otherwise. + Return the natural (base e) logarithm of the operand. The result is + correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + .. method:: log10([context]) -.. method:: is_subnormal() + Return the base ten logarithm of the operand. The result is correctly + rounded using the :const:`ROUND_HALF_EVEN` rounding mode. - Return :const:`True` if the argument is subnormal, and - :const:`False` otherwise. + .. method:: logb([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. -.. method:: is_zero() + .. method:: logical_and(other[, context]) - Return :const:`True` if the argument is a (positive or negative) - zero and :const:`False` otherwise. + :meth:`logical_and` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``and`` of the two operands. + .. method:: logical_invert(other[, context]) -.. method:: Decimal.ln([context]) + :meth:`logical_invert` is a logical operation. The argument must + be a *logical operand* (see :ref:`logical_operands_label`). The + result is the digit-wise inversion of the operand. - Return the natural (base e) logarithm of the operand. The result - is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding - mode. + .. 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 + digit-wise ``or`` of the two operands. -.. method:: Decimal.log10([context]) + .. method:: logical_xor(other[, context]) - Return the base ten logarithm of the operand. The result is - correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + :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. + .. method:: max(other[, context]) -.. method:: Decimal.logb([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). - For a nonzero number, return the adjusted exponent of its operand - as a :class:`Decimal` instance. If the operand is a zero then - ``Decimal('-Infinity')`` is returned and the - :const:`DivisionByZero` flag is raised. If the operand is an - infinity then ``Decimal('Infinity')`` is returned. + .. method:: max_mag(other[, context]) + Similar to the :meth:`max` method, but the comparison is done using the + absolute values of the operands. -.. method:: Decimal.logical_and(other[, context]) + .. method:: min(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. + 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). + .. method:: min_mag(other[, context]) -.. method:: Decimal.logical_invert(other[, context]) + Similar to the :meth:`min` method, but the comparison is done using the + absolute values of the operands. - :meth:`logical_invert` is a logical operation. The argument must - be a *logical operand* (see :ref:`logical_operands_label`). The - result is the digit-wise inversion of the operand. + .. 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. -.. method:: Decimal.logical_or(other[, context]) + .. method:: next_plus([context]) - :meth:`logical_or` is a logical operation which takes two *logical - operands* (see :ref:`logical_operands_label`). The result is the - digit-wise ``or`` of the two operands. + Return the smallest number representable in the given context (or in the + current thread's context if no context is given) that is larger than the + given operand. + .. method:: next_toward(other[, context]) -.. method:: Decimal.logical_xor(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. - :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. + .. 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')``. -.. method:: Decimal.max(other[, context]) + .. method:: number_class([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). + 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. + * ``"-Subnormal"``, indicating that the operand is negative and subnormal. + * ``"-Zero"``, indicating that the operand is a negative zero. + * ``"+Zero"``, indicating that the operand is a positive zero. + * ``"+Subnormal"``, indicating that the operand is positive and subnormal. + * ``"+Normal"``, indicating that the operand is a positive normal number. + * ``"+Infinity"``, indicating that the operand is positive infinity. + * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). + * ``"sNaN"``, indicating that the operand is a signaling NaN. -.. method:: Decimal.max_mag(other[, context]) + .. method:: quantize(exp[, rounding[, context[, watchexp]]]) - Similar to the :meth:`max` method, but the comparison is done using - the absolute values of the operands. + 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') -.. method:: Decimal.min(other[, context]) + 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. - 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). + Also unlike other operations, quantize never signals Underflow, even if + the result is subnormal and inexact. -.. method:: Decimal.min_mag(other[, context]) + 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. - Similar to the :meth:`min` method, but the comparison is done using - the absolute values of the operands. + If *watchexp* is set (default), then an error is returned whenever the + resulting exponent is greater than :attr:`Emax` or less than + :attr:`Etiny`. + .. method:: radix() -.. method:: Decimal.next_minus([context]) + Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` + class does all its arithmetic. Included for compatibility with the + specification. - 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. + .. 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')``. -.. method:: Decimal.next_plus([context]) + If both are equally close, the one chosen will have the same sign as + *self*. - Return the smallest number representable in the given context (or - in the current thread's context if no context is given) that is - larger than the given operand. + .. method:: 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. -.. method:: Decimal.next_toward(other[, context]) + .. method:: same_quantum(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. + Test whether self and other have the same exponent or whether both are + :const:`NaN`. + .. method:: scaleb(other[, context]) -.. method:: Decimal.normalize([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. - 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:: 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. -.. method:: Decimal.number_class([context]) + .. method:: sqrt([context]) - Return a string describing the *class* of the operand. The - returned value is one of the following ten strings. + Return the square root of the argument to full precision. - * ``"-Infinity"``, indicating that the operand is negative infinity. - * ``"-Normal"``, indicating that the operand is a negative normal number. - * ``"-Subnormal"``, indicating that the operand is negative and subnormal. - * ``"-Zero"``, indicating that the operand is a negative zero. - * ``"+Zero"``, indicating that the operand is a positive zero. - * ``"+Subnormal"``, indicating that the operand is positive and subnormal. - * ``"+Normal"``, indicating that the operand is a positive normal number. - * ``"+Infinity"``, indicating that the operand is positive infinity. - * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). - * ``"sNaN"``, indicating that the operand is a signaling NaN. + .. method:: to_eng_string([context]) -.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) + Convert to an engineering-type string. - Return a value equal to the first operand after rounding and - having the exponent of the second operand. + 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')`` - >>> Decimal('1.41421356').quantize(Decimal('1.000')) - Decimal('1.414') + .. method:: to_integral([rounding[, context]]) - 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. + Identical to the :meth:`to_integral_value` method. The ``to_integral`` + name has been kept for compatibility with older versions. - Also unlike other operations, quantize never signals Underflow, - even if the result is subnormal and inexact. + .. method:: to_integral_exact([rounding[, context]]) - 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. + 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. - If *watchexp* is set (default), then an error is returned whenever the - resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. + .. method:: to_integral_value([rounding[, context]]) -.. method:: Decimal.radix() - - Return ``Decimal(10)``, the radix (base) in which the - :class:`Decimal` class does all its arithmetic. Included for - compatibility with the specification. - - -.. method:: Decimal.remainder_near(other[, context]) - - Compute the modulo as either a positive or negative value depending on which is - closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns - ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``. - - If both are equally close, the one chosen will have the same sign as *self*. - -.. method:: Decimal.rotate(other[, context]) - - Return the result of rotating the digits of the first operand by - an amount specified by the second operand. The second operand - must be an integer in the range -precision through precision. The - absolute value of the second operand gives the number of places to - rotate. If the second operand is positive then rotation is to the - left; otherwise rotation is to the right. The coefficient of the - first operand is padded on the left with zeros to length precision - if necessary. The sign and exponent of the first operand are - unchanged. - - -.. method:: Decimal.same_quantum(other[, context]) - - Test whether self and other have the same exponent or whether both are - :const:`NaN`. + 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. -.. method:: Decimal.scaleb(other[, context]) + .. method:: trim() - 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. - - -.. 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 - are unchanged. - - -.. method:: Decimal.sqrt([context]) - - Return the square root of the argument to full precision. - - -.. method:: Decimal.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 - ``Decimal('123E+1')`` to ``Decimal('1.23E+3')`` - -.. method:: Decimal.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]]) - - Round to the nearest integer, signaling - :const:`Inexact` or :const:`Rounded` as appropriate if rounding - occurs. The rounding mode is determined by the ``rounding`` - parameter if given, else by the given ``context``. If neither - parameter is given then the rounding mode of the current context is - used. - - -.. method:: Decimal.to_integral_value([rounding[, context]]) - - 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. - - -.. method:: Decimal.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. .. _logical_operands_label: @@ -916,150 +868,147 @@ In addition to the three supplied contexts, new contexts can be created with the lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. -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() + 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)``. - Resets all of the flags to :const:`0`. + .. method:: clear_flags() -.. method:: Context.copy() + Resets all of the flags to :const:`0`. - Return a duplicate of the context. + .. method:: copy() -.. method:: Context.copy_decimal(num) + Return a duplicate of the context. - Return a copy of the Decimal instance num. + .. method:: copy_decimal(num) -.. method:: Context.create_decimal(num) + Return a copy of the Decimal instance 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. + .. method:: create_decimal(num) - 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: + 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. - .. doctest:: newcontext + 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: - >>> getcontext().prec = 3 - >>> Decimal('3.4445') + Decimal('1.0023') - Decimal('4.45') - >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') - Decimal('4.44') + .. doctest:: newcontext - This method implements the to-number operation of the IBM - specification. If the argument is a string, no leading or trailing - whitespace is permitted. + >>> getcontext().prec = 3 + >>> Decimal('3.4445') + Decimal('1.0023') + Decimal('4.45') + >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') + Decimal('4.44') -.. method:: Context.Etiny() + This method implements the to-number operation of the IBM specification. + If the argument is a string, no leading or trailing whitespace is + permitted. - 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:: 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() - Returns a value equal to ``Emax - prec + 1``. + .. method:: Etop() -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. + 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. -.. method:: Context.abs(x) - Returns the absolute value of *x*. + .. method:: abs(x) + Returns the absolute value of *x*. -.. method:: Context.add(x, y) - Return the sum of *x* and *y*. + .. method:: add(x, y) + Return the sum of *x* and *y*. -.. method:: Context.divide(x, y) - Return *x* divided by *y*. + .. method:: divide(x, y) + Return *x* divided by *y*. -.. method:: Context.divide_int(x, y) - Return *x* divided by *y*, truncated to an integer. + .. method:: divide_int(x, y) + Return *x* divided by *y*, truncated to an integer. -.. method:: Context.divmod(x, y) - Divides two numbers and returns the integer part of the result. + .. method:: divmod(x, y) + Divides two numbers and returns the integer part of the result. -.. method:: Context.minus(x) - Minus corresponds to the unary prefix minus operator in Python. + .. method:: minus(x) + Minus corresponds to the unary prefix minus operator in Python. -.. method:: Context.multiply(x, y) - Return the product of *x* and *y*. + .. method:: multiply(x, y) + Return the product of *x* and *y*. -.. method:: Context.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. + .. 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. -.. method:: Context.power(x, y[, modulo]) - Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if - given. + .. method:: power(x, y[, modulo]) - 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. + Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given. - With three arguments, compute ``(x**y) % modulo``. For the three - argument form, the following restrictions on the arguments hold: + 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. - - 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 + With three arguments, compute ``(x**y) % modulo``. For the three argument + form, the following restrictions on the arguments hold: - 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. + - 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. -.. method:: Context.remainder(x, y) + .. method:: remainder(x, y) - Returns the remainder from integer division. + Returns the remainder from integer division. - The sign of the result, if non-zero, is the same as that of the original - dividend. + 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*. + Return the difference between *x* and *y*. -.. method:: Context.to_sci_string(x) + .. method:: to_sci_string(x) - Converts a number to a string using scientific notation. + Converts a number to a string using scientific notation. .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -1138,28 +1087,29 @@ condition. 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 diff --git a/Doc/library/difflib.rst b/Doc/library/difflib.rst index 585fa74..01c9c85 100644 --- a/Doc/library/difflib.rst +++ b/Doc/library/difflib.rst @@ -343,166 +343,171 @@ The :class:`SequenceMatcher` class has this constructor: The optional arguments *a* and *b* are sequences to be compared; both default to empty strings. The elements of both sequences must be :term:`hashable`. -:class:`SequenceMatcher` objects have the following methods: + :class:`SequenceMatcher` objects have the following methods: -.. method:: SequenceMatcher.set_seqs(a, b) + .. method:: set_seqs(a, b) - Set the two sequences to be compared. + Set the two sequences to be compared. -:class:`SequenceMatcher` computes and caches detailed information about the -second sequence, so if you want to compare one sequence against many sequences, -use :meth:`set_seq2` to set the commonly used sequence once and call -:meth:`set_seq1` repeatedly, once for each of the other sequences. + :class:`SequenceMatcher` computes and caches detailed information about the + second sequence, so if you want to compare one sequence against many + sequences, use :meth:`set_seq2` to set the commonly used sequence once and + call :meth:`set_seq1` repeatedly, once for each of the other sequences. -.. method:: SequenceMatcher.set_seq1(a) + .. method:: set_seq1(a) - Set the first sequence to be compared. The second sequence to be compared is - not changed. + Set the first sequence to be compared. The second sequence to be compared + is not changed. -.. method:: SequenceMatcher.set_seq2(b) + .. method:: set_seq2(b) - Set the second sequence to be compared. The first sequence to be compared is - not changed. + Set the second sequence to be compared. The first sequence to be compared + is not changed. -.. method:: SequenceMatcher.find_longest_match(alo, ahi, blo, bhi) + .. method:: find_longest_match(alo, ahi, blo, bhi) - Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. + Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. - If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns ``(i, j, - k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <= - ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those - conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i == - i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks, - return one that starts earliest in *a*, and of all those maximal matching blocks - that start earliest in *a*, return the one that starts earliest in *b*. + If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns + ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo + <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', + k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i + <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of + all maximal matching blocks, return one that starts earliest in *a*, and + of all those maximal matching blocks that start earliest in *a*, return + the one that starts earliest in *b*. - >>> s = SequenceMatcher(None, " abcd", "abcd abcd") - >>> s.find_longest_match(0, 5, 0, 9) - Match(a=0, b=4, size=5) + >>> s = SequenceMatcher(None, " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=0, b=4, size=5) - If *isjunk* was provided, first the longest matching block is determined as - above, but with the additional restriction that no junk element appears in the - block. Then that block is extended as far as possible by matching (only) junk - elements on both sides. So the resulting block never matches on junk except as - identical junk happens to be adjacent to an interesting match. + If *isjunk* was provided, first the longest matching block is determined + as above, but with the additional restriction that no junk element appears + in the block. Then that block is extended as far as possible by matching + (only) junk elements on both sides. So the resulting block never matches + on junk except as identical junk happens to be adjacent to an interesting + match. - Here's the same example as before, but considering blanks to be junk. That - prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second - sequence directly. Instead only the ``'abcd'`` can match, and matches the - leftmost ``'abcd'`` in the second sequence: + Here's the same example as before, but considering blanks to be junk. That + prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the + second sequence directly. Instead only the ``'abcd'`` can match, and + matches the leftmost ``'abcd'`` in the second sequence: - >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") - >>> s.find_longest_match(0, 5, 0, 9) - Match(a=1, b=0, size=4) + >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") + >>> s.find_longest_match(0, 5, 0, 9) + Match(a=1, b=0, size=4) - If no blocks match, this returns ``(alo, blo, 0)``. + If no blocks match, this returns ``(alo, blo, 0)``. - This method returns a :term:`named tuple` ``Match(a, b, size)``. + This method returns a :term:`named tuple` ``Match(a, b, size)``. -.. method:: SequenceMatcher.get_matching_blocks() + .. method:: get_matching_blocks() - Return list of triples describing matching subsequences. Each triple is of the - form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The triples are - monotonically increasing in *i* and *j*. + Return list of triples describing matching subsequences. Each triple is of + the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The + triples are monotonically increasing in *i* and *j*. - The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It is - the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` are - adjacent triples in the list, and the second is not the last triple in the list, - then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always - describe non-adjacent equal blocks. + The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It + is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` + are adjacent triples in the list, and the second is not the last triple in + the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent + triples always describe non-adjacent equal blocks. - .. XXX Explain why a dummy is used! + .. XXX Explain why a dummy is used! - .. doctest:: + .. doctest:: - >>> s = SequenceMatcher(None, "abxcd", "abcd") - >>> s.get_matching_blocks() - [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] + >>> s = SequenceMatcher(None, "abxcd", "abcd") + >>> s.get_matching_blocks() + [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] -.. method:: SequenceMatcher.get_opcodes() + .. method:: get_opcodes() - Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is of - the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == 0``, and - remaining tuples have *i1* equal to the *i2* from the preceding tuple, and, - likewise, *j1* equal to the previous *j2*. + Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is + of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == + 0``, and remaining tuples have *i1* equal to the *i2* from the preceding + tuple, and, likewise, *j1* equal to the previous *j2*. - The *tag* values are strings, with these meanings: + The *tag* values are strings, with these meanings: - +---------------+---------------------------------------------+ - | Value | Meaning | - +===============+=============================================+ - | ``'replace'`` | ``a[i1:i2]`` should be replaced by | - | | ``b[j1:j2]``. | - +---------------+---------------------------------------------+ - | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | - | | ``j1 == j2`` in this case. | - +---------------+---------------------------------------------+ - | ``'insert'`` | ``b[j1:j2]`` should be inserted at | - | | ``a[i1:i1]``. Note that ``i1 == i2`` in | - | | this case. | - +---------------+---------------------------------------------+ - | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | - | | are equal). | - +---------------+---------------------------------------------+ + +---------------+---------------------------------------------+ + | Value | Meaning | + +===============+=============================================+ + | ``'replace'`` | ``a[i1:i2]`` should be replaced by | + | | ``b[j1:j2]``. | + +---------------+---------------------------------------------+ + | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | + | | ``j1 == j2`` in this case. | + +---------------+---------------------------------------------+ + | ``'insert'`` | ``b[j1:j2]`` should be inserted at | + | | ``a[i1:i1]``. Note that ``i1 == i2`` in | + | | this case. | + +---------------+---------------------------------------------+ + | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | + | | are equal). | + +---------------+---------------------------------------------+ - For example: + For example: - >>> a = "qabxcd" - >>> b = "abycdf" - >>> s = SequenceMatcher(None, a, b) - >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) - delete a[0:1] (q) b[0:0] () - equal a[1:3] (ab) b[0:2] (ab) - replace a[3:4] (x) b[2:3] (y) - equal a[4:6] (cd) b[3:5] (cd) - insert a[6:6] () b[5:6] (f) + >>> a = "qabxcd" + >>> b = "abycdf" + >>> s = SequenceMatcher(None, a, b) + >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) + delete a[0:1] (q) b[0:0] () + equal a[1:3] (ab) b[0:2] (ab) + replace a[3:4] (x) b[2:3] (y) + equal a[4:6] (cd) b[3:5] (cd) + insert a[6:6] () b[5:6] (f) -.. method:: SequenceMatcher.get_grouped_opcodes([n]) + .. method:: get_grouped_opcodes([n]) - Return a :term:`generator` of groups with up to *n* lines of context. + Return a :term:`generator` of groups with up to *n* lines of context. - Starting with the groups returned by :meth:`get_opcodes`, this method splits out - smaller change clusters and eliminates intervening ranges which have no changes. + Starting with the groups returned by :meth:`get_opcodes`, this method + splits out smaller change clusters and eliminates intervening ranges which + have no changes. - The groups are returned in the same format as :meth:`get_opcodes`. + The groups are returned in the same format as :meth:`get_opcodes`. -.. method:: SequenceMatcher.ratio() + .. method:: ratio() - Return a measure of the sequences' similarity as a float in the range [0, 1]. + Return a measure of the sequences' similarity as a float in the range [0, + 1]. - Where T is the total number of elements in both sequences, and M is the number - of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the sequences are - identical, and ``0.0`` if they have nothing in common. + Where T is the total number of elements in both sequences, and M is the + number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the + sequences are identical, and ``0.0`` if they have nothing in common. - This is expensive to compute if :meth:`get_matching_blocks` or - :meth:`get_opcodes` hasn't already been called, in which case you may want to - try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper bound. + This is expensive to compute if :meth:`get_matching_blocks` or + :meth:`get_opcodes` hasn't already been called, in which case you may want + to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an + upper bound. -.. method:: SequenceMatcher.quick_ratio() + .. method:: quick_ratio() - Return an upper bound on :meth:`ratio` relatively quickly. + Return an upper bound on :meth:`ratio` relatively quickly. - This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is - faster to compute. + This isn't defined beyond that it is an upper bound on :meth:`ratio`, and + is faster to compute. -.. method:: SequenceMatcher.real_quick_ratio() + .. method:: real_quick_ratio() - Return an upper bound on :meth:`ratio` very quickly. + Return an upper bound on :meth:`ratio` very quickly. - This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is - faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. + This isn't defined beyond that it is an upper bound on :meth:`ratio`, and + is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`. The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although @@ -589,17 +594,17 @@ The :class:`Differ` class has this constructor: length 1), and returns true if the character is junk. The default is ``None``, meaning that no character is considered junk. -:class:`Differ` objects are used (deltas generated) via a single method: + :class:`Differ` objects are used (deltas generated) via a single method: -.. method:: Differ.compare(a, b) + .. method:: Differ.compare(a, b) - Compare two sequences of lines, and generate the delta (a sequence of lines). + Compare two sequences of lines, and generate the delta (a sequence of lines). - Each sequence must contain individual single-line strings ending with newlines. - Such sequences can be obtained from the :meth:`readlines` method of file-like - objects. The delta generated also consists of newline-terminated strings, ready - to be printed as-is via the :meth:`writelines` method of a file-like object. + Each sequence must contain individual single-line strings ending with newlines. + Such sequences can be obtained from the :meth:`readlines` method of file-like + objects. The delta generated also consists of newline-terminated strings, ready + to be printed as-is via the :meth:`writelines` method of a file-like object. .. _differ-examples: diff --git a/Doc/library/doctest.rst b/Doc/library/doctest.rst index ee03572..aa662c0 100644 --- a/Doc/library/doctest.rst +++ b/Doc/library/doctest.rst @@ -1113,48 +1113,48 @@ DocTest Objects names. -:class:`DocTest` defines the following member variables. They are initialized -by the constructor, and should not be modified directly. + :class:`DocTest` defines the following member variables. They are initialized by + the constructor, and should not be modified directly. -.. attribute:: DocTest.examples + .. attribute:: examples - A list of :class:`Example` objects encoding the individual interactive Python - examples that should be run by this test. + A list of :class:`Example` objects encoding the individual interactive Python + examples that should be run by this test. -.. attribute:: DocTest.globs + .. attribute:: globs - The namespace (aka globals) that the examples should be run in. This is a - dictionary mapping names to values. Any changes to the namespace made by the - examples (such as binding new variables) will be reflected in :attr:`globs` - after the test is run. + The namespace (aka globals) that the examples should be run in. This is a + dictionary mapping names to values. Any changes to the namespace made by the + examples (such as binding new variables) will be reflected in :attr:`globs` + after the test is run. -.. attribute:: DocTest.name + .. attribute:: name - A string name identifying the :class:`DocTest`. Typically, this is the name of - the object or file that the test was extracted from. + A string name identifying the :class:`DocTest`. Typically, this is the name + of the object or file that the test was extracted from. -.. attribute:: DocTest.filename + .. attribute:: filename - The name of the file that this :class:`DocTest` was extracted from; or ``None`` - if the filename is unknown, or if the :class:`DocTest` was not extracted from a - file. + The name of the file that this :class:`DocTest` was extracted from; or + ``None`` if the filename is unknown, or if the :class:`DocTest` was not + extracted from a file. -.. attribute:: DocTest.lineno + .. attribute:: lineno - The line number within :attr:`filename` where this :class:`DocTest` begins, or - ``None`` if the line number is unavailable. This line number is zero-based with - respect to the beginning of the file. + The line number within :attr:`filename` where this :class:`DocTest` begins, or + ``None`` if the line number is unavailable. This line number is zero-based + with respect to the beginning of the file. -.. attribute:: DocTest.docstring + .. attribute:: docstring - The string that the test was extracted from, or 'None' if the string is - unavailable, or if the test was not extracted from a string. + The string that the test was extracted from, or 'None' if the string is + unavailable, or if the test was not extracted from a string. .. _doctest-example: @@ -1170,53 +1170,53 @@ Example Objects of the same names. -:class:`Example` defines the following member variables. They are initialized -by the constructor, and should not be modified directly. + :class:`Example` defines the following member variables. They are initialized by + the constructor, and should not be modified directly. -.. attribute:: Example.source + .. attribute:: source - A string containing the example's source code. This source code consists of a - single Python statement, and always ends with a newline; the constructor adds a - newline when necessary. + A string containing the example's source code. This source code consists of a + single Python statement, and always ends with a newline; the constructor adds + a newline when necessary. -.. attribute:: Example.want + .. attribute:: want - The expected output from running the example's source code (either from stdout, - or a traceback in case of exception). :attr:`want` ends with a newline unless - no output is expected, in which case it's an empty string. The constructor adds - a newline when necessary. + The expected output from running the example's source code (either from + stdout, or a traceback in case of exception). :attr:`want` ends with a + newline unless no output is expected, in which case it's an empty string. The + constructor adds a newline when necessary. -.. attribute:: Example.exc_msg + .. attribute:: exc_msg - The exception message generated by the example, if the example is expected to - generate an exception; or ``None`` if it is not expected to generate an - exception. This exception message is compared against the return value of - :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline - unless it's ``None``. The constructor adds a newline if needed. + The exception message generated by the example, if the example is expected to + generate an exception; or ``None`` if it is not expected to generate an + exception. This exception message is compared against the return value of + :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline + unless it's ``None``. The constructor adds a newline if needed. -.. attribute:: Example.lineno + .. attribute:: lineno - The line number within the string containing this example where the example - begins. This line number is zero-based with respect to the beginning of the - containing string. + The line number within the string containing this example where the example + begins. This line number is zero-based with respect to the beginning of the + containing string. -.. attribute:: Example.indent + .. attribute:: indent - The example's indentation in the containing string, i.e., the number of space - characters that precede the example's first prompt. + The example's indentation in the containing string, i.e., the number of space + characters that precede the example's first prompt. -.. attribute:: Example.options + .. attribute:: options - A dictionary mapping from option flags to ``True`` or ``False``, which is used - to override default options for this example. Any option flags not contained in - this dictionary are left at their default value (as specified by the - :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. + A dictionary mapping from option flags to ``True`` or ``False``, which is used + to override default options for this example. Any option flags not contained + in this dictionary are left at their default value (as specified by the + :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. .. _doctest-doctestfinder: @@ -1246,44 +1246,44 @@ DocTestFinder objects :meth:`DocTestFinder.find` will include tests for objects with empty docstrings. -:class:`DocTestFinder` defines the following method: + :class:`DocTestFinder` defines the following method: -.. method:: DocTestFinder.find(obj[, name][, module][, globs][, extraglobs]) + .. method:: find(obj[, name][, module][, globs][, extraglobs]) - Return a list of the :class:`DocTest`\ s that are defined by *obj*'s docstring, - or by any of its contained objects' docstrings. + Return a list of the :class:`DocTest`\ s that are defined by *obj*'s + docstring, or by any of its contained objects' docstrings. - The optional argument *name* specifies the object's name; this name will be used - to construct names for the returned :class:`DocTest`\ s. If *name* is not - specified, then ``obj.__name__`` is used. + The optional argument *name* specifies the object's name; this name will be + used to construct names for the returned :class:`DocTest`\ s. If *name* is + not specified, then ``obj.__name__`` is used. - The optional parameter *module* is the module that contains the given object. - If the module is not specified or is None, then the test finder will attempt to - automatically determine the correct module. The object's module is used: + The optional parameter *module* is the module that contains the given object. + If the module is not specified or is None, then the test finder will attempt + to automatically determine the correct module. The object's module is used: - * As a default namespace, if *globs* is not specified. + * As a default namespace, if *globs* is not specified. - * To prevent the DocTestFinder from extracting DocTests from objects that are - imported from other modules. (Contained objects with modules other than - *module* are ignored.) + * To prevent the DocTestFinder from extracting DocTests from objects that are + imported from other modules. (Contained objects with modules other than + *module* are ignored.) - * To find the name of the file containing the object. + * To find the name of the file containing the object. - * To help find the line number of the object within its file. + * To help find the line number of the object within its file. - If *module* is ``False``, no attempt to find the module will be made. This is - obscure, of use mostly in testing doctest itself: if *module* is ``False``, or - is ``None`` but cannot be found automatically, then all objects are considered - to belong to the (non-existent) module, so all contained objects will - (recursively) be searched for doctests. + If *module* is ``False``, no attempt to find the module will be made. This is + obscure, of use mostly in testing doctest itself: if *module* is ``False``, or + is ``None`` but cannot be found automatically, then all objects are considered + to belong to the (non-existent) module, so all contained objects will + (recursively) be searched for doctests. - The globals for each :class:`DocTest` is formed by combining *globs* and - *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new - shallow copy of the globals dictionary is created for each :class:`DocTest`. If - *globs* is not specified, then it defaults to the module's *__dict__*, if - specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it - defaults to ``{}``. + The globals for each :class:`DocTest` is formed by combining *globs* and + *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new + shallow copy of the globals dictionary is created for each :class:`DocTest`. + If *globs* is not specified, then it defaults to the module's *__dict__*, if + specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it + defaults to ``{}``. .. _doctest-doctestparser: @@ -1298,32 +1298,32 @@ DocTestParser objects them to create a :class:`DocTest` object. -:class:`DocTestParser` defines the following methods: + :class:`DocTestParser` defines the following methods: -.. method:: DocTestParser.get_doctest(string, globs, name, filename, lineno) + .. method:: get_doctest(string, globs, name, filename, lineno) - Extract all doctest examples from the given string, and collect them into a - :class:`DocTest` object. + Extract all doctest examples from the given string, and collect them into a + :class:`DocTest` object. - *globs*, *name*, *filename*, and *lineno* are attributes for the new - :class:`DocTest` object. See the documentation for :class:`DocTest` for more - information. + *globs*, *name*, *filename*, and *lineno* are attributes for the new + :class:`DocTest` object. See the documentation for :class:`DocTest` for more + information. -.. method:: DocTestParser.get_examples(string[, name]) + .. method:: get_examples(string[, name]) - Extract all doctest examples from the given string, and return them as a list of - :class:`Example` objects. Line numbers are 0-based. The optional argument - *name* is a name identifying this string, and is only used for error messages. + Extract all doctest examples from the given string, and return them as a list + of :class:`Example` objects. Line numbers are 0-based. The optional argument + *name* is a name identifying this string, and is only used for error messages. -.. method:: DocTestParser.parse(string[, name]) + .. method:: parse(string[, name]) - Divide the given string into examples and intervening text, and return them as a - list of alternating :class:`Example`\ s and strings. Line numbers for the - :class:`Example`\ s are 0-based. The optional argument *name* is a name - identifying this string, and is only used for error messages. + Divide the given string into examples and intervening text, and return them as + a list of alternating :class:`Example`\ s and strings. Line numbers for the + :class:`Example`\ s are 0-based. The optional argument *name* is a name + identifying this string, and is only used for error messages. .. _doctest-doctestrunner: @@ -1366,81 +1366,81 @@ DocTestRunner objects For more information, see section :ref:`doctest-options`. -:class:`DocTestParser` defines the following methods: + :class:`DocTestParser` defines the following methods: -.. method:: DocTestRunner.report_start(out, test, example) + .. method:: report_start(out, test, example) - Report that the test runner is about to process the given example. This method - is provided to allow subclasses of :class:`DocTestRunner` to customize their - output; it should not be called directly. + Report that the test runner is about to process the given example. This method + is provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. - *example* is the example about to be processed. *test* is the test containing - *example*. *out* is the output function that was passed to - :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *test* is the test + *containing example*. *out* is the output function that was passed to + :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_success(out, test, example, got) + .. method:: report_success(out, test, example, got) - Report that the given example ran successfully. This method is provided to - allow subclasses of :class:`DocTestRunner` to customize their output; it should - not be called directly. + Report that the given example ran successfully. This method is provided to + allow subclasses of :class:`DocTestRunner` to customize their output; it + should not be called directly. - *example* is the example about to be processed. *got* is the actual output from - the example. *test* is the test containing *example*. *out* is the output - function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_failure(out, test, example, got) + .. method:: report_failure(out, test, example, got) - Report that the given example failed. This method is provided to allow - subclasses of :class:`DocTestRunner` to customize their output; it should not be - called directly. + Report that the given example failed. This method is provided to allow + subclasses of :class:`DocTestRunner` to customize their output; it should not + be called directly. - *example* is the example about to be processed. *got* is the actual output from - the example. *test* is the test containing *example*. *out* is the output - function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *got* is the actual output + from the example. *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.report_unexpected_exception(out, test, example, exc_info) + .. method:: report_unexpected_exception(out, test, example, exc_info) - Report that the given example raised an unexpected exception. This method is - provided to allow subclasses of :class:`DocTestRunner` to customize their - output; it should not be called directly. + Report that the given example raised an unexpected exception. This method is + provided to allow subclasses of :class:`DocTestRunner` to customize their + output; it should not be called directly. - *example* is the example about to be processed. *exc_info* is a tuple containing - information about the unexpected exception (as returned by - :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the - output function that was passed to :meth:`DocTestRunner.run`. + *example* is the example about to be processed. *exc_info* is a tuple + containing information about the unexpected exception (as returned by + :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the + output function that was passed to :meth:`DocTestRunner.run`. -.. method:: DocTestRunner.run(test[, compileflags][, out][, clear_globs]) + .. method:: run(test[, compileflags][, out][, clear_globs]) - Run the examples in *test* (a :class:`DocTest` object), and display the results - using the writer function *out*. + Run the examples in *test* (a :class:`DocTest` object), and display the + results using the writer function *out*. - The examples are run in the namespace ``test.globs``. If *clear_globs* is true - (the default), then this namespace will be cleared after the test runs, to help - with garbage collection. If you would like to examine the namespace after the - test completes, then use *clear_globs=False*. + The examples are run in the namespace ``test.globs``. If *clear_globs* is + true (the default), then this namespace will be cleared after the test runs, + to help with garbage collection. If you would like to examine the namespace + after the test completes, then use *clear_globs=False*. - *compileflags* gives the set of flags that should be used by the Python compiler - when running the examples. If not specified, then it will default to the set of - future-import flags that apply to *globs*. + *compileflags* gives the set of flags that should be used by the Python + compiler when running the examples. If not specified, then it will default to + the set of future-import flags that apply to *globs*. - The output of each example is checked using the :class:`DocTestRunner`'s output - checker, and the results are formatted by the :meth:`DocTestRunner.report_\*` - methods. + The output of each example is checked using the :class:`DocTestRunner`'s + output checker, and the results are formatted by the + :meth:`DocTestRunner.report_\*` methods. -.. method:: DocTestRunner.summarize([verbose]) + .. method:: summarize([verbose]) - Print a summary of all the test cases that have been run by this DocTestRunner, - and return a :term:`named tuple` ``TestResults(failed, attempted)``. - - The optional *verbose* argument controls how detailed the summary is. If the - verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is used. + 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. .. _doctest-outputchecker: @@ -1457,22 +1457,22 @@ OutputChecker objects the differences between two outputs. -:class:`OutputChecker` defines the following methods: + :class:`OutputChecker` defines the following methods: -.. method:: OutputChecker.check_output(want, got, optionflags) + .. method:: check_output(want, got, optionflags) - Return ``True`` iff the actual output from an example (*got*) matches the - expected output (*want*). These strings are always considered to match if they - are identical; but depending on what option flags the test runner is using, - several non-exact match types are also possible. See section - :ref:`doctest-options` for more information about option flags. + Return ``True`` iff the actual output from an example (*got*) matches the + expected output (*want*). These strings are always considered to match if + they are identical; but depending on what option flags the test runner is + using, several non-exact match types are also possible. See section + :ref:`doctest-options` for more information about option flags. -.. method:: OutputChecker.output_difference(example, got, optionflags) + .. method:: output_difference(example, got, optionflags) - Return a string describing the differences between the expected output for a - given example (*example*) and the actual output (*got*). *optionflags* is the - set of option flags used to compare *want* and *got*. + Return a string describing the differences between the expected output for a + given example (*example*) and the actual output (*got*). *optionflags* is the + set of option flags used to compare *want* and *got*. .. _doctest-debugging: diff --git a/Doc/library/email.charset.rst b/Doc/library/email.charset.rst index 3a18220..01529a0 100644 --- a/Doc/library/email.charset.rst +++ b/Doc/library/email.charset.rst @@ -38,164 +38,168 @@ Import this class from the :mod:`email.charset` module. will not be encoded, but output text will be converted from the ``euc-jp`` character set to the ``iso-2022-jp`` character set. -:class:`Charset` instances have the following data attributes: + :class:`Charset` instances have the following data attributes: -.. data:: input_charset + .. attribute:: input_charset - The initial character set specified. Common aliases are converted to their - *official* email names (e.g. ``latin_1`` is converted to ``iso-8859-1``). - Defaults to 7-bit ``us-ascii``. + The initial character set specified. Common aliases are converted to + their *official* email names (e.g. ``latin_1`` is converted to + ``iso-8859-1``). Defaults to 7-bit ``us-ascii``. -.. data:: header_encoding + .. attribute:: header_encoding - If the character set must be encoded before it can be used in an email header, - this attribute will be set to ``Charset.QP`` (for quoted-printable), - ``Charset.BASE64`` (for base64 encoding), or ``Charset.SHORTEST`` for the - shortest of QP or BASE64 encoding. Otherwise, it will be ``None``. + If the character set must be encoded before it can be used in an email + header, this attribute will be set to ``Charset.QP`` (for + quoted-printable), ``Charset.BASE64`` (for base64 encoding), or + ``Charset.SHORTEST`` for the shortest of QP or BASE64 encoding. Otherwise, + it will be ``None``. -.. data:: body_encoding + .. attribute:: body_encoding - Same as *header_encoding*, but describes the encoding for the mail message's - body, which indeed may be different than the header encoding. - ``Charset.SHORTEST`` is not allowed for *body_encoding*. + Same as *header_encoding*, but describes the encoding for the mail + message's body, which indeed may be different than the header encoding. + ``Charset.SHORTEST`` is not allowed for *body_encoding*. -.. data:: output_charset + .. attribute:: output_charset - Some character sets must be converted before they can be used in email headers - or bodies. If the *input_charset* is one of them, this attribute will contain - the name of the character set output will be converted to. Otherwise, it will - be ``None``. + Some character sets must be converted before they can be used in email headers + or bodies. If the *input_charset* is one of them, this attribute will + contain the name of the character set output will be converted to. Otherwise, it will + be ``None``. -.. data:: input_codec + .. attribute:: input_codec - The name of the Python codec used to convert the *input_charset* to Unicode. If - no conversion codec is necessary, this attribute will be ``None``. + The name of the Python codec used to convert the *input_charset* to + Unicode. If no conversion codec is necessary, this attribute will be + ``None``. -.. data:: output_codec + .. attribute:: output_codec - The name of the Python codec used to convert Unicode to the *output_charset*. - If no conversion codec is necessary, this attribute will have the same value as - the *input_codec*. + The name of the Python codec used to convert Unicode to the + *output_charset*. If no conversion codec is necessary, this attribute + will have the same value as the *input_codec*. -:class:`Charset` instances also have the following methods: + :class:`Charset` instances also have the following methods: -.. method:: Charset.get_body_encoding() + .. method:: get_body_encoding() - Return the content transfer encoding used for body encoding. + Return the content transfer encoding used for body encoding. - This is either the string ``quoted-printable`` or ``base64`` depending on the - encoding used, or it is a function, in which case you should call the function - with a single argument, the Message object being encoded. The function should - then set the :mailheader:`Content-Transfer-Encoding` header itself to whatever - is appropriate. + This is either the string ``quoted-printable`` or ``base64`` depending on + the encoding used, or it is a function, in which case you should call the + function with a single argument, the Message object being encoded. The + function should then set the :mailheader:`Content-Transfer-Encoding` + header itself to whatever is appropriate. - Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, returns - the string ``base64`` if *body_encoding* is ``BASE64``, and returns the string - ``7bit`` otherwise. + Returns the string ``quoted-printable`` if *body_encoding* is ``QP``, + returns the string ``base64`` if *body_encoding* is ``BASE64``, and + returns the string ``7bit`` otherwise. -.. method:: Charset.convert(s) + .. method:: convert(s) - Convert the string *s* from the *input_codec* to the *output_codec*. + Convert the string *s* from the *input_codec* to the *output_codec*. -.. method:: Charset.to_splittable(s) + .. method:: to_splittable(s) - Convert a possibly multibyte string to a safely splittable format. *s* is the - string to split. + Convert a possibly multibyte string to a safely splittable format. *s* is + the string to split. - Uses the *input_codec* to try and convert the string to Unicode, so it can be - safely split on character boundaries (even for multibyte characters). + Uses the *input_codec* to try and convert the string to Unicode, so it can + be safely split on character boundaries (even for multibyte characters). - Returns the string as-is if it isn't known how to convert *s* to Unicode with - the *input_charset*. + Returns the string as-is if it isn't known how to convert *s* to Unicode + with the *input_charset*. - Characters that could not be converted to Unicode will be replaced with the - Unicode replacement character ``'U+FFFD'``. + Characters that could not be converted to Unicode will be replaced with + the Unicode replacement character ``'U+FFFD'``. -.. method:: Charset.from_splittable(ustr[, to_output]) + .. method:: from_splittable(ustr[, to_output]) - Convert a splittable string back into an encoded string. *ustr* is a Unicode - string to "unsplit". + Convert a splittable string back into an encoded string. *ustr* is a + Unicode string to "unsplit". - This method uses the proper codec to try and convert the string from Unicode - back into an encoded format. Return the string as-is if it is not Unicode, or - if it could not be converted from Unicode. + This method uses the proper codec to try and convert the string from + Unicode back into an encoded format. Return the string as-is if it is not + Unicode, or if it could not be converted from Unicode. - Characters that could not be converted from Unicode will be replaced with an - appropriate character (usually ``'?'``). + Characters that could not be converted from Unicode will be replaced with + an appropriate character (usually ``'?'``). - If *to_output* is ``True`` (the default), uses *output_codec* to convert to an - encoded format. If *to_output* is ``False``, it uses *input_codec*. + If *to_output* is ``True`` (the default), uses *output_codec* to convert + to an encoded format. If *to_output* is ``False``, it uses *input_codec*. -.. method:: Charset.get_output_charset() + .. method:: get_output_charset() - Return the output character set. + Return the output character set. - This is the *output_charset* attribute if that is not ``None``, otherwise it is - *input_charset*. + This is the *output_charset* attribute if that is not ``None``, otherwise + it is *input_charset*. -.. method:: Charset.encoded_header_len() + .. method:: encoded_header_len() - Return the length of the encoded header string, properly calculating for - quoted-printable or base64 encoding. + Return the length of the encoded header string, properly calculating for + quoted-printable or base64 encoding. -.. method:: Charset.header_encode(s[, convert]) + .. method:: header_encode(s[, convert]) - Header-encode the string *s*. + Header-encode the string *s*. - If *convert* is ``True``, the string will be converted from the input charset to - the output charset automatically. This is not useful for multibyte character - sets, which have line length issues (multibyte characters must be split on a - character, not a byte boundary); use the higher-level :class:`Header` class to - deal with these issues (see :mod:`email.header`). *convert* defaults to - ``False``. + If *convert* is ``True``, the string will be converted from the input + charset to the output charset automatically. This is not useful for + multibyte character sets, which have line length issues (multibyte + characters must be split on a character, not a byte boundary); use the + higher-level :class:`Header` class to deal with these issues (see + :mod:`email.header`). *convert* defaults to ``False``. - The type of encoding (base64 or quoted-printable) will be based on the - *header_encoding* attribute. + The type of encoding (base64 or quoted-printable) will be based on the + *header_encoding* attribute. -.. method:: Charset.body_encode(s[, convert]) + .. method:: body_encode(s[, convert]) - Body-encode the string *s*. + Body-encode the string *s*. - If *convert* is ``True`` (the default), the string will be converted from the - input charset to output charset automatically. Unlike :meth:`header_encode`, - there are no issues with byte boundaries and multibyte charsets in email bodies, - so this is usually pretty safe. + If *convert* is ``True`` (the default), the string will be converted from + the input charset to output charset automatically. Unlike + :meth:`header_encode`, there are no issues with byte boundaries and + multibyte charsets in email bodies, so this is usually pretty safe. - The type of encoding (base64 or quoted-printable) will be based on the - *body_encoding* attribute. + The type of encoding (base64 or quoted-printable) will be based on the + *body_encoding* attribute. -The :class:`Charset` class also provides a number of methods to support standard -operations and built-in functions. + The :class:`Charset` class also provides a number of methods to support + standard operations and built-in functions. -.. method:: Charset.__str__() + .. method:: __str__() - Returns *input_charset* as a string coerced to lower case. :meth:`__repr__` is - an alias for :meth:`__str__`. + Returns *input_charset* as a string coerced to lower + case. :meth:`__repr__` is an alias for :meth:`__str__`. -.. method:: Charset.__eq__(other) + .. method:: __eq__(other) - This method allows you to compare two :class:`Charset` instances for equality. + This method allows you to compare two :class:`Charset` instances for + equality. -.. method:: Header.__ne__(other) + .. method:: __ne__(other) - This method allows you to compare two :class:`Charset` instances for inequality. + This method allows you to compare two :class:`Charset` instances for + inequality. The :mod:`email.charset` module also provides the following functions for adding new entries to the global character set, alias, and codec registries: diff --git a/Doc/library/email.generator.rst b/Doc/library/email.generator.rst index 6fc8ebe..4e2ea2f 100644 --- a/Doc/library/email.generator.rst +++ b/Doc/library/email.generator.rst @@ -44,35 +44,34 @@ Here are the public methods of the :class:`Generator` class, imported from the :mod:`email.header.Header` class. Set to zero to disable header wrapping. The default is 78, as recommended (but not required) by :rfc:`2822`. -The other public :class:`Generator` methods are: + The other public :class:`Generator` methods are: -.. method:: Generator.flatten(msg[, unixfrom]) + .. method:: flatten(msg[, unixfrom]) - Print the textual representation of the message object structure rooted at *msg* - to the output file specified when the :class:`Generator` instance was created. - Subparts are visited depth-first and the resulting text will be properly MIME - encoded. + Print the textual representation of the message object structure rooted at + *msg* to the output file specified when the :class:`Generator` instance + was created. Subparts are visited depth-first and the resulting text will + be properly MIME encoded. - Optional *unixfrom* is a flag that forces the printing of the envelope header - delimiter before the first :rfc:`2822` header of the root message object. If - the root object has no envelope header, a standard one is crafted. By default, - this is set to ``False`` to inhibit the printing of the envelope delimiter. + Optional *unixfrom* is a flag that forces the printing of the envelope + header delimiter before the first :rfc:`2822` header of the root message + object. If the root object has no envelope header, a standard one is + crafted. By default, this is set to ``False`` to inhibit the printing of + the envelope delimiter. - Note that for subparts, no envelope header is ever printed. + Note that for subparts, no envelope header is ever printed. + .. method:: clone(fp) -.. method:: Generator.clone(fp) + Return an independent clone of this :class:`Generator` instance with the + exact same options. - Return an independent clone of this :class:`Generator` instance with the exact - same options. + .. method:: write(s) - -.. method:: Generator.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 the :func:`print` function. + 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 the :func:`print` function. As a convenience, see the methods :meth:`Message.as_string` and ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation diff --git a/Doc/library/email.header.rst b/Doc/library/email.header.rst index ecd9f1f..5f37264 100644 --- a/Doc/library/email.header.rst +++ b/Doc/library/email.header.rst @@ -74,65 +74,66 @@ Here is the :class:`Header` class description: and is usually either a space or a hard tab character. This character will be prepended to continuation lines. -Optional *errors* is passed straight through to the :meth:`append` method. + Optional *errors* is passed straight through to the :meth:`append` method. -.. method:: Header.append(s[, charset[, errors]]) + .. method:: append(s[, charset[, errors]]) - Append the string *s* to the MIME header. + Append the string *s* to the MIME header. - Optional *charset*, if given, should be a :class:`Charset` instance (see - :mod:`email.charset`) or the name of a character set, which will be converted to - a :class:`Charset` instance. A value of ``None`` (the default) means that the - *charset* given in the constructor is used. + Optional *charset*, if given, should be a :class:`Charset` instance (see + :mod:`email.charset`) or the name of a character set, which will be + converted to a :class:`Charset` instance. A value of ``None`` (the + default) means that the *charset* given in the constructor is used. - *s* may be an instance of :class:`bytes` or :class:`str`. If it is an instance - of :class:`bytes`, 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 an instance of :class:`bytes` or :class:`str`. If it is an + instance of :class:`bytes`, 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 an instance of :class:`str`, 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 an instance of :class:`str`, 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:`encode` or - :func:`ustr.encode` call, and defaults to "strict". + Optional *errors* is passed through to any :func:`encode` or + :func:`ustr.encode` call, and defaults to "strict". -.. method:: Header.encode([splitchars]) + .. method:: encode([splitchars]) - Encode a message header into an RFC-compliant format, possibly wrapping long - lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings. - Optional *splitchars* is a string containing characters to split long ASCII - lines on, in rough support of :rfc:`2822`'s *highest level syntactic breaks*. - This doesn't affect :rfc:`2047` encoded lines. + Encode a message header into an RFC-compliant format, possibly wrapping + long lines and encapsulating non-ASCII parts in base64 or quoted-printable + encodings. Optional *splitchars* is a string containing characters to + split long ASCII lines on, in rough support of :rfc:`2822`'s *highest + level syntactic breaks*. This doesn't affect :rfc:`2047` encoded lines. -The :class:`Header` class also provides a number of methods to support standard -operators and built-in functions. + The :class:`Header` class also provides a number of methods to support + standard operators and built-in functions. -.. method:: Header.__str__() + .. method:: __str__() - A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. + A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. -.. method:: Header.__unicode__() + .. method:: __unicode__() - A helper for :class:`str`'s :func:`encode` method. Returns the header as a - Unicode string. + A helper for :class:`str`'s :func:`encode` method. Returns the header as + a Unicode string. + .. method:: __eq__(other) -.. method:: Header.__eq__(other) + This method allows you to compare two :class:`Header` instances for + equality. - This method allows you to compare two :class:`Header` instances for equality. + .. method:: __ne__(other) -.. method:: Header.__ne__(other) - - This method allows you to compare two :class:`Header` instances for inequality. + This method allows you to compare two :class:`Header` instances for + inequality. The :mod:`email.header` module also provides the following convenient functions. diff --git a/Doc/library/email.message.rst b/Doc/library/email.message.rst index 2b0df34..5344b45 100644 --- a/Doc/library/email.message.rst +++ b/Doc/library/email.message.rst @@ -36,472 +36,489 @@ Here are the methods of the :class:`Message` class: The constructor takes no arguments. -.. method:: Message.as_string([unixfrom]) + .. method:: as_string([unixfrom]) - Return the entire message flattened as a string. When optional *unixfrom* is - ``True``, the envelope header is included in the returned string. *unixfrom* - defaults to ``False``. + Return the entire message flattened as a string. When optional *unixfrom* + is ``True``, the envelope header is included in the returned string. + *unixfrom* defaults to ``False``. - Note that this method is provided as a convenience and may not always format the - message the way you want. For example, by default it mangles lines that begin - with ``From``. For more flexibility, instantiate a :class:`Generator` instance - and use its :meth:`flatten` method directly. For example:: + Note that this method is provided as a convenience and may not always + format the message the way you want. For example, by default it mangles + lines that begin with ``From``. For more flexibility, instantiate a + :class:`Generator` instance and use its :meth:`flatten` method directly. + For example:: - from cStringIO import StringIO - from email.generator import Generator - fp = StringIO() - g = Generator(fp, mangle_from_=False, maxheaderlen=60) - g.flatten(msg) - text = fp.getvalue() + from cStringIO import StringIO + from email.generator import Generator + fp = StringIO() + g = Generator(fp, mangle_from_=False, maxheaderlen=60) + g.flatten(msg) + text = fp.getvalue() -.. method:: Message.__str__() + .. method:: __str__() - Equivalent to ``as_string(unixfrom=True)``. + Equivalent to ``as_string(unixfrom=True)``. -.. method:: Message.is_multipart() + .. method:: is_multipart() - Return ``True`` if the message's payload is a list of sub-\ :class:`Message` - objects, otherwise return ``False``. When :meth:`is_multipart` returns False, - the payload should be a string object. + Return ``True`` if the message's payload is a list of sub-\ + :class:`Message` objects, otherwise return ``False``. When + :meth:`is_multipart` returns False, the payload should be a string object. -.. method:: Message.set_unixfrom(unixfrom) + .. method:: set_unixfrom(unixfrom) - Set the message's envelope header to *unixfrom*, which should be a string. + Set the message's envelope header to *unixfrom*, which should be a string. -.. method:: Message.get_unixfrom() + .. method:: get_unixfrom() - Return the message's envelope header. Defaults to ``None`` if the envelope - header was never set. + Return the message's envelope header. Defaults to ``None`` if the + envelope header was never set. -.. method:: Message.attach(payload) + .. method:: attach(payload) - Add the given *payload* to the current payload, which must be ``None`` or a list - of :class:`Message` objects before the call. After the call, the payload will - always be a list of :class:`Message` objects. If you want to set the payload to - a scalar object (e.g. a string), use :meth:`set_payload` instead. + Add the given *payload* to the current payload, which must be ``None`` or + a list of :class:`Message` objects before the call. After the call, the + payload will always be a list of :class:`Message` objects. If you want to + set the payload to a scalar object (e.g. a string), use + :meth:`set_payload` instead. -.. method:: Message.get_payload([i[, decode]]) + .. method:: get_payload([i[, decode]]) - Return a reference the current payload, which will be a list of :class:`Message` - objects when :meth:`is_multipart` is ``True``, or a string when - :meth:`is_multipart` is ``False``. If the payload is a list and you mutate the - list object, you modify the message's payload in place. + Return a reference the current payload, which will be a list of + :class:`Message` objects when :meth:`is_multipart` is ``True``, or a + string when :meth:`is_multipart` is ``False``. If the payload is a list + and you mutate the list object, you modify the message's payload in place. - With optional argument *i*, :meth:`get_payload` will return the *i*-th element - of the payload, counting from zero, if :meth:`is_multipart` is ``True``. An - :exc:`IndexError` will be raised if *i* is less than 0 or greater than or equal - to the number of items in the payload. If the payload is a string (i.e. - :meth:`is_multipart` is ``False``) and *i* is given, a :exc:`TypeError` is - raised. + With optional argument *i*, :meth:`get_payload` will return the *i*-th + element of the payload, counting from zero, if :meth:`is_multipart` is + ``True``. An :exc:`IndexError` will be raised if *i* is less than 0 or + greater than or equal to the number of items in the payload. If the + payload is a string (i.e. :meth:`is_multipart` is ``False``) and *i* is + given, a :exc:`TypeError` is raised. - Optional *decode* is a flag indicating whether the payload should be decoded or - not, according to the :mailheader:`Content-Transfer-Encoding` header. When - ``True`` and the message is not a multipart, the payload will be decoded if this - header's value is ``quoted-printable`` or ``base64``. If some other encoding is - used, or :mailheader:`Content-Transfer-Encoding` header is missing, or if the - payload has bogus base64 data, the payload is returned as-is (undecoded). If - the message is a multipart and the *decode* flag is ``True``, then ``None`` is - returned. The default for *decode* is ``False``. + Optional *decode* is a flag indicating whether the payload should be + decoded or not, according to the :mailheader:`Content-Transfer-Encoding` + header. When ``True`` and the message is not a multipart, the payload will + be decoded if this header's value is ``quoted-printable`` or ``base64``. + If some other encoding is used, or :mailheader:`Content-Transfer-Encoding` + header is missing, or if the payload has bogus base64 data, the payload is + returned as-is (undecoded). If the message is a multipart and the + *decode* flag is ``True``, then ``None`` is returned. The default for + *decode* is ``False``. -.. method:: Message.set_payload(payload[, charset]) + .. method:: set_payload(payload[, charset]) - Set the entire message object's payload to *payload*. It is the client's - responsibility to ensure the payload invariants. Optional *charset* sets the - message's default character set; see :meth:`set_charset` for details. + Set the entire message object's payload to *payload*. It is the client's + responsibility to ensure the payload invariants. Optional *charset* sets + the message's default character set; see :meth:`set_charset` for details. + .. method:: set_charset(charset) -.. method:: Message.set_charset(charset) + Set the character set of the payload to *charset*, which can either be a + :class:`Charset` instance (see :mod:`email.charset`), a string naming a + character set, or ``None``. If it is a string, it will be converted to a + :class:`Charset` instance. If *charset* is ``None``, the ``charset`` + parameter will be removed from the :mailheader:`Content-Type` + header. Anything else will generate a :exc:`TypeError`. - Set the character set of the payload to *charset*, which can either be a - :class:`Charset` instance (see :mod:`email.charset`), a string naming a - character set, or ``None``. If it is a string, it will be converted to a - :class:`Charset` instance. If *charset* is ``None``, the ``charset`` parameter - will be removed from the :mailheader:`Content-Type` header. Anything else will - generate a :exc:`TypeError`. + The message will be assumed to be of type :mimetype:`text/\*` encoded with + *charset.input_charset*. It will be converted to *charset.output_charset* + and encoded properly, if needed, when generating the plain text + representation of the message. MIME headers (:mailheader:`MIME-Version`, + :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will + be added as needed. - The message will be assumed to be of type :mimetype:`text/\*` encoded with - *charset.input_charset*. It will be converted to *charset.output_charset* and - encoded properly, if needed, when generating the plain text representation of - the message. MIME headers (:mailheader:`MIME-Version`, - :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will be - added as needed. + .. method:: get_charset() + Return the :class:`Charset` instance associated with the message's + payload. -.. method:: Message.get_charset() + 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. - Return the :class:`Charset` instance associated with the message's payload. + These semantic differences are intentional and are biased toward maximal + convenience. -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. + Note that in all cases, any envelope header present in the message is not + included in the mapping interface. -These semantic differences are intentional and are biased toward maximal -convenience. -Note that in all cases, any envelope header present in the message is not -included in the mapping interface. + .. method:: __len__() + Return the total number of headers, including duplicates. -.. method:: Message.__len__() - Return the total number of headers, including duplicates. + .. 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.:: -.. method:: Message.__contains__(name) + if 'message-id' in myMessage: + print('Message-ID:', myMessage['message-id']) - 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:: __getitem__(name) + Return the value of the named header field. *name* should not include the + colon field separator. If the header is missing, ``None`` is returned; a + :exc:`KeyError` is never raised. -.. method:: Message.__getitem__(name) + 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. - 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. + .. 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. -.. method:: Message.__setitem__(name, val) + Note that this does *not* overwrite or delete any existing header with the same + name. If you want to ensure that the new header is the only one present in the + message with field name *name*, delete the field first, e.g.:: - 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. + del msg['subject'] + msg['subject'] = 'Python roolz!' - Note that this does *not* overwrite or delete any existing header with the same - name. If you want to ensure that the new header is the only one present in the - message with field name *name*, delete the field first, e.g.:: - del msg['subject'] - msg['subject'] = 'Python roolz!' + .. 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. -.. method:: Message.__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. + .. method:: Message.__contains__(name) + Return true if the message contains a header field named *name*, otherwise + return false. -.. method:: Message.__contains__(name) - Return true if the message contains a header field named *name*, otherwise - return false. + .. method:: keys() + Return a list of all the message's header field names. -.. method:: Message.keys() - Return a list of all the message's header field names. + .. method:: values() + Return a list of all the message's field values. -.. method:: Message.values() - Return a list of all the message's field values. + .. method:: items() + Return a list of 2-tuples containing all the message's field headers and + values. -.. method:: Message.items() - Return a list of 2-tuples containing all the message's field headers and values. + .. 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``). -.. method:: Message.get(name[, failobj]) + Here are some additional useful methods: - Return the value of the named header field. This is identical to - :meth:`__getitem__` except that optional *failobj* is returned if the named - header is missing (defaults to ``None``). -Here are some additional useful methods: + .. 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``). -.. method:: Message.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``). + .. 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. -.. method:: Message.add_header(_name, _value, **_params) + 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. - 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. + Here's an example:: - 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. + msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') - Here's an example:: + This will add a header that looks like :: - msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') + Content-Disposition: attachment; filename="bud.gif" - This will add a header that looks like :: - Content-Disposition: attachment; filename="bud.gif" + .. 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. -.. method:: Message.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. + .. 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. -.. method:: Message.get_content_type() + :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`. - 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`. + .. 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`. -.. method:: Message.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`. + .. 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`. -.. method:: Message.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`. + .. 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`. -.. method:: Message.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`. + .. 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. -.. method:: Message.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. + .. 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). -.. method:: Message.get_params([failobj[, header[, unquote]]]) + 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`. - 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`. + .. 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``). -.. method:: Message.get_param(param[, failobj[, header[, unquote]]]) + Optional *header* if given, specifies the message header to use instead of + :mailheader:`Content-Type`. - 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``). + 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``. - Optional *header* if given, specifies the message header to use instead of - :mailheader:`Content-Type`. + 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:: - 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``. + rawparam = msg.get_param('foo') + param = email.Utils.collapse_rfc2231_value(rawparam) - 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:: + 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``. - 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``. + .. 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`. -.. method:: Message.set_param(param, value[, header[, requote[, charset[, language]]]]) + 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``). - 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`. + 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. - 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. + .. 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`. -.. method:: Message.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`. + .. 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. -.. method:: Message.set_type(type[, header][, requote]) + 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). - 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. + 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. - 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. + .. 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`. -.. method:: Message.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`. + .. 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`. -.. method:: Message.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`. + .. 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. -.. method:: Message.set_boundary(boundary) + 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. - Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to - *boundary*. :meth:`set_boundary` will always quote *boundary* if necessary. A - :exc:`HeaderParseError` is raised if the message object has no - :mailheader:`Content-Type` header. - Note that using this method is subtly different than deleting the old - :mailheader:`Content-Type` header and adding a new one with the new boundary via - :meth:`add_header`, because :meth:`set_boundary` preserves the order of the - :mailheader:`Content-Type` header in the list of headers. However, it does *not* - preserve any continuation lines which may have been present in the original - :mailheader:`Content-Type` header. + .. method:: get_content_charset([failobj]) + Return the ``charset`` parameter of the :mailheader:`Content-Type` header, + coerced to lower case. If there is no :mailheader:`Content-Type` header, or if + that header has no ``charset`` parameter, *failobj* is returned. -.. method:: Message.get_content_charset([failobj]) + Note that this method differs from :meth:`get_charset` which returns the + :class:`Charset` instance for the default encoding of the message body. - Return the ``charset`` parameter of the :mailheader:`Content-Type` header, - coerced to lower case. If there is no :mailheader:`Content-Type` header, or if - that header has no ``charset`` parameter, *failobj* is returned. - Note that this method differs from :meth:`get_charset` which returns the - :class:`Charset` instance for the default encoding of the message body. + .. 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. -.. method:: Message.get_charsets([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*. - 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*. + .. 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. -.. method:: Message.walk() + Here's an example that prints the MIME type of every part of a multipart + message structure:: - 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. + >>> for part in msg.walk(): + ... print(part.get_content_type()) + multipart/report + text/plain + message/delivery-status + text/plain + text/plain + message/rfc822 - Here's an example that prints the MIME type of every part of a multipart message - structure:: + :class:`Message` objects can also optionally contain two instance attributes, + which can be used when generating the plain text of a MIME message. - >>> for part in msg.walk(): - ... print(part.get_content_type()) - multipart/report - text/plain - message/delivery-status - text/plain - text/plain - message/rfc822 -:class:`Message` objects can also optionally contain two instance attributes, -which can be used when generating the plain text of a MIME message. + .. 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. -.. data:: preamble + 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. - 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. + Note that if the message object has no preamble, the *preamble* attribute + will be ``None``. - The *preamble* attribute contains this leading extra-armor text for MIME - documents. When the :class:`Parser` discovers some text after the headers but - before the first boundary string, it assigns this text to the message's - *preamble* attribute. When the :class:`Generator` is writing out the plain text - representation of a MIME message, and it finds the message has a *preamble* - attribute, it will write this text in the area between the headers and the first - boundary. See :mod:`email.parser` and :mod:`email.generator` for details. - Note that if the message object has no preamble, the *preamble* attribute will - be ``None``. + .. attribute:: epilogue + The *epilogue* attribute acts the same way as the *preamble* attribute, + except that it contains text that appears between the last boundary and + the end of the message. -.. data:: epilogue + You do not need to set the epilogue to the empty string in order for the + :class:`Generator` to print a newline at the end of the file. - The *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. - You do not need to set the epilogue to the empty string in order for the - :class:`Generator` to print a newline at the end of the file. + .. attribute:: defects - -.. data:: 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. diff --git a/Doc/library/email.parser.rst b/Doc/library/email.parser.rst index 6d623a7..7a00912 100644 --- a/Doc/library/email.parser.rst +++ b/Doc/library/email.parser.rst @@ -65,20 +65,21 @@ Here is the API for the :class:`FeedParser`: defaults to the :class:`email.message.Message` class. -.. method:: FeedParser.feed(data) + .. method:: feed(data) - Feed the :class:`FeedParser` some more data. *data* should be a string - containing one or more lines. The lines can be partial and the - :class:`FeedParser` will stitch such partial lines together properly. The lines - in the string can have any of the common three line endings, carriage return, - newline, or carriage return and newline (they can even be mixed). + Feed the :class:`FeedParser` some more data. *data* should be a string + containing one or more lines. The lines can be partial and the + :class:`FeedParser` will stitch such partial lines together properly. The + lines in the string can have any of the common three line endings, + carriage return, newline, or carriage return and newline (they can even be + mixed). -.. method:: FeedParser.close() + .. method:: close() - Closing a :class:`FeedParser` completes the parsing of all previously fed data, - and returns the root message object. It is undefined what happens if you feed - more data to a closed :class:`FeedParser`. + Closing a :class:`FeedParser` completes the parsing of all previously fed + data, and returns the root message object. It is undefined what happens + if you feed more data to a closed :class:`FeedParser`. Parser class API @@ -111,33 +112,33 @@ class. effectively non-strict. You should simply stop passing a *strict* flag to the :class:`Parser` constructor. -The other public :class:`Parser` methods are: + The other public :class:`Parser` methods are: -.. method:: Parser.parse(fp[, headersonly]) + .. method:: parse(fp[, headersonly]) - Read all the data from the file-like object *fp*, parse the resulting text, and - return the root message object. *fp* must support both the :meth:`readline` and - the :meth:`read` methods on file-like objects. + Read all the data from the file-like object *fp*, parse the resulting + text, and return the root message object. *fp* must support both the + :meth:`readline` and the :meth:`read` methods on file-like objects. - The text contained in *fp* must be formatted as a block of :rfc:`2822` style - headers and header continuation lines, optionally preceded by a envelope - header. The header block is terminated either by the end of the data or by a - blank line. Following the header block is the body of the message (which may - contain MIME-encoded subparts). + The text contained in *fp* must be formatted as a block of :rfc:`2822` + style headers and header continuation lines, optionally preceded by a + envelope header. The header block is terminated either by the end of the + data or by a blank line. Following the header block is the body of the + message (which may contain MIME-encoded subparts). - Optional *headersonly* is as with the :meth:`parse` method. + Optional *headersonly* is as with the :meth:`parse` method. + .. method:: parsestr(text[, headersonly]) -.. method:: Parser.parsestr(text[, headersonly]) + Similar to the :meth:`parse` method, except it takes a string object + instead of a file-like object. Calling this method on a string is exactly + equivalent to wrapping *text* in a :class:`StringIO` instance first and + calling :meth:`parse`. - Similar to the :meth:`parse` method, except it takes a string object instead of - a file-like object. Calling this method on a string is exactly equivalent to - wrapping *text* in a :class:`StringIO` instance first and calling :meth:`parse`. - - Optional *headersonly* is a flag specifying whether to stop parsing after - reading the headers or not. The default is ``False``, meaning it parses the - entire contents of the file. + Optional *headersonly* is a flag specifying whether to stop parsing after + reading the headers or not. The default is ``False``, meaning it parses + the entire contents of the file. Since creating a message object structure from a string or a file object is such diff --git a/Doc/library/filecmp.rst b/Doc/library/filecmp.rst index 141889e..3377d97 100644 --- a/Doc/library/filecmp.rst +++ b/Doc/library/filecmp.rst @@ -66,88 +66,91 @@ The :class:`dircmp` class 'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir, os.pardir]``. -The :class:`dircmp` class provides the following methods: + The :class:`dircmp` class provides the following methods: -.. method:: dircmp.report() + .. method:: report() - Print (to ``sys.stdout``) a comparison between *a* and *b*. + Print (to ``sys.stdout``) a comparison between *a* and *b*. -.. method:: dircmp.report_partial_closure() + .. method:: report_partial_closure() - Print a comparison between *a* and *b* and common immediate subdirectories. + Print a comparison between *a* and *b* and common immediate + subdirectories. -.. method:: dircmp.report_full_closure() + .. method:: report_full_closure() - Print a comparison between *a* and *b* and common subdirectories (recursively). + Print a comparison between *a* and *b* and common subdirectories + (recursively). -The :class:`dircmp` offers a number of interesting attributes that may be used -to get various bits of information about the directory trees being compared. + The :class:`dircmp` offers a number of interesting attributes that may be + used to get various bits of information about the directory trees being + compared. -Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, so -there is no speed penalty if only those attributes which are lightweight to -compute are used. + Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, + so there is no speed penalty if only those attributes which are lightweight + to compute are used. -.. attribute:: dircmp.left_list + .. attribute:: left_list - Files and subdirectories in *a*, filtered by *hide* and *ignore*. + Files and subdirectories in *a*, filtered by *hide* and *ignore*. -.. attribute:: dircmp.right_list + .. attribute:: right_list - Files and subdirectories in *b*, filtered by *hide* and *ignore*. + Files and subdirectories in *b*, filtered by *hide* and *ignore*. -.. attribute:: dircmp.common + .. attribute:: common - Files and subdirectories in both *a* and *b*. + Files and subdirectories in both *a* and *b*. -.. attribute:: dircmp.left_only + .. attribute:: left_only - Files and subdirectories only in *a*. + Files and subdirectories only in *a*. -.. attribute:: dircmp.right_only + .. attribute:: right_only - Files and subdirectories only in *b*. + Files and subdirectories only in *b*. -.. attribute:: dircmp.common_dirs + .. attribute:: common_dirs - Subdirectories in both *a* and *b*. + Subdirectories in both *a* and *b*. -.. attribute:: dircmp.common_files + .. attribute:: common_files - Files in both *a* and *b* + Files in both *a* and *b* -.. attribute:: dircmp.common_funny + .. attribute:: common_funny - Names in both *a* and *b*, such that the type differs between the directories, - or names for which :func:`os.stat` reports an error. + Names in both *a* and *b*, such that the type differs between the + directories, or names for which :func:`os.stat` reports an error. -.. attribute:: dircmp.same_files + .. attribute:: same_files - Files which are identical in both *a* and *b*. + Files which are identical in both *a* and *b*. -.. attribute:: dircmp.diff_files + .. attribute:: diff_files - Files which are in both *a* and *b*, whose contents differ. + Files which are in both *a* and *b*, whose contents differ. -.. attribute:: dircmp.funny_files + .. attribute:: funny_files - Files which are in both *a* and *b*, but could not be compared. + Files which are in both *a* and *b*, but could not be compared. -.. attribute:: dircmp.subdirs + .. attribute:: subdirs - A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. + A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. diff --git a/Doc/library/fractions.rst b/Doc/library/fractions.rst index 299e154..dbbde4a 100644 --- a/Doc/library/fractions.rst +++ b/Doc/library/fractions.rst @@ -30,60 +30,58 @@ Rational 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 ``Rational(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 ``Rational(3, 10)`` -.. method:: Fraction.from_decimal(dec) + .. method:: from_decimal(dec) - This classmethod constructs a :class:`Fraction` representing the - exact value of *dec*, which must be a - :class:`decimal.Decimal`. + This classmethod constructs a :class:`Fraction` representing the exact + value of *dec*, which must be a :class:`decimal.Decimal`. -.. method:: Fraction.limit_denominator(max_denominator=1000000) + .. method:: limit_denominator(max_denominator=1000000) - Finds and returns the closest :class:`Fraction` to ``self`` that - has denominator at most max_denominator. This method is useful for - finding rational approximations to a given floating-point number: + Finds and returns the closest :class:`Fraction` to ``self`` that has + denominator at most max_denominator. This method is useful for finding + rational approximations to a given floating-point number: - >>> from fractions import Fraction - >>> Fraction('3.1415926535897932').limit_denominator(1000) - Fraction(355L, 113L) + >>> from fractions import Fraction + >>> Fraction('3.1415926535897932').limit_denominator(1000) + Fraction(355L, 113L) - or for recovering a rational number that's represented as a float: + or for recovering a rational number that's represented as a float: - >>> from math import pi, cos - >>> Fraction.from_float(cos(pi/3)) - Fraction(4503599627370497L, 9007199254740992L) - >>> Fraction.from_float(cos(pi/3)).limit_denominator() - Fraction(1L, 2L) + >>> from math import pi, cos + >>> Fraction.from_float(cos(pi/3)) + Fraction(4503599627370497L, 9007199254740992L) + >>> Fraction.from_float(cos(pi/3)).limit_denominator() + Fraction(1L, 2L) -.. method:: Fraction.__floor__() + .. method:: __floor__() - Returns the greatest :class:`int` ``<= self``. Will be accessible - through :func:`math.floor` in Py3k. + Returns the greatest :class:`int` ``<= self``. Will be accessible through + :func:`math.floor` in Py3k. -.. method:: Fraction.__ceil__() + .. method:: __ceil__() - Returns the least :class:`int` ``>= self``. Will be accessible - through :func:`math.ceil` in Py3k. + Returns the least :class:`int` ``>= self``. Will be accessible through + :func:`math.ceil` in Py3k. -.. method:: Fraction.__round__() - Fraction.__round__(ndigits) + .. method:: __round__() + __round__(ndigits) - The first version returns the nearest :class:`int` to ``self``, - rounding half to even. The second version rounds ``self`` to the - nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if - ``ndigits`` is negative), again rounding half toward even. Will be - accessible through :func:`round` in Py3k. + The first version returns the nearest :class:`int` to ``self``, rounding + half to even. The second version rounds ``self`` to the nearest multiple + of ``Fraction(1, 10**ndigits)`` (logically, if ``ndigits`` is negative), + again rounding half toward even. Will be accessible through :func:`round` + in Py3k. .. seealso:: diff --git a/Doc/library/ftplib.rst b/Doc/library/ftplib.rst index 9e99190..4ce8893 100644 --- a/Doc/library/ftplib.rst +++ b/Doc/library/ftplib.rst @@ -47,33 +47,34 @@ The module defines the following items: or passed as None, the global default timeout setting will be used). -.. data:: all_errors + .. attribute:: all_errors - The set of all exceptions (as a tuple) that methods of :class:`FTP` instances - may raise as a result of problems with the FTP connection (as opposed to - programming errors made by the caller). This set includes the four exceptions - listed below as well as :exc:`socket.error` and :exc:`IOError`. + The set of all exceptions (as a tuple) that methods of :class:`FTP` + instances may raise as a result of problems with the FTP connection (as + opposed to programming errors made by the caller). This set includes the + four exceptions listed below as well as :exc:`socket.error` and + :exc:`IOError`. -.. exception:: error_reply + .. exception:: error_reply - Exception raised when an unexpected reply is received from the server. + Exception raised when an unexpected reply is received from the server. -.. exception:: error_temp + .. exception:: error_temp - Exception raised when an error code in the range 400--499 is received. + Exception raised when an error code in the range 400--499 is received. -.. exception:: error_perm + .. exception:: error_perm - Exception raised when an error code in the range 500--599 is received. + Exception raised when an error code in the range 500--599 is received. -.. exception:: error_proto + .. exception:: error_proto - Exception raised when a reply is received from the server that does not begin - with a digit in the range 1--5. + Exception raised when a reply is received from the server that does not + begin with a digit in the range 1--5. .. seealso:: diff --git a/Doc/library/gettext.rst b/Doc/library/gettext.rst index da8f4f1..fa1271a 100644 --- a/Doc/library/gettext.rst +++ b/Doc/library/gettext.rst @@ -218,7 +218,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 @@ -227,105 +227,107 @@ are the methods of :class:`NullTranslations`: ``None``. -.. method:: NullTranslations._parse(fp) + .. method:: _parse(fp) - No-op'd in the base class, this method takes file object *fp*, and reads the - data from the file, initializing its message catalog. If you have an - unsupported message catalog file format, you should override this method to - parse your format. + No-op'd in the base class, this method takes file object *fp*, and reads + the data from the file, initializing its message catalog. If you have an + unsupported message catalog file format, you should override this method + to parse your format. -.. method:: NullTranslations.add_fallback(fallback) + .. method:: add_fallback(fallback) - Add *fallback* as the fallback object for the current translation object. A - translation object should consult the fallback if it cannot provide a - translation for a given message. + Add *fallback* as the fallback object for the current translation + object. A translation object should consult the fallback if it cannot provide a + translation for a given message. -.. method:: NullTranslations.gettext(message) + .. method:: gettext(message) - If a fallback has been set, forward :meth:`gettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`gettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. -.. method:: NullTranslations.lgettext(message) + .. method:: lgettext(message) - If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`lgettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. + .. method:: ugettext(message) -.. method:: NullTranslations.ugettext(message) + If a fallback has been set, forward :meth:`ugettext` to the + fallback. Otherwise, return the translated message as a string. Overridden + in derived classes. - If a fallback has been set, forward :meth:`ugettext` to the fallback. Otherwise, - return the translated message as a string. Overridden in derived classes. + .. method:: ngettext(singular, plural, n) -.. method:: NullTranslations.ngettext(singular, plural, n) + If a fallback has been set, forward :meth:`ngettext` to the + fallback. Otherwise, return the translated message. Overridden in derived + classes. - If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + .. 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. -.. method:: NullTranslations.lngettext(singular, plural, n) + .. method:: ungettext(singular, plural, n) - If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, - return the translated message. Overridden in derived classes. + If a fallback has been set, forward :meth:`ungettext` to the fallback. + Otherwise, return the translated message as a string. Overridden in + derived classes. + .. method:: info() -.. method:: NullTranslations.ungettext(singular, plural, n) + Return the "protected" :attr:`_info` variable. - If a fallback has been set, forward :meth:`ungettext` to the fallback. - Otherwise, return the translated message as a string. Overridden in - derived classes. + .. method:: charset() -.. method:: NullTranslations.info() + Return the "protected" :attr:`_charset` variable. - Return the "protected" :attr:`_info` variable. + .. method:: output_charset() -.. method:: NullTranslations.charset() + Return the "protected" :attr:`_output_charset` variable, which defines the + encoding used to return translated messages. - Return the "protected" :attr:`_charset` variable. + .. method:: set_output_charset(charset) -.. method:: NullTranslations.output_charset() + Change the "protected" :attr:`_output_charset` variable, which defines the + encoding used to return translated messages. - Return the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + .. method:: install([unicode [, names]]) -.. method:: NullTranslations.set_output_charset(charset) + 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. - Change the "protected" :attr:`_output_charset` variable, which defines the - encoding used to return translated messages. + 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:: -.. method:: NullTranslations.install([unicode [, names]]) + import gettext + t = gettext.translation('mymodule', ...) + _ = t.gettext - 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'``. - - 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. The :class:`GNUTranslations` class diff --git a/Doc/library/logging.rst b/Doc/library/logging.rst index d109ea1..bbedab6 100644 --- a/Doc/library/logging.rst +++ b/Doc/library/logging.rst @@ -1491,19 +1491,19 @@ and :meth:`flush` methods). will be used. -.. method:: StreamHandler.emit(record) + .. method:: emit(record) - If a formatter is specified, it is used to format the record. The record is then - written to the stream with a trailing newline. If exception information is - present, it is formatted using :func:`traceback.print_exception` and appended to - the stream. + If a formatter is specified, it is used to format the record. The record + is then written to the stream with a trailing newline. If exception + information is present, it is formatted using + :func:`traceback.print_exception` and appended to the stream. -.. method:: StreamHandler.flush() + .. method:: flush() - Flushes the stream by calling its :meth:`flush` method. Note that the - :meth:`close` method is inherited from :class:`Handler` and so does nothing, so - an explicit :meth:`flush` call may be needed at times. + Flushes the stream by calling its :meth:`flush` method. Note that the + :meth:`close` method is inherited from :class:`Handler` and so does + nothing, so an explicit :meth:`flush` call may be needed at times. FileHandler @@ -1523,14 +1523,14 @@ sends logging output to a disk file. It inherits the output functionality from first call to :meth:`emit`. By default, the file grows indefinitely. -.. method:: FileHandler.close() + .. method:: close() - Closes the file. + Closes the file. -.. method:: FileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file. + Outputs the record to the file. WatchedFileHandler @@ -1563,11 +1563,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 @@ -1599,14 +1599,15 @@ module, supports rotation of disk log files. :file:`app.log.2`, :file:`app.log.3` etc. respectively. -.. method:: RotatingFileHandler.doRollover() + .. method:: doRollover() - Does a rollover, as described above. + Does a rollover, as described above. -.. method:: RotatingFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, catering for rollover as described previously. + Outputs the record to the file, catering for rollover as described + previously. TimedRotatingFileHandler @@ -1652,14 +1653,14 @@ timed intervals. files to delete, so changing the interval may leave old files lying around. -.. method:: TimedRotatingFileHandler.doRollover() + .. method:: doRollover() - Does a rollover, as described above. + Does a rollover, as described above. -.. method:: TimedRotatingFileHandler.emit(record) + .. method:: emit(record) - Outputs the record to the file, catering for rollover as described above. + Outputs the record to the file, catering for rollover as described above. SocketHandler @@ -1675,43 +1676,44 @@ sends logging output to a network socket. The base class uses a TCP socket. communicate with a remote machine whose address is given by *host* and *port*. -.. method:: SocketHandler.close() + .. method:: close() - Closes the socket. + Closes the socket. -.. method:: SocketHandler.emit() + .. method:: emit() - Pickles the record's attribute dictionary and writes it to the socket in binary - format. If there is an error with the socket, silently drops the packet. If the - connection was previously lost, re-establishes the connection. To unpickle the - record at the receiving end into a :class:`LogRecord`, use the - :func:`makeLogRecord` function. + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. If the connection was previously lost, re-establishes the + connection. To unpickle the record at the receiving end into a + :class:`LogRecord`, use the :func:`makeLogRecord` function. -.. method:: SocketHandler.handleError() + .. method:: handleError() - Handles an error which has occurred during :meth:`emit`. The most likely cause - is a lost connection. Closes the socket so that we can retry on the next event. + Handles an error which has occurred during :meth:`emit`. The most likely + cause is a lost connection. Closes the socket so that we can retry on the + next event. -.. method:: SocketHandler.makeSocket() + .. method:: makeSocket() - This is a factory method which allows subclasses to define the precise type of - socket they want. The default implementation creates a TCP socket - (:const:`socket.SOCK_STREAM`). + This is a factory method which allows subclasses to define the precise + type of socket they want. The default implementation creates a TCP socket + (:const:`socket.SOCK_STREAM`). -.. method:: SocketHandler.makePickle(record) + .. method:: makePickle(record) - Pickles the record's attribute dictionary in binary format with a length prefix, - and returns it ready for transmission across the socket. + Pickles the record's attribute dictionary in binary format with a length + prefix, and returns it ready for transmission across the socket. -.. method:: SocketHandler.send(packet) + .. method:: send(packet) - Send a pickled string *packet* to the socket. This function allows for partial - sends which can happen when the network is busy. + Send a pickled string *packet* to the socket. This function allows for + partial sends which can happen when the network is busy. DatagramHandler @@ -1728,23 +1730,23 @@ over UDP sockets. communicate with a remote machine whose address is given by *host* and *port*. -.. method:: DatagramHandler.emit() + .. method:: emit() - Pickles the record's attribute dictionary and writes it to the socket in binary - format. If there is an error with the socket, silently drops the packet. To - unpickle the record at the receiving end into a :class:`LogRecord`, use the - :func:`makeLogRecord` function. + Pickles the record's attribute dictionary and writes it to the socket in + binary format. If there is an error with the socket, silently drops the + packet. To unpickle the record at the receiving end into a + :class:`LogRecord`, use the :func:`makeLogRecord` function. -.. method:: DatagramHandler.makeSocket() + .. method:: makeSocket() - The factory method of :class:`SocketHandler` is here overridden to create a UDP - socket (:const:`socket.SOCK_DGRAM`). + The factory method of :class:`SocketHandler` is here overridden to create + a UDP socket (:const:`socket.SOCK_DGRAM`). -.. method:: DatagramHandler.send(s) + .. method:: send(s) - Send a pickled string to a socket. + Send a pickled string to a socket. SysLogHandler @@ -1766,22 +1768,22 @@ supports sending logging messages to a remote or local Unix syslog. :const:`LOG_USER` is used. -.. method:: SysLogHandler.close() + .. method:: close() - Closes the socket to the remote host. + Closes the socket to the remote host. -.. method:: SysLogHandler.emit(record) + .. method:: emit(record) - The record is formatted, and then sent to the syslog server. If exception - information is present, it is *not* sent to the server. + The record is formatted, and then sent to the syslog server. If exception + information is present, it is *not* sent to the server. -.. method:: SysLogHandler.encodePriority(facility, priority) + .. method:: encodePriority(facility, priority) - Encodes the facility and priority into an integer. You can pass in strings or - integers - if strings are passed, internal mapping dictionaries are used to - convert them to integers. + Encodes the facility and priority into an integer. You can pass in strings + or integers - if strings are passed, internal mapping dictionaries are + used to convert them to integers. NTEventLogHandler @@ -1809,45 +1811,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 @@ -1867,15 +1869,15 @@ supports sending logging messages to an email address via SMTP. can specify a (username, password) tuple for the *credentials* argument. -.. method:: SMTPHandler.emit(record) + .. method:: emit(record) - Formats the record and sends it to the specified addressees. + Formats the record and sends it to the specified addressees. -.. method:: SMTPHandler.getSubject(record) + .. method:: getSubject(record) - If you want to specify a subject line which is record-dependent, override this - method. + If you want to specify a subject line which is record-dependent, override + this method. MemoryHandler @@ -1898,22 +1900,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]]) @@ -1924,25 +1926,27 @@ should, then :meth:`flush` is expected to do the needful. set using :meth:`setTarget` before this handler does anything useful. -.. method:: MemoryHandler.close() + .. method:: close() - Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer. + Calls :meth:`flush`, sets the target to :const:`None` and clears the + buffer. -.. method:: MemoryHandler.flush() + .. method:: flush() - For a :class:`MemoryHandler`, flushing means just sending the buffered records - to the target, if there is one. Override if you want different behavior. + For a :class:`MemoryHandler`, flushing means just sending the buffered + records to the target, if there is one. Override if you want different + behavior. -.. method:: MemoryHandler.setTarget(target) + .. method:: setTarget(target) - Sets the target handler for this handler. + Sets the target handler for this handler. -.. method:: MemoryHandler.shouldFlush(record) + .. method:: shouldFlush(record) - Checks for buffer full or a record at the *flushLevel* or higher. + Checks for buffer full or a record at the *flushLevel* or higher. HTTPHandler @@ -1961,9 +1965,9 @@ supports sending logging messages to a Web server, using either ``GET`` or *method* is specified, ``GET`` is used. -.. method:: HTTPHandler.emit(record) + .. method:: emit(record) - Sends the record to the Web server as an URL-encoded dictionary. + Sends the record to the Web server as an URL-encoded dictionary. .. _formatter-objects: @@ -2048,38 +2052,42 @@ Currently, the useful mapping keys in a :class:`LogRecord` are: is used. -.. method:: Formatter.format(record) + .. method:: format(record) - The record's attribute dictionary is used as the operand to a string formatting - operation. Returns the resulting string. Before formatting the dictionary, a - couple of preparatory steps are carried out. The *message* attribute of the - record is computed using *msg* % *args*. If the formatting string contains - ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there - is exception information, it is formatted using :meth:`formatException` and - appended to the message. Note that the formatted exception information is cached - in attribute *exc_text*. This is useful because the exception information can - be pickled and sent across the wire, but you should be careful if you have more - than one :class:`Formatter` subclass which customizes the formatting of exception - information. In this case, you will have to clear the cached value after a - formatter has done its formatting, so that the next formatter to handle the event - doesn't use the cached value but recalculates it afresh. + The record's attribute dictionary is used as the operand to a string + formatting operation. Returns the resulting string. Before formatting the + dictionary, a couple of preparatory steps are carried out. The *message* + attribute of the record is computed using *msg* % *args*. If the + formatting string contains ``'(asctime)'``, :meth:`formatTime` is called + to format the event time. If there is exception information, it is + formatted using :meth:`formatException` and appended to the message. Note + that the formatted exception information is cached in attribute + *exc_text*. This is useful because the exception information can be + pickled and sent across the wire, but you should be careful if you have + more than one :class:`Formatter` subclass which customizes the formatting + of exception information. In this case, you will have to clear the cached + value after a formatter has done its formatting, so that the next + formatter to handle the event doesn't use the cached value but + recalculates it afresh. -.. method:: Formatter.formatTime(record[, datefmt]) + .. method:: formatTime(record[, datefmt]) - This method should be called from :meth:`format` by a formatter which wants to - make use of a formatted time. This method can be overridden in formatters to - provide for any specific requirement, but the basic behavior is as follows: if - *datefmt* (a string) is specified, it is used with :func:`time.strftime` to - format the creation time of the record. Otherwise, the ISO8601 format is used. - The resulting string is returned. + This method should be called from :meth:`format` by a formatter which + wants to make use of a formatted time. This method can be overridden in + formatters to provide for any specific requirement, but the basic behavior + is as follows: if *datefmt* (a string) is specified, it is used with + :func:`time.strftime` to format the creation time of the + record. Otherwise, the ISO8601 format is used. The resulting string is + returned. -.. method:: Formatter.formatException(exc_info) + .. method:: formatException(exc_info) - Formats the specified exception information (a standard exception tuple as - returned by :func:`sys.exc_info`) as a string. This default implementation just - uses :func:`traceback.print_exception`. The resulting string is returned. + Formats the specified exception information (a standard exception tuple as + returned by :func:`sys.exc_info`) as a string. This default implementation + just uses :func:`traceback.print_exception`. The resulting string is + returned. Filter Objects @@ -2100,10 +2108,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 @@ -2131,10 +2140,11 @@ made, and any exception information to be logged. specified, it defaults to ``None``. -.. method:: LogRecord.getMessage() + .. method:: getMessage() + + Returns the message for this :class:`LogRecord` instance after merging any + user-supplied arguments with the message. - Returns the message for this :class:`LogRecord` instance after merging any - user-supplied arguments with the message. LoggerAdapter Objects --------------------- @@ -2150,13 +2160,13 @@ __ context-info_ Returns an instance of :class:`LoggerAdapter` initialized with an underlying :class:`Logger` instance and a dict-like object. -.. method:: LoggerAdapter.process(msg, kwargs) + .. method:: process(msg, kwargs) - Modifies the message and/or keyword arguments passed to a logging call in - order to insert contextual information. This implementation takes the - object passed as *extra* to the constructor and adds it to *kwargs* using - key 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the - (possibly modified) versions of the arguments passed in. + Modifies the message and/or keyword arguments passed to a logging call in + order to insert contextual information. This implementation takes the object + passed as *extra* to the constructor and adds it to *kwargs* using key + 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the + (possibly modified) versions of the arguments passed in. In addition to the above, :class:`LoggerAdapter` supports all the logging methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`, diff --git a/Doc/library/mailbox.rst b/Doc/library/mailbox.rst index b5773f4..f76c97a 100644 --- a/Doc/library/mailbox.rst +++ b/Doc/library/mailbox.rst @@ -32,237 +32,243 @@ Maildir, mbox, MH, Babyl, and MMDF. A mailbox, which may be inspected and modified. -The :class:`Mailbox` class defines an interface and is not intended to be -instantiated. Instead, format-specific subclasses should inherit from -:class:`Mailbox` and your code should instantiate a particular subclass. + The :class:`Mailbox` class defines an interface and is not intended to be + instantiated. Instead, format-specific subclasses should inherit from + :class:`Mailbox` and your code should instantiate a particular subclass. + + The :class:`Mailbox` interface is dictionary-like, with small keys + corresponding to messages. Keys are issued by the :class:`Mailbox` instance + with which they will be used and are only meaningful to that :class:`Mailbox` + instance. A key continues to identify a message even if the corresponding + message is modified, such as by replacing it with another message. + + Messages may be added to a :class:`Mailbox` instance using the set-like + method :meth:`add` and removed using a ``del`` statement or the set-like + methods :meth:`remove` and :meth:`discard`. + + :class:`Mailbox` interface semantics differ from dictionary semantics in some + noteworthy ways. Each time a message is requested, a new representation + (typically a :class:`Message` instance) is generated based upon the current + state of the mailbox. Similarly, when a message is added to a + :class:`Mailbox` instance, the provided message representation's contents are + copied. In neither case is a reference to the message representation kept by + the :class:`Mailbox` instance. + + The default :class:`Mailbox` iterator iterates over message representations, + not keys as the default dictionary iterator does. Moreover, modification of a + mailbox during iteration is safe and well-defined. Messages added to the + mailbox after an iterator is created will not be seen by the + iterator. Messages removed from the mailbox before the iterator yields them + will be silently skipped, though using a key from an iterator may result in a + :exc:`KeyError` exception if the corresponding message is subsequently + removed. -The :class:`Mailbox` interface is dictionary-like, with small keys corresponding -to messages. Keys are issued by the :class:`Mailbox` instance with which they -will be used and are only meaningful to that :class:`Mailbox` instance. A key -continues to identify a message even if the corresponding message is modified, -such as by replacing it with another message. - -Messages may be added to a :class:`Mailbox` instance using the set-like method -:meth:`add` and removed using a ``del`` statement or the set-like methods -:meth:`remove` and :meth:`discard`. - -:class:`Mailbox` interface semantics differ from dictionary semantics in some -noteworthy ways. Each time a message is requested, a new representation -(typically a :class:`Message` instance) is generated based upon the current -state of the mailbox. Similarly, when a message is added to a :class:`Mailbox` -instance, the provided message representation's contents are copied. In neither -case is a reference to the message representation kept by the :class:`Mailbox` -instance. + .. warning:: -The default :class:`Mailbox` iterator iterates over message representations, not -keys as the default dictionary iterator does. Moreover, modification of a -mailbox during iteration is safe and well-defined. Messages added to the mailbox -after an iterator is created will not be seen by the iterator. Messages removed -from the mailbox before the iterator yields them will be silently skipped, -though using a key from an iterator may result in a :exc:`KeyError` exception if -the corresponding message is subsequently removed. + Be very cautious when modifying mailboxes that might be simultaneously + changed by some other process. The safest mailbox format to use for such + tasks is Maildir; try to avoid using single-file formats such as mbox for + concurrent writing. If you're modifying a mailbox, you *must* lock it by + calling the :meth:`lock` and :meth:`unlock` methods *before* reading any + messages in the file or making any changes by adding or deleting a + message. Failing to lock the mailbox runs the risk of losing messages or + corrupting the entire mailbox. -.. warning:: + :class:`Mailbox` instances have the following methods: - Be very cautious when modifying mailboxes that might be simultaneously changed - by some other process. The safest mailbox format to use for such tasks is - Maildir; try to avoid using single-file formats such as mbox for concurrent - writing. If you're modifying a mailbox, you *must* lock it by calling the - :meth:`lock` and :meth:`unlock` methods *before* reading any messages in the - file or making any changes by adding or deleting a message. Failing to lock the - mailbox runs the risk of losing messages or corrupting the entire mailbox. -:class:`Mailbox` instances have the following methods: + .. method:: add(message) + Add *message* to the mailbox and return the key that has been assigned to + it. -.. method:: Mailbox.add(message) + Parameter *message* may be a :class:`Message` instance, an + :class:`email.Message.Message` instance, a string, or a file-like object + (which should be open in text mode). If *message* is an instance of the + appropriate format-specific :class:`Message` subclass (e.g., if it's an + :class:`mboxMessage` instance and this is an :class:`mbox` instance), its + format-specific information is used. Otherwise, reasonable defaults for + format-specific information are used. - Add *message* to the mailbox and return the key that has been assigned to it. - Parameter *message* may be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). If *message* is an instance of the appropriate - format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` - instance and this is an :class:`mbox` instance), its format-specific information - is used. Otherwise, reasonable defaults for format-specific information are - used. + .. method:: remove(key) + __delitem__(key) + discard(key) + Delete the message corresponding to *key* from the mailbox. -.. method:: Mailbox.remove(key) - Mailbox.__delitem__(key) - Mailbox.discard(key) + If no such message exists, a :exc:`KeyError` exception is raised if the + method was called as :meth:`remove` or :meth:`__delitem__` but no + exception is raised if the method was called as :meth:`discard`. The + behavior of :meth:`discard` may be preferred if the underlying mailbox + format supports concurrent modification by other processes. - Delete the message corresponding to *key* from the mailbox. - If no such message exists, a :exc:`KeyError` exception is raised if the method - was called as :meth:`remove` or :meth:`__delitem__` but no exception is raised - if the method was called as :meth:`discard`. The behavior of :meth:`discard` may - be preferred if the underlying mailbox format supports concurrent modification - by other processes. + .. method:: __setitem__(key, message) + Replace the message corresponding to *key* with *message*. Raise a + :exc:`KeyError` exception if no message already corresponds to *key*. -.. method:: Mailbox.__setitem__(key, message) + As with :meth:`add`, parameter *message* may be a :class:`Message` + instance, an :class:`email.Message.Message` instance, a string, or a + file-like object (which should be open in text mode). If *message* is an + instance of the appropriate format-specific :class:`Message` subclass + (e.g., if it's an :class:`mboxMessage` instance and this is an + :class:`mbox` instance), its format-specific information is + used. Otherwise, the format-specific information of the message that + currently corresponds to *key* is left unchanged. - Replace the message corresponding to *key* with *message*. Raise a - :exc:`KeyError` exception if no message already corresponds to *key*. - As with :meth:`add`, parameter *message* may be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). If *message* is an instance of the appropriate - format-specific :class:`Message` subclass (e.g., if it's an :class:`mboxMessage` - instance and this is an :class:`mbox` instance), its format-specific information - is used. Otherwise, the format-specific information of the message that - currently corresponds to *key* is left unchanged. + .. method:: iterkeys() + keys() + Return an iterator over all keys if called as :meth:`iterkeys` or return a + list of keys if called as :meth:`keys`. -.. method:: Mailbox.iterkeys() - Mailbox.keys() - Return an iterator over all keys if called as :meth:`iterkeys` or return a list - of keys if called as :meth:`keys`. + .. method:: itervalues() + __iter__() + values() + Return an iterator over representations of all messages if called as + :meth:`itervalues` or :meth:`__iter__` or return a list of such + representations if called as :meth:`values`. The messages are represented + as instances of the appropriate format-specific :class:`Message` subclass + unless a custom message factory was specified when the :class:`Mailbox` + instance was initialized. -.. method:: Mailbox.itervalues() - Mailbox.__iter__() - Mailbox.values() + .. note:: - Return an iterator over representations of all messages if called as - :meth:`itervalues` or :meth:`__iter__` or return a list of such representations - if called as :meth:`values`. The messages are represented as instances of the - appropriate format-specific :class:`Message` subclass unless a custom message - factory was specified when the :class:`Mailbox` instance was initialized. + The behavior of :meth:`__iter__` is unlike that of dictionaries, which + iterate over keys. - .. note:: - The behavior of :meth:`__iter__` is unlike that of dictionaries, which iterate - over keys. + .. method:: iteritems() + items() + Return an iterator over (*key*, *message*) pairs, where *key* is a key and + *message* is a message representation, if called as :meth:`iteritems` or + return a list of such pairs if called as :meth:`items`. The messages are + represented as instances of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.iteritems() - Mailbox.items() - Return an iterator over (*key*, *message*) pairs, where *key* is a key and - *message* is a message representation, if called as :meth:`iteritems` or return - a list of such pairs if called as :meth:`items`. The messages are represented as - instances of the appropriate format-specific :class:`Message` subclass unless a - custom message factory was specified when the :class:`Mailbox` instance was - initialized. + .. method:: get(key[, default=None]) + __getitem__(key) + Return a representation of the message corresponding to *key*. If no such + message exists, *default* is returned if the method was called as + :meth:`get` and a :exc:`KeyError` exception is raised if the method was + called as :meth:`__getitem__`. The message is represented as an instance + of the appropriate format-specific :class:`Message` subclass unless a + custom message factory was specified when the :class:`Mailbox` instance + was initialized. -.. method:: Mailbox.get(key[, default=None]) - Mailbox.__getitem__(key) - Return a representation of the message corresponding to *key*. If no such - message exists, *default* is returned if the method was called as :meth:`get` - and a :exc:`KeyError` exception is raised if the method was called as - :meth:`__getitem__`. The message is represented as an instance of the - appropriate format-specific :class:`Message` subclass unless a custom message - factory was specified when the :class:`Mailbox` instance was initialized. + .. method:: get_message(key) + Return a representation of the message corresponding to *key* as an + instance of the appropriate format-specific :class:`Message` subclass, or + raise a :exc:`KeyError` exception if no such message exists. -.. method:: Mailbox.get_message(key) - Return a representation of the message corresponding to *key* as an instance of - the appropriate format-specific :class:`Message` subclass, or raise a - :exc:`KeyError` exception if no such message exists. + .. method:: get_string(key) + Return a string representation of the message corresponding to *key*, or + raise a :exc:`KeyError` exception if no such message exists. -.. method:: Mailbox.get_string(key) - Return a string representation of the message corresponding to *key*, or raise a - :exc:`KeyError` exception if no such message exists. + .. method:: get_file(key) + Return a file-like representation of the message corresponding to *key*, + or raise a :exc:`KeyError` exception if no such message exists. The + file-like object behaves as if open in binary mode. This file should be + closed once it is no longer needed. -.. method:: Mailbox.get_file(key) + .. note:: - Return a file-like representation of the message corresponding to *key*, or - raise a :exc:`KeyError` exception if no such message exists. The file-like - object behaves as if open in binary mode. This file should be closed once it is - no longer needed. + Unlike other representations of messages, file-like representations are + not necessarily independent of the :class:`Mailbox` instance that + created them or of the underlying mailbox. More specific documentation + is provided by each subclass. - .. note:: - Unlike other representations of messages, file-like representations are not - necessarily independent of the :class:`Mailbox` instance that created them or of - the underlying mailbox. More specific documentation is provided by each - subclass. + .. method:: __contains__(key) + Return ``True`` if *key* corresponds to a message, ``False`` otherwise. -.. method:: Mailbox.__contains__(key) - Return ``True`` if *key* corresponds to a message, ``False`` otherwise. + .. method:: __len__() + Return a count of messages in the mailbox. -.. method:: Mailbox.__len__() - Return a count of messages in the mailbox. + .. method:: clear() + Delete all messages from the mailbox. -.. method:: Mailbox.clear() - Delete all messages from the mailbox. + .. method:: pop(key[, default]) + Return a representation of the message corresponding to *key* and delete + the message. If no such message exists, return *default* if it was + supplied or else raise a :exc:`KeyError` exception. The message is + represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.pop(key[, default]) - Return a representation of the message corresponding to *key* and delete the - message. If no such message exists, return *default* if it was supplied or else - raise a :exc:`KeyError` exception. The message is represented as an instance of - the appropriate format-specific :class:`Message` subclass unless a custom - message factory was specified when the :class:`Mailbox` instance was - initialized. + .. method:: popitem() + Return an arbitrary (*key*, *message*) pair, where *key* is a key and + *message* is a message representation, and delete the corresponding + message. If the mailbox is empty, raise a :exc:`KeyError` exception. The + message is represented as an instance of the appropriate format-specific + :class:`Message` subclass unless a custom message factory was specified + when the :class:`Mailbox` instance was initialized. -.. method:: Mailbox.popitem() - Return an arbitrary (*key*, *message*) pair, where *key* is a key and *message* - is a message representation, and delete the corresponding message. If the - mailbox is empty, raise a :exc:`KeyError` exception. The message is represented - as an instance of the appropriate format-specific :class:`Message` subclass - unless a custom message factory was specified when the :class:`Mailbox` instance - was initialized. + .. method:: update(arg) + Parameter *arg* should be a *key*-to-*message* mapping or an iterable of + (*key*, *message*) pairs. Updates the mailbox so that, for each given + *key* and *message*, the message corresponding to *key* is set to + *message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`, + each *key* must already correspond to a message in the mailbox or else a + :exc:`KeyError` exception will be raised, so in general it is incorrect + for *arg* to be a :class:`Mailbox` instance. -.. method:: Mailbox.update(arg) + .. note:: - Parameter *arg* should be a *key*-to-*message* mapping or an iterable of (*key*, - *message*) pairs. Updates the mailbox so that, for each given *key* and - *message*, the message corresponding to *key* is set to *message* as if by using - :meth:`__setitem__`. As with :meth:`__setitem__`, each *key* must already - correspond to a message in the mailbox or else a :exc:`KeyError` exception will - be raised, so in general it is incorrect for *arg* to be a :class:`Mailbox` - instance. + Unlike with dictionaries, keyword arguments are not supported. - .. note:: - Unlike with dictionaries, keyword arguments are not supported. + .. method:: flush() + Write any pending changes to the filesystem. For some :class:`Mailbox` + subclasses, changes are always written immediately and :meth:`flush` does + nothing, but you should still make a habit of calling this method. -.. method:: Mailbox.flush() - Write any pending changes to the filesystem. For some :class:`Mailbox` - subclasses, changes are always written immediately and :meth:`flush` does - nothing, but you should still make a habit of calling this method. + .. method:: lock() + Acquire an exclusive advisory lock on the mailbox so that other processes + know not to modify it. An :exc:`ExternalClashError` is raised if the lock + is not available. The particular locking mechanisms used depend upon the + mailbox format. You should *always* lock the mailbox before making any + modifications to its contents. -.. method:: Mailbox.lock() - Acquire an exclusive advisory lock on the mailbox so that other processes know - not to modify it. An :exc:`ExternalClashError` is raised if the lock is not - available. The particular locking mechanisms used depend upon the mailbox - format. You should *always* lock the mailbox before making any modifications - to its contents. + .. method:: unlock() + Release the lock on the mailbox, if any. -.. method:: Mailbox.unlock() - Release the lock on the mailbox, if any. + .. method:: close() - -.. method:: Mailbox.close() - - Flush the mailbox, unlock it if necessary, and close any open files. For some - :class:`Mailbox` subclasses, this method does nothing. + Flush the mailbox, unlock it if necessary, and close any open files. For + some :class:`Mailbox` subclasses, this method does nothing. .. _mailbox-maildir: @@ -285,113 +291,115 @@ the corresponding message is subsequently removed. instance that behaves like instances of other :class:`Mailbox` subclasses, set *factory* to ``None``. -Maildir is a directory-based mailbox format invented for the qmail mail transfer -agent and now widely supported by other programs. Messages in a Maildir mailbox -are stored in separate files within a common directory structure. This design -allows Maildir mailboxes to be accessed and modified by multiple unrelated -programs without data corruption, so file locking is unnecessary. + Maildir is a directory-based mailbox format invented for the qmail mail + transfer agent and now widely supported by other programs. Messages in a + Maildir mailbox are stored in separate files within a common directory + structure. This design allows Maildir mailboxes to be accessed and modified + by multiple unrelated programs without data corruption, so file locking is + unnecessary. + + Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, + :file:`new`, and :file:`cur`. Messages are created momentarily in the + :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to + finalize delivery. A mail user agent may subsequently move the message to the + :file:`cur` subdirectory and store information about the state of the message + in a special "info" section appended to its file name. + + Folders of the style introduced by the Courier mail transfer agent are also + supported. Any subdirectory of the main mailbox is considered a folder if + ``'.'`` is the first character in its name. Folder names are represented by + :class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir + mailbox but should not contain other folders. Instead, a logical nesting is + indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". -Maildir mailboxes contain three subdirectories, namely: :file:`tmp`, -:file:`new`, and :file:`cur`. Messages are created momentarily in the -:file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to -finalize delivery. A mail user agent may subsequently move the message to the -:file:`cur` subdirectory and store information about the state of the message in -a special "info" section appended to its file name. + .. note:: -Folders of the style introduced by the Courier mail transfer agent are also -supported. Any subdirectory of the main mailbox is considered a folder if -``'.'`` is the first character in its name. Folder names are represented by -:class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir -mailbox but should not contain other folders. Instead, a logical nesting is -indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07". + The Maildir specification requires the use of a colon (``':'``) in certain + message file names. However, some operating systems do not permit this + character in file names, If you wish to use a Maildir-like format on such + an operating system, you should specify another character to use + instead. The exclamation point (``'!'``) is a popular choice. For + example:: -.. note:: + import mailbox + mailbox.Maildir.colon = '!' - The Maildir specification requires the use of a colon (``':'``) in certain - message file names. However, some operating systems do not permit this character - in file names, If you wish to use a Maildir-like format on such an operating - system, you should specify another character to use instead. The exclamation - point (``'!'``) is a popular choice. For example:: + The :attr:`colon` attribute may also be set on a per-instance basis. - import mailbox - mailbox.Maildir.colon = '!' + :class:`Maildir` instances have all of the methods of :class:`Mailbox` in + addition to the following: - The :attr:`colon` attribute may also be set on a per-instance basis. -:class:`Maildir` instances have all of the methods of :class:`Mailbox` in -addition to the following: + .. method:: list_folders() + Return a list of the names of all folders. -.. method:: Maildir.list_folders() - Return a list of the names of all folders. + .. method:: .et_folder(folder) + Return a :class:`Maildir` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. -.. method:: Maildir.get_folder(folder) - Return a :class:`Maildir` instance representing the folder whose name is - *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder does not - exist. + .. method:: add_folder(folder) + Create a folder whose name is *folder* and return a :class:`Maildir` + instance representing it. -.. method:: Maildir.add_folder(folder) - Create a folder whose name is *folder* and return a :class:`Maildir` instance - representing it. + .. method:: remove_folder(folder) + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. -.. method:: Maildir.remove_folder(folder) - Delete the folder whose name is *folder*. If the folder contains any messages, a - :exc:`NotEmptyError` exception will be raised and the folder will not be - deleted. + .. method:: clean() + Delete temporary files from the mailbox that have not been accessed in the + last 36 hours. The Maildir specification says that mail-reading programs + should do this occasionally. -.. method:: Maildir.clean() + Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special + remarks: - Delete temporary files from the mailbox that have not been accessed in the last - 36 hours. The Maildir specification says that mail-reading programs should do - this occasionally. -Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special -remarks: + .. method:: add(message) + __setitem__(key, message) + update(arg) + .. warning:: -.. method:: Maildir.add(message) - Maildir.__setitem__(key, message) - Maildir.update(arg) + These methods generate unique file names based upon the current process + ID. When using multiple threads, undetected name clashes may occur and + cause corruption of the mailbox unless threads are coordinated to avoid + using these methods to manipulate the same mailbox simultaneously. - .. warning:: - These methods generate unique file names based upon the current process ID. When - using multiple threads, undetected name clashes may occur and cause corruption - of the mailbox unless threads are coordinated to avoid using these methods to - manipulate the same mailbox simultaneously. + .. method:: flush() + All changes to Maildir mailboxes are immediately applied, so this method + does nothing. -.. method:: Maildir.flush() - All changes to Maildir mailboxes are immediately applied, so this method does - nothing. + .. method:: lock() + unlock() + Maildir mailboxes do not support (or require) locking, so these methods do + nothing. -.. method:: Maildir.lock() - Maildir.unlock() - Maildir mailboxes do not support (or require) locking, so these methods do - nothing. + .. method:: close() + :class:`Maildir` instances do not keep any open files and the underlying + mailboxes do not support locking, so this method does nothing. -.. method:: Maildir.close() - :class:`Maildir` instances do not keep any open files and the underlying - mailboxes do not support locking, so this method does nothing. + .. method:: get_file(key) - -.. method:: Maildir.get_file(key) - - Depending upon the host platform, it may not be possible to modify or remove the - underlying message while the returned file remains open. + Depending upon the host platform, it may not be possible to modify or + remove the underlying message while the returned file remains open. .. seealso:: @@ -423,33 +431,34 @@ remarks: representation. If *create* is ``True``, the mailbox is created if it does not exist. -The mbox format is the classic format for storing mail on Unix systems. All -messages in an mbox mailbox are stored in a single file with the beginning of -each message indicated by a line whose first five characters are "From ". + The mbox format is the classic format for storing mail on Unix systems. All + messages in an mbox mailbox are stored in a single file with the beginning of + each message indicated by a line whose first five characters are "From ". -Several variations of the mbox format exist to address perceived shortcomings in -the original. In the interest of compatibility, :class:`mbox` implements the -original format, which is sometimes referred to as :dfn:`mboxo`. This means that -the :mailheader:`Content-Length` header, if present, is ignored and that any -occurrences of "From " at the beginning of a line in a message body are -transformed to ">From " when storing the message, although occurrences of ">From -" are not transformed to "From " when reading the message. + Several variations of the mbox format exist to address perceived shortcomings in + the original. In the interest of compatibility, :class:`mbox` implements the + original format, which is sometimes referred to as :dfn:`mboxo`. This means that + the :mailheader:`Content-Length` header, if present, is ignored and that any + occurrences of "From " at the beginning of a line in a message body are + transformed to ">From " when storing the message, although occurrences of ">From + " are not transformed to "From " when reading the message. -Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special + remarks: -.. method:: mbox.get_file(key) + .. method:: get_file(key) - Using the file after calling :meth:`flush` or :meth:`close` on the :class:`mbox` - instance may yield unpredictable results or raise an exception. + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`mbox` instance may yield unpredictable results or raise an + exception. -.. method:: mbox.lock() - mbox.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -482,106 +491,109 @@ remarks: representation. If *create* is ``True``, the mailbox is created if it does not exist. -MH is a directory-based mailbox format invented for the MH Message Handling -System, a mail user agent. Each message in an MH mailbox resides in its own -file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in -addition to messages. Folders may be nested indefinitely. MH mailboxes also -support :dfn:`sequences`, which are named lists used to logically group messages -without moving them to sub-folders. Sequences are defined in a file called -:file:`.mh_sequences` in each folder. + MH is a directory-based mailbox format invented for the MH Message Handling + System, a mail user agent. Each message in an MH mailbox resides in its own + file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in + addition to messages. Folders may be nested indefinitely. MH mailboxes also + support :dfn:`sequences`, which are named lists used to logically group + messages without moving them to sub-folders. Sequences are defined in a file + called :file:`.mh_sequences` in each folder. -The :class:`MH` class manipulates MH mailboxes, but it does not attempt to -emulate all of :program:`mh`'s behaviors. In particular, it does not modify and -is not affected by the :file:`context` or :file:`.mh_profile` files that are -used by :program:`mh` to store its state and configuration. + The :class:`MH` class manipulates MH mailboxes, but it does not attempt to + emulate all of :program:`mh`'s behaviors. In particular, it does not modify + and is not affected by the :file:`context` or :file:`.mh_profile` files that + are used by :program:`mh` to store its state and configuration. -:class:`MH` instances have all of the methods of :class:`Mailbox` in addition to -the following: + :class:`MH` instances have all of the methods of :class:`Mailbox` in addition + to the following: -.. method:: MH.list_folders() + .. method:: list_folders() - Return a list of the names of all folders. + Return a list of the names of all folders. -.. method:: MH.get_folder(folder) + .. method:: get_folder(folder) - Return an :class:`MH` instance representing the folder whose name is *folder*. A - :exc:`NoSuchMailboxError` exception is raised if the folder does not exist. + Return an :class:`MH` instance representing the folder whose name is + *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder + does not exist. -.. method:: MH.add_folder(folder) + .. method:: add_folder(folder) - Create a folder whose name is *folder* and return an :class:`MH` instance - representing it. + Create a folder whose name is *folder* and return an :class:`MH` instance + representing it. -.. method:: MH.remove_folder(folder) + .. method:: remove_folder(folder) - Delete the folder whose name is *folder*. If the folder contains any messages, a - :exc:`NotEmptyError` exception will be raised and the folder will not be - deleted. + Delete the folder whose name is *folder*. If the folder contains any + messages, a :exc:`NotEmptyError` exception will be raised and the folder + will not be deleted. -.. method:: MH.get_sequences() + .. method:: get_sequences() - Return a dictionary of sequence names mapped to key lists. If there are no - sequences, the empty dictionary is returned. + Return a dictionary of sequence names mapped to key lists. If there are no + sequences, the empty dictionary is returned. -.. method:: MH.set_sequences(sequences) + .. method:: set_sequences(sequences) - Re-define the sequences that exist in the mailbox based upon *sequences*, a - dictionary of names mapped to key lists, like returned by :meth:`get_sequences`. + Re-define the sequences that exist in the mailbox based upon *sequences*, + a dictionary of names mapped to key lists, like returned by + :meth:`get_sequences`. -.. method:: MH.pack() + .. method:: pack() - Rename messages in the mailbox as necessary to eliminate gaps in numbering. - Entries in the sequences list are updated correspondingly. + Rename messages in the mailbox as necessary to eliminate gaps in + numbering. Entries in the sequences list are updated correspondingly. - .. note:: + .. note:: - Already-issued keys are invalidated by this operation and should not be - subsequently used. + Already-issued keys are invalidated by this operation and should not be + subsequently used. -Some :class:`Mailbox` methods implemented by :class:`MH` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`MH` deserve special + remarks: -.. method:: MH.remove(key) - MH.__delitem__(key) - MH.discard(key) + .. method:: remove(key) + __delitem__(key) + discard(key) - These methods immediately delete the message. The MH convention of marking a - message for deletion by prepending a comma to its name is not used. + These methods immediately delete the message. The MH convention of marking + a message for deletion by prepending a comma to its name is not used. -.. method:: MH.lock() - MH.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking the - mailbox means locking the :file:`.mh_sequences` file and, only for the duration - of any operations that affect them, locking individual message files. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. For MH mailboxes, locking + the mailbox means locking the :file:`.mh_sequences` file and, only for the + duration of any operations that affect them, locking individual message + files. -.. method:: MH.get_file(key) + .. method:: get_file(key) - Depending upon the host platform, it may not be possible to remove the - underlying message while the returned file remains open. + Depending upon the host platform, it may not be possible to remove the + underlying message while the returned file remains open. -.. method:: MH.flush() + .. method:: flush() - All changes to MH mailboxes are immediately applied, so this method does - nothing. + All changes to MH mailboxes are immediately applied, so this method does + nothing. -.. method:: MH.close() + .. method:: close() - :class:`MH` instances do not keep any open files, so this method is equivalent - to :meth:`unlock`. + :class:`MH` instances do not keep any open files, so this method is + equivalent to :meth:`unlock`. .. seealso:: @@ -609,54 +621,56 @@ remarks: representation. If *create* is ``True``, the mailbox is created if it does not exist. -Babyl is a single-file mailbox format used by the Rmail mail user agent included -with Emacs. The beginning of a message is indicated by a line containing the two -characters Control-Underscore (``'\037'``) and Control-L (``'\014'``). The end -of a message is indicated by the start of the next message or, in the case of -the last message, a line containing a Control-Underscore (``'\037'``) -character. + Babyl is a single-file mailbox format used by the Rmail mail user agent + included with Emacs. The beginning of a message is indicated by a line + containing the two characters Control-Underscore (``'\037'``) and Control-L + (``'\014'``). The end of a message is indicated by the start of the next + message or, in the case of the last message, a line containing a + Control-Underscore (``'\037'``) character. -Messages in a Babyl mailbox have two sets of headers, original headers and -so-called visible headers. Visible headers are typically a subset of the -original headers that have been reformatted or abridged to be more -attractive. Each message in a Babyl mailbox also has an accompanying list of -:dfn:`labels`, or short strings that record extra information about the message, -and a list of all user-defined labels found in the mailbox is kept in the Babyl -options section. + Messages in a Babyl mailbox have two sets of headers, original headers and + so-called visible headers. Visible headers are typically a subset of the + original headers that have been reformatted or abridged to be more + attractive. Each message in a Babyl mailbox also has an accompanying list of + :dfn:`labels`, or short strings that record extra information about the + message, and a list of all user-defined labels found in the mailbox is kept + in the Babyl options section. -:class:`Babyl` instances have all of the methods of :class:`Mailbox` in addition -to the following: + :class:`Babyl` instances have all of the methods of :class:`Mailbox` in + addition to the following: -.. method:: Babyl.get_labels() + .. method:: get_labels() - Return a list of the names of all user-defined labels used in the mailbox. + Return a list of the names of all user-defined labels used in the mailbox. - .. note:: + .. note:: - The actual messages are inspected to determine which labels exist in the mailbox - rather than consulting the list of labels in the Babyl options section, but the - Babyl section is updated whenever the mailbox is modified. + The actual messages are inspected to determine which labels exist in + the mailbox rather than consulting the list of labels in the Babyl + options section, but the Babyl section is updated whenever the mailbox + is modified. -Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special + remarks: -.. method:: Babyl.get_file(key) + .. method:: get_file(key) - In Babyl mailboxes, the headers of a message are not stored contiguously with - the body of the message. To generate a file-like representation, the headers and - body are copied together into a :class:`StringIO` instance (from the - :mod:`StringIO` module), which has an API identical to that of a file. As a - result, the file-like object is truly independent of the underlying mailbox but - does not save memory compared to a string representation. + In Babyl mailboxes, the headers of a message are not stored contiguously + with the body of the message. To generate a file-like representation, the + headers and body are copied together into a :class:`StringIO` instance + (from the :mod:`StringIO` module), which has an API identical to that of a + file. As a result, the file-like object is truly independent of the + underlying mailbox but does not save memory compared to a string + representation. -.. method:: Babyl.lock() - Babyl.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -683,30 +697,31 @@ remarks: representation. If *create* is ``True``, the mailbox is created if it does not exist. -MMDF is a single-file mailbox format invented for the Multichannel Memorandum -Distribution Facility, a mail transfer agent. Each message is in the same form -as an mbox message but is bracketed before and after by lines containing four -Control-A (``'\001'``) characters. As with the mbox format, the beginning of -each message is indicated by a line whose first five characters are "From ", but -additional occurrences of "From " are not transformed to ">From " when storing -messages because the extra message separator lines prevent mistaking such -occurrences for the starts of subsequent messages. + MMDF is a single-file mailbox format invented for the Multichannel Memorandum + Distribution Facility, a mail transfer agent. Each message is in the same + form as an mbox message but is bracketed before and after by lines containing + four Control-A (``'\001'``) characters. As with the mbox format, the + beginning of each message is indicated by a line whose first five characters + are "From ", but additional occurrences of "From " are not transformed to + ">From " when storing messages because the extra message separator lines + prevent mistaking such occurrences for the starts of subsequent messages. -Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special -remarks: + Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special + remarks: -.. method:: MMDF.get_file(key) + .. method:: get_file(key) - Using the file after calling :meth:`flush` or :meth:`close` on the :class:`MMDF` - instance may yield unpredictable results or raise an exception. + Using the file after calling :meth:`flush` or :meth:`close` on the + :class:`MMDF` instance may yield unpredictable results or raise an + exception. -.. method:: MMDF.lock() - MMDF.unlock() + .. method:: lock() + unlock() - Three locking mechanisms are used---dot locking and, if available, the - :cfunc:`flock` and :cfunc:`lockf` system calls. + Three locking mechanisms are used---dot locking and, if available, the + :cfunc:`flock` and :cfunc:`lockf` system calls. .. seealso:: @@ -737,21 +752,21 @@ remarks: or a file, it should contain an :rfc:`2822`\ -compliant message, which is read and parsed. -The format-specific state and behaviors offered by subclasses vary, but in -general it is only the properties that are not specific to a particular mailbox -that are supported (although presumably the properties are specific to a -particular mailbox format). For example, file offsets for single-file mailbox -formats and file names for directory-based mailbox formats are not retained, -because they are only applicable to the original mailbox. But state such as -whether a message has been read by the user or marked as important is retained, -because it applies to the message itself. + The format-specific state and behaviors offered by subclasses vary, but in + general it is only the properties that are not specific to a particular + mailbox that are supported (although presumably the properties are specific + to a particular mailbox format). For example, file offsets for single-file + mailbox formats and file names for directory-based mailbox formats are not + retained, because they are only applicable to the original mailbox. But state + such as whether a message has been read by the user or marked as important is + retained, because it applies to the message itself. -There is no requirement that :class:`Message` instances be used to represent -messages retrieved using :class:`Mailbox` instances. In some situations, the -time and memory required to generate :class:`Message` representations might not -not acceptable. For such situations, :class:`Mailbox` instances also offer -string and file-like representations, and a custom message factory may be -specified when a :class:`Mailbox` instance is initialized. + There is no requirement that :class:`Message` instances be used to represent + messages retrieved using :class:`Mailbox` instances. In some situations, the + time and memory required to generate :class:`Message` representations might + not not acceptable. For such situations, :class:`Mailbox` instances also + offer string and file-like representations, and a custom message factory may + be specified when a :class:`Mailbox` instance is initialized. .. _mailbox-maildirmessage: @@ -765,106 +780,109 @@ specified when a :class:`Mailbox` instance is initialized. A message with Maildir-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Typically, a mail user agent application moves all of the messages in the -:file:`new` subdirectory to the :file:`cur` subdirectory after the first time -the user opens and closes the mailbox, recording that the messages are old -whether or not they've actually been read. Each message in :file:`cur` has an -"info" section added to its file name to store information about its state. -(Some mail readers may also add an "info" section to messages in :file:`new`.) -The "info" section may take one of two forms: it may contain "2," followed by a -list of standardized flags (e.g., "2,FR") or it may contain "1," followed by -so-called experimental information. Standard flags for Maildir messages are as -follows: - -+------+---------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+=========+================================+ -| D | Draft | Under composition | -+------+---------+--------------------------------+ -| F | Flagged | Marked as important | -+------+---------+--------------------------------+ -| P | Passed | Forwarded, resent, or bounced | -+------+---------+--------------------------------+ -| R | Replied | Replied to | -+------+---------+--------------------------------+ -| S | Seen | Read | -+------+---------+--------------------------------+ -| T | Trashed | Marked for subsequent deletion | -+------+---------+--------------------------------+ - -:class:`MaildirMessage` instances offer the following methods: - - -.. method:: MaildirMessage.get_subdir() - - Return either "new" (if the message should be stored in the :file:`new` - subdirectory) or "cur" (if the message should be stored in the :file:`cur` - subdirectory). + Typically, a mail user agent application moves all of the messages in the + :file:`new` subdirectory to the :file:`cur` subdirectory after the first time + the user opens and closes the mailbox, recording that the messages are old + whether or not they've actually been read. Each message in :file:`cur` has an + "info" section added to its file name to store information about its state. + (Some mail readers may also add an "info" section to messages in + :file:`new`.) The "info" section may take one of two forms: it may contain + "2," followed by a list of standardized flags (e.g., "2,FR") or it may + contain "1," followed by so-called experimental information. Standard flags + for Maildir messages are as follows: - .. note:: + +------+---------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+=========+================================+ + | D | Draft | Under composition | + +------+---------+--------------------------------+ + | F | Flagged | Marked as important | + +------+---------+--------------------------------+ + | P | Passed | Forwarded, resent, or bounced | + +------+---------+--------------------------------+ + | R | Replied | Replied to | + +------+---------+--------------------------------+ + | S | Seen | Read | + +------+---------+--------------------------------+ + | T | Trashed | Marked for subsequent deletion | + +------+---------+--------------------------------+ + + :class:`MaildirMessage` instances offer the following methods: + + + .. method:: get_subdir() + + Return either "new" (if the message should be stored in the :file:`new` + subdirectory) or "cur" (if the message should be stored in the :file:`cur` + subdirectory). + + .. note:: - A message is typically moved from :file:`new` to :file:`cur` after its mailbox - has been accessed, whether or not the message is has been read. A message - ``msg`` has been read if ``"S" in msg.get_flags()`` is ``True``. + A message is typically moved from :file:`new` to :file:`cur` after its + mailbox has been accessed, whether or not the message is has been + read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is + ``True``. -.. method:: MaildirMessage.set_subdir(subdir) + .. method:: set_subdir(subdir) - Set the subdirectory the message should be stored in. Parameter *subdir* must be - either "new" or "cur". + Set the subdirectory the message should be stored in. Parameter *subdir* + must be either "new" or "cur". -.. method:: MaildirMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the standard Maildir format, the result is the concatenation in - alphabetical order of zero or one occurrence of each of ``'D'``, ``'F'``, - ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string is returned if no flags - are set or if "info" contains experimental semantics. + Return a string specifying the flags that are currently set. If the + message complies with the standard Maildir format, the result is the + concatenation in alphabetical order of zero or one occurrence of each of + ``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string + is returned if no flags are set or if "info" contains experimental + semantics. -.. method:: MaildirMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. + Set the flags specified by *flags* and unset all others. -.. method:: MaildirMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. The - current "info" is overwritten whether or not it contains experimental - information rather than flags. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. The current "info" is overwritten whether or not it contains + experimental information rather than flags. -.. method:: MaildirMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. - If "info" contains experimental information rather than flags, the current - "info" is not modified. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. If "info" contains experimental information rather than + flags, the current "info" is not modified. -.. method:: MaildirMessage.get_date() + .. method:: get_date() - Return the delivery date of the message as a floating-point number representing - seconds since the epoch. + Return the delivery date of the message as a floating-point number + representing seconds since the epoch. -.. method:: MaildirMessage.set_date(date) + .. method:: set_date(date) - Set the delivery date of the message to *date*, a floating-point number - representing seconds since the epoch. + Set the delivery date of the message to *date*, a floating-point number + representing seconds since the epoch. -.. method:: MaildirMessage.get_info() + .. method:: get_info() - Return a string containing the "info" for a message. This is useful for - accessing and modifying "info" that is experimental (i.e., not a list of flags). + Return a string containing the "info" for a message. This is useful for + accessing and modifying "info" that is experimental (i.e., not a list of + flags). -.. method:: MaildirMessage.set_info(info) + .. method:: set_info(info) - Set "info" to *info*, which should be a string. + Set "info" to *info*, which should be a string. When a :class:`MaildirMessage` instance is created based upon an :class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status` @@ -930,78 +948,81 @@ When a :class:`MaildirMessage` instance is created based upon a A message with mbox-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Messages in an mbox mailbox are stored together in a single file. The sender's -envelope address and the time of delivery are typically stored in a line -beginning with "From " that is used to indicate the start of a message, though -there is considerable variation in the exact format of this data among mbox -implementations. Flags that indicate the state of the message, such as whether -it has been read or marked as important, are typically stored in -:mailheader:`Status` and :mailheader:`X-Status` headers. + Messages in an mbox mailbox are stored together in a single file. The + sender's envelope address and the time of delivery are typically stored in a + line beginning with "From " that is used to indicate the start of a message, + though there is considerable variation in the exact format of this data among + mbox implementations. Flags that indicate the state of the message, such as + whether it has been read or marked as important, are typically stored in + :mailheader:`Status` and :mailheader:`X-Status` headers. -Conventional flags for mbox messages are as follows: + Conventional flags for mbox messages are as follows: -+------+----------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+==========+================================+ -| R | Read | Read | -+------+----------+--------------------------------+ -| O | Old | Previously detected by MUA | -+------+----------+--------------------------------+ -| D | Deleted | Marked for subsequent deletion | -+------+----------+--------------------------------+ -| F | Flagged | Marked as important | -+------+----------+--------------------------------+ -| A | Answered | Replied to | -+------+----------+--------------------------------+ + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ -The "R" and "O" flags are stored in the :mailheader:`Status` header, and the -"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The -flags and headers typically appear in the order mentioned. + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. -:class:`mboxMessage` instances offer the following methods: + :class:`mboxMessage` instances offer the following methods: -.. method:: mboxMessage.get_from() + .. method:: get_from() - Return a string representing the "From " line that marks the start of the - message in an mbox mailbox. The leading "From " and the trailing newline are - excluded. + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. -.. method:: mboxMessage.set_from(from_[, time_=None]) + .. method:: set_from(from_[, time_=None]) - Set the "From " line to *from_*, which should be specified without a leading - "From " or trailing newline. For convenience, *time_* may be specified and will - be formatted appropriately and appended to *from_*. If *time_* is specified, it - should be a :class:`struct_time` instance, a tuple suitable for passing to - :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). -.. method:: mboxMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the conventional format, the result is the concatenation in the - following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, - ``'F'``, and ``'A'``. + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: mboxMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. Parameter *flags* - should be the concatenation in any order of zero or more occurrences of each of - ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: mboxMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. -.. method:: mboxMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. When an :class:`mboxMessage` instance is created based upon a :class:`MaildirMessage` instance, a "From " line is generated based upon the @@ -1081,43 +1102,43 @@ instance, the "From " line is copied and all flags directly correspond: A message with MH-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -MH messages do not support marks or flags in the traditional sense, but they do -support sequences, which are logical groupings of arbitrary messages. Some mail -reading programs (although not the standard :program:`mh` and :program:`nmh`) -use sequences in much the same way flags are used with other formats, as -follows: + MH messages do not support marks or flags in the traditional sense, but they + do support sequences, which are logical groupings of arbitrary messages. Some + mail reading programs (although not the standard :program:`mh` and + :program:`nmh`) use sequences in much the same way flags are used with other + formats, as follows: -+----------+------------------------------------------+ -| Sequence | Explanation | -+==========+==========================================+ -| unseen | Not read, but previously detected by MUA | -+----------+------------------------------------------+ -| replied | Replied to | -+----------+------------------------------------------+ -| flagged | Marked as important | -+----------+------------------------------------------+ + +----------+------------------------------------------+ + | Sequence | Explanation | + +==========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +----------+------------------------------------------+ + | replied | Replied to | + +----------+------------------------------------------+ + | flagged | Marked as important | + +----------+------------------------------------------+ -:class:`MHMessage` instances offer the following methods: + :class:`MHMessage` instances offer the following methods: -.. method:: MHMessage.get_sequences() + .. method:: get_sequences() - Return a list of the names of sequences that include this message. + Return a list of the names of sequences that include this message. -.. method:: MHMessage.set_sequences(sequences) + .. method:: set_sequences(sequences) - Set the list of sequences that include this message. + Set the list of sequences that include this message. -.. method:: MHMessage.add_sequence(sequence) + .. method:: add_sequence(sequence) - Add *sequence* to the list of sequences that include this message. + Add *sequence* to the list of sequences that include this message. -.. method:: MHMessage.remove_sequence(sequence) + .. method:: remove_sequence(sequence) - Remove *sequence* from the list of sequences that include this message. + Remove *sequence* from the list of sequences that include this message. When an :class:`MHMessage` instance is created based upon a :class:`MaildirMessage` instance, the following conversions take place: @@ -1171,79 +1192,79 @@ When an :class:`MHMessage` instance is created based upon a A message with Babyl-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -Certain message labels, called :dfn:`attributes`, are defined by convention to -have special meanings. The attributes are as follows: + Certain message labels, called :dfn:`attributes`, are defined by convention + to have special meanings. The attributes are as follows: -+-----------+------------------------------------------+ -| Label | Explanation | -+===========+==========================================+ -| unseen | Not read, but previously detected by MUA | -+-----------+------------------------------------------+ -| deleted | Marked for subsequent deletion | -+-----------+------------------------------------------+ -| filed | Copied to another file or mailbox | -+-----------+------------------------------------------+ -| answered | Replied to | -+-----------+------------------------------------------+ -| forwarded | Forwarded | -+-----------+------------------------------------------+ -| edited | Modified by the user | -+-----------+------------------------------------------+ -| resent | Resent | -+-----------+------------------------------------------+ + +-----------+------------------------------------------+ + | Label | Explanation | + +===========+==========================================+ + | unseen | Not read, but previously detected by MUA | + +-----------+------------------------------------------+ + | deleted | Marked for subsequent deletion | + +-----------+------------------------------------------+ + | filed | Copied to another file or mailbox | + +-----------+------------------------------------------+ + | answered | Replied to | + +-----------+------------------------------------------+ + | forwarded | Forwarded | + +-----------+------------------------------------------+ + | edited | Modified by the user | + +-----------+------------------------------------------+ + | resent | Resent | + +-----------+------------------------------------------+ -By default, Rmail displays only visible headers. The :class:`BabylMessage` -class, though, uses the original headers because they are more complete. Visible -headers may be accessed explicitly if desired. + By default, Rmail displays only visible headers. The :class:`BabylMessage` + class, though, uses the original headers because they are more + complete. Visible headers may be accessed explicitly if desired. -:class:`BabylMessage` instances offer the following methods: + :class:`BabylMessage` instances offer the following methods: -.. method:: BabylMessage.get_labels() + .. method:: get_labels() - Return a list of labels on the message. + Return a list of labels on the message. -.. method:: BabylMessage.set_labels(labels) + .. method:: set_labels(labels) - Set the list of labels on the message to *labels*. + Set the list of labels on the message to *labels*. -.. method:: BabylMessage.add_label(label) + .. method:: add_label(label) - Add *label* to the list of labels on the message. + Add *label* to the list of labels on the message. -.. method:: BabylMessage.remove_label(label) + .. method:: remove_label(label) - Remove *label* from the list of labels on the message. + Remove *label* from the list of labels on the message. -.. method:: BabylMessage.get_visible() + .. method:: get_visible() - Return an :class:`Message` instance whose headers are the message's visible - headers and whose body is empty. + Return an :class:`Message` instance whose headers are the message's + visible headers and whose body is empty. -.. method:: BabylMessage.set_visible(visible) + .. method:: set_visible(visible) - Set the message's visible headers to be the same as the headers in *message*. - Parameter *visible* should be a :class:`Message` instance, an - :class:`email.Message.Message` instance, a string, or a file-like object (which - should be open in text mode). + Set the message's visible headers to be the same as the headers in + *message*. Parameter *visible* should be a :class:`Message` instance, an + :class:`email.Message.Message` instance, a string, or a file-like object + (which should be open in text mode). -.. method:: BabylMessage.update_visible() + .. method:: update_visible() - When a :class:`BabylMessage` instance's original headers are modified, the - visible headers are not automatically modified to correspond. This method - updates the visible headers as follows: each visible header with a corresponding - original header is set to the value of the original header, each visible header - without a corresponding original header is removed, and any of - :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, - :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are present - in the original headers but not the visible headers are added to the visible - headers. + When a :class:`BabylMessage` instance's original headers are modified, the + visible headers are not automatically modified to correspond. This method + updates the visible headers as follows: each visible header with a + corresponding original header is set to the value of the original header, + each visible header without a corresponding original header is removed, + and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`, + :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are + present in the original headers but not the visible headers are added to + the visible headers. When a :class:`BabylMessage` instance is created based upon a :class:`MaildirMessage` instance, the following conversions take place: @@ -1299,77 +1320,80 @@ When a :class:`BabylMessage` instance is created based upon an A message with MMDF-specific behaviors. Parameter *message* has the same meaning as with the :class:`Message` constructor. -As with message in an mbox mailbox, MMDF messages are stored with the sender's -address and the delivery date in an initial line beginning with "From ". -Likewise, flags that indicate the state of the message are typically stored in -:mailheader:`Status` and :mailheader:`X-Status` headers. + As with message in an mbox mailbox, MMDF messages are stored with the + sender's address and the delivery date in an initial line beginning with + "From ". Likewise, flags that indicate the state of the message are + typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers. -Conventional flags for MMDF messages are identical to those of mbox message and -are as follows: + Conventional flags for MMDF messages are identical to those of mbox message + and are as follows: -+------+----------+--------------------------------+ -| Flag | Meaning | Explanation | -+======+==========+================================+ -| R | Read | Read | -+------+----------+--------------------------------+ -| O | Old | Previously detected by MUA | -+------+----------+--------------------------------+ -| D | Deleted | Marked for subsequent deletion | -+------+----------+--------------------------------+ -| F | Flagged | Marked as important | -+------+----------+--------------------------------+ -| A | Answered | Replied to | -+------+----------+--------------------------------+ + +------+----------+--------------------------------+ + | Flag | Meaning | Explanation | + +======+==========+================================+ + | R | Read | Read | + +------+----------+--------------------------------+ + | O | Old | Previously detected by MUA | + +------+----------+--------------------------------+ + | D | Deleted | Marked for subsequent deletion | + +------+----------+--------------------------------+ + | F | Flagged | Marked as important | + +------+----------+--------------------------------+ + | A | Answered | Replied to | + +------+----------+--------------------------------+ -The "R" and "O" flags are stored in the :mailheader:`Status` header, and the -"D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The -flags and headers typically appear in the order mentioned. + The "R" and "O" flags are stored in the :mailheader:`Status` header, and the + "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The + flags and headers typically appear in the order mentioned. -:class:`MMDFMessage` instances offer the following methods, which are identical -to those offered by :class:`mboxMessage`: + :class:`MMDFMessage` instances offer the following methods, which are + identical to those offered by :class:`mboxMessage`: -.. method:: MMDFMessage.get_from() + .. method:: get_from() - Return a string representing the "From " line that marks the start of the - message in an mbox mailbox. The leading "From " and the trailing newline are - excluded. + Return a string representing the "From " line that marks the start of the + message in an mbox mailbox. The leading "From " and the trailing newline + are excluded. -.. method:: MMDFMessage.set_from(from_[, time_=None]) + .. method:: set_from(from_[, time_=None]) - Set the "From " line to *from_*, which should be specified without a leading - "From " or trailing newline. For convenience, *time_* may be specified and will - be formatted appropriately and appended to *from_*. If *time_* is specified, it - should be a :class:`struct_time` instance, a tuple suitable for passing to - :meth:`time.strftime`, or ``True`` (to use :meth:`time.gmtime`). + Set the "From " line to *from_*, which should be specified without a + leading "From " or trailing newline. For convenience, *time_* may be + specified and will be formatted appropriately and appended to *from_*. If + *time_* is specified, it should be a :class:`struct_time` instance, a + tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use + :meth:`time.gmtime`). -.. method:: MMDFMessage.get_flags() + .. method:: get_flags() - Return a string specifying the flags that are currently set. If the message - complies with the conventional format, the result is the concatenation in the - following order of zero or one occurrence of each of ``'R'``, ``'O'``, ``'D'``, - ``'F'``, and ``'A'``. + Return a string specifying the flags that are currently set. If the + message complies with the conventional format, the result is the + concatenation in the following order of zero or one occurrence of each of + ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: MMDFMessage.set_flags(flags) + .. method:: set_flags(flags) - Set the flags specified by *flags* and unset all others. Parameter *flags* - should be the concatenation in any order of zero or more occurrences of each of - ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. + Set the flags specified by *flags* and unset all others. Parameter *flags* + should be the concatenation in any order of zero or more occurrences of + each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``. -.. method:: MMDFMessage.add_flag(flag) + .. method:: add_flag(flag) - Set the flag(s) specified by *flag* without changing other flags. To add more - than one flag at a time, *flag* may be a string of more than one character. + Set the flag(s) specified by *flag* without changing other flags. To add + more than one flag at a time, *flag* may be a string of more than one + character. -.. method:: MMDFMessage.remove_flag(flag) + .. method:: remove_flag(flag) - Unset the flag(s) specified by *flag* without changing other flags. To remove - more than one flag at a time, *flag* maybe a string of more than one character. + Unset the flag(s) specified by *flag* without changing other flags. To + remove more than one flag at a time, *flag* maybe a string of more than + one character. When an :class:`MMDFMessage` instance is created based upon a :class:`MaildirMessage` instance, a "From " line is generated based upon the @@ -1445,25 +1469,25 @@ Exceptions The following exception classes are defined in the :mod:`mailbox` module: -.. class:: Error() +.. exception:: Error() The based class for all other module-specific exceptions. -.. class:: NoSuchMailboxError() +.. exception:: NoSuchMailboxError() Raised when a mailbox is expected but is not found, such as when instantiating a :class:`Mailbox` subclass with a path that does not exist (and with the *create* parameter set to ``False``), or when opening a folder that does not exist. -.. class:: NotEmptyErrorError() +.. exception:: NotEmptyErrorError() Raised when a mailbox is not empty but is expected to be, such as when deleting a folder that contains messages. -.. class:: ExternalClashError() +.. exception:: ExternalClashError() Raised when some mailbox-related condition beyond the control of the program causes it to be unable to proceed, such as when failing to acquire a lock that @@ -1471,7 +1495,7 @@ The following exception classes are defined in the :mod:`mailbox` module: already exists. -.. class:: FormatError() +.. exception:: FormatError() Raised when the data in a file cannot be parsed, such as when an :class:`MH` instance attempts to read a corrupted :file:`.mh_sequences` file. diff --git a/Doc/library/mmap.rst b/Doc/library/mmap.rst index 0361320..4828935 100644 --- a/Doc/library/mmap.rst +++ b/Doc/library/mmap.rst @@ -131,111 +131,111 @@ To map anonymous memory, -1 should be passed as the fileno along with the length map.close() -Memory-mapped file objects support the following methods: + Memory-mapped file objects support the following methods: -.. method:: mmap.close() + .. method:: close() - Close the file. Subsequent calls to other methods of the object will - result in an exception being raised. + Close the file. Subsequent calls to other methods of the object will + result in an exception being raised. -.. method:: mmap.find(string[, start[, end]]) + .. method:: find(string[, start[, end]]) - Returns the lowest index in the object where the substring *string* is - found, such that *string* is contained in the range [*start*, *end*]. - Optional arguments *start* and *end* are interpreted as in slice notation. - Returns ``-1`` on failure. + Returns the lowest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. -.. method:: mmap.flush([offset, size]) + .. method:: flush([offset, size]) - Flushes changes made to the in-memory copy of a file back to disk. Without - use of this call there is no guarantee that changes are written back before - the object is destroyed. If *offset* and *size* are specified, only - changes to the given range of bytes will be flushed to disk; otherwise, the - whole extent of the mapping is flushed. + Flushes changes made to the in-memory copy of a file back to disk. Without + use of this call there is no guarantee that changes are written back before + the object is destroyed. If *offset* and *size* are specified, only + changes to the given range of bytes will be flushed to disk; otherwise, the + whole extent of the mapping is flushed. - **(Windows version)** A nonzero value returned indicates success; zero - indicates failure. + **(Windows version)** A nonzero value returned indicates success; zero + indicates failure. - **(Unix version)** A zero value is returned to indicate success. An - exception is raised when the call failed. + **(Unix version)** A zero value is returned to indicate success. An + exception is raised when the call failed. -.. method:: mmap.move(dest, src, count) + .. method:: move(dest, src, count) - Copy the *count* bytes starting at offset *src* to the destination index - *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to - move will throw a :exc:`TypeError` exception. + Copy the *count* bytes starting at offset *src* to the destination index + *dest*. If the mmap was created with :const:`ACCESS_READ`, then calls to + move will throw a :exc:`TypeError` exception. -.. method:: mmap.read(num) + .. method:: read(num) - Return a string containing up to *num* bytes starting from the current file - position; the file position is updated to point after the bytes that were - returned. + Return a string containing up to *num* bytes starting from the current + file position; the file position is updated to point after the bytes that + were returned. -.. method:: mmap.read_byte() + .. method:: read_byte() - Returns a string of length 1 containing the character at the current file - position, and advances the file position by 1. + Returns a string of length 1 containing the character at the current file + position, and advances the file position by 1. -.. method:: mmap.readline() + .. method:: readline() - Returns a single line, starting at the current file position and up to the - next newline. + Returns a single line, starting at the current file position and up to the + next newline. -.. method:: mmap.resize(newsize) + .. method:: resize(newsize) - Resizes the map and the underlying file, if any. If the mmap was created - with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will - throw a :exc:`TypeError` exception. + Resizes the map and the underlying file, if any. If the mmap was created + with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will + throw a :exc:`TypeError` exception. -.. method:: mmap.rfind(string[, start[, end]]) + .. method:: rfind(string[, start[, end]]) - Returns the highest index in the object where the substring *string* is - found, such that *string* is contained in the range [*start*, *end*]. - Optional arguments *start* and *end* are interpreted as in slice notation. - Returns ``-1`` on failure. + Returns the highest index in the object where the substring *string* is + found, such that *string* is contained in the range [*start*, *end*]. + Optional arguments *start* and *end* are interpreted as in slice notation. + Returns ``-1`` on failure. -.. method:: mmap.seek(pos[, whence]) + .. method:: seek(pos[, whence]) - Set the file's current position. *whence* argument is optional and - defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other - values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current position) - and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). + Set the file's current position. *whence* argument is optional and + defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other + values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current + position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end). -.. method:: mmap.size() + .. method:: size() - Return the length of the file, which can be larger than the size of the - memory-mapped area. + Return the length of the file, which can be larger than the size of the + memory-mapped area. -.. method:: mmap.tell() + .. method:: tell() - Returns the current position of the file pointer. + Returns the current position of the file pointer. -.. method:: mmap.write(string) + .. method:: write(string) - Write the bytes in *string* into memory at the current position of the file - pointer; the file position is updated to point after the bytes that were - written. If the mmap was created with :const:`ACCESS_READ`, then writing to - it will throw a :exc:`TypeError` exception. + Write the bytes in *string* into memory at the current position of the + file pointer; the file position is updated to point after the bytes that + were written. If the mmap was created with :const:`ACCESS_READ`, then + writing to it will throw a :exc:`TypeError` exception. -.. method:: mmap.write_byte(byte) + .. method:: write_byte(byte) - Write the single-character string *byte* into memory at the current - position of the file pointer; the file position is advanced by ``1``. If - the mmap was created with :const:`ACCESS_READ`, then writing to it will - throw a :exc:`TypeError` exception. + Write the single-character string *byte* into memory at the current + position of the file pointer; the file position is advanced by ``1``. If + the mmap was created with :const:`ACCESS_READ`, then writing to it will + throw a :exc:`TypeError` exception. diff --git a/Doc/library/modulefinder.rst b/Doc/library/modulefinder.rst index d39f412..7a289f4 100644 --- a/Doc/library/modulefinder.rst +++ b/Doc/library/modulefinder.rst @@ -38,19 +38,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: diff --git a/Doc/library/msilib.rst b/Doc/library/msilib.rst index a8972a8..6f558e6 100644 --- a/Doc/library/msilib.rst +++ b/Doc/library/msilib.rst @@ -318,19 +318,20 @@ CAB Objects *name* is the name of the CAB file in the MSI file. -.. method:: CAB.append(full, file, logical) + .. method:: append(full, file, logical) - Add the file with the pathname *full* to the CAB file, under the name *logical*. - If there is already a file named *logical*, a new file name is created. + Add the file with the pathname *full* to the CAB file, under the name + *logical*. If there is already a file named *logical*, a new file name is + created. - Return the index of the file in the CAB file, and the new name of the file - inside the CAB file. + Return the index of the file in the CAB file, and the new name of the file + inside the CAB file. -.. method:: CAB.commit(database) + .. method:: commit(database) - Generate a CAB file, add it as a stream to the MSI file, put it into the - ``Media`` table, and remove the generated file from the disk. + Generate a CAB file, add it as a stream to the MSI file, put it into the + ``Media`` table, and remove the generated file from the disk. .. _msi-directory: @@ -351,33 +352,33 @@ Directory Objects the default flags that new components get. -.. method:: Directory.start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) + .. method:: start_component([component[, feature[, flags[, keyfile[, uuid]]]]]) - Add an entry to the Component table, and make this component the current - component for this directory. If no component name is given, the directory name - is used. If no *feature* is given, the current feature is used. If no *flags* - are given, the directory's default flags are used. If no *keyfile* is given, the - KeyPath is left null in the Component table. + Add an entry to the Component table, and make this component the current + component for this directory. If no component name is given, the directory + name is used. If no *feature* is given, the current feature is used. If no + *flags* are given, the directory's default flags are used. If no *keyfile* + is given, the KeyPath is left null in the Component table. -.. method:: Directory.add_file(file[, src[, version[, language]]]) + .. method:: add_file(file[, src[, version[, language]]]) - Add a file to the current component of the directory, starting a new one if - there is no current component. By default, the file name in the source and the - file table will be identical. If the *src* file is specified, it is interpreted - relative to the current directory. Optionally, a *version* and a *language* can - be specified for the entry in the File table. + Add a file to the current component of the directory, starting a new one + if there is no current component. By default, the file name in the source + and the file table will be identical. If the *src* file is specified, it + is interpreted relative to the current directory. Optionally, a *version* + and a *language* can be specified for the entry in the File table. -.. method:: Directory.glob(pattern[, exclude]) + .. method:: glob(pattern[, exclude]) - Add a list of files to the current component as specified in the glob pattern. - Individual files can be excluded in the *exclude* list. + Add a list of files to the current component as specified in the glob + pattern. Individual files can be excluded in the *exclude* list. -.. method:: Directory.remove_pyc() + .. method:: remove_pyc() - Remove ``.pyc``/``.pyo`` files on uninstall. + Remove ``.pyc``/``.pyo`` files on uninstall. .. seealso:: @@ -401,11 +402,11 @@ Features :class:`Directory`. -.. method:: Feature.set_current() + .. method:: set_current() - Make this feature the current feature of :mod:`msilib`. New components are - automatically added to the default feature, unless a feature is explicitly - specified. + Make this feature the current feature of :mod:`msilib`. New components are + automatically added to the default feature, unless a feature is explicitly + specified. .. seealso:: @@ -428,19 +429,19 @@ to create MSI files with a user-interface for installing Python packages. belongs to, and *name* is the control's name. -.. method:: Control.event(event, argument[, condition=1[, ordering]]) + .. method:: event(event, argument[, condition=1[, ordering]]) - Make an entry into the ``ControlEvent`` table for this control. + Make an entry into the ``ControlEvent`` table for this control. -.. method:: Control.mapping(event, attribute) + .. method:: mapping(event, attribute) - Make an entry into the ``EventMapping`` table for this control. + Make an entry into the ``EventMapping`` table for this control. -.. method:: Control.condition(action, condition) + .. method:: condition(action, condition) - Make an entry into the ``ControlCondition`` table for this control. + Make an entry into the ``ControlCondition`` table for this control. .. class:: RadioButtonGroup(dlg, name, property) @@ -449,11 +450,11 @@ to create MSI files with a user-interface for installing Python packages. that gets set when a radio button is selected. -.. method:: RadioButtonGroup.add(name, x, y, width, height, text [, value]) + .. method:: add(name, x, y, width, height, text [, value]) - Add a radio button named *name* to the group, at the coordinates *x*, *y*, - *width*, *height*, and with the label *text*. If *value* is omitted, it defaults - to *name*. + Add a radio button named *name* to the group, at the coordinates *x*, *y*, + *width*, *height*, and with the label *text*. If *value* is omitted, it + defaults to *name*. .. class:: Dialog(db, name, x, y, w, h, attr, title, first, default, cancel) @@ -463,42 +464,43 @@ to create MSI files with a user-interface for installing Python packages. default, and cancel controls. -.. method:: Dialog.control(name, type, x, y, width, height, attributes, property, text, control_next, help) + .. method:: control(name, type, x, y, width, height, attributes, property, text, control_next, help) - Return a new :class:`Control` object. An entry in the ``Control`` table is made - with the specified parameters. + Return a new :class:`Control` object. An entry in the ``Control`` table is + made with the specified parameters. - This is a generic method; for specific types, specialized methods are provided. + This is a generic method; for specific types, specialized methods are + provided. -.. method:: Dialog.text(name, x, y, width, height, attributes, text) + .. method:: text(name, x, y, width, height, attributes, text) - Add and return a ``Text`` control. + Add and return a ``Text`` control. -.. method:: Dialog.bitmap(name, x, y, width, height, text) + .. method:: bitmap(name, x, y, width, height, text) - Add and return a ``Bitmap`` control. + Add and return a ``Bitmap`` control. -.. method:: Dialog.line(name, x, y, width, height) + .. method:: line(name, x, y, width, height) - Add and return a ``Line`` control. + Add and return a ``Line`` control. -.. method:: Dialog.pushbutton(name, x, y, width, height, attributes, text, next_control) + .. method:: pushbutton(name, x, y, width, height, attributes, text, next_control) - Add and return a ``PushButton`` control. + Add and return a ``PushButton`` control. -.. method:: Dialog.radiogroup(name, x, y, width, height, attributes, property, text, next_control) + .. method:: radiogroup(name, x, y, width, height, attributes, property, text, next_control) - Add and return a ``RadioButtonGroup`` control. + Add and return a ``RadioButtonGroup`` control. -.. method:: Dialog.checkbox(name, x, y, width, height, attributes, property, text, next_control) + .. method:: checkbox(name, x, y, width, height, attributes, property, text, next_control) - Add and return a ``CheckBox`` control. + Add and return a ``CheckBox`` control. .. seealso:: diff --git a/Doc/library/numbers.rst b/Doc/library/numbers.rst index be6cf1f..c74bd47 100644 --- a/Doc/library/numbers.rst +++ b/Doc/library/numbers.rst @@ -27,18 +27,18 @@ The numeric tower ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All except ``-`` and ``!=`` are abstract. -.. attribute:: Complex.real + .. attribute:: real - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the :class:`Real` component of this number. -.. attribute:: Complex.imag + .. attribute:: imag - Abstract. Retrieves the :class:`Real` component of this number. + Abstract. Retrieves the :class:`Real` component of this number. -.. method:: Complex.conjugate() + .. method:: conjugate() - Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() == - (1-3j)``. + Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate() + == (1-3j)``. .. class:: Real @@ -60,13 +60,13 @@ The numeric tower should be in lowest terms. With these, it provides a default for :func:`float`. -.. attribute:: Rational.numerator + .. attribute:: numerator - Abstract. + Abstract. -.. attribute:: Rational.denominator + .. attribute:: denominator - Abstract. + Abstract. .. class:: Integral diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst index 848766f..ff3d918 100644 --- a/Doc/library/pickle.rst +++ b/Doc/library/pickle.rst @@ -245,34 +245,34 @@ The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and It can thus be an open file object, a :mod:`StringIO` object, or any other custom object that meets this interface. -:class:`Pickler` objects define one (or two) public methods: + :class:`Pickler` objects define one (or two) public methods: -.. method:: Pickler.dump(obj) + .. method:: dump(obj) - Write a pickled representation of *obj* to the open file object given in the - constructor. Either the binary or ASCII format will be used, depending on the - value of the *protocol* argument passed to the constructor. + Write a pickled representation of *obj* to the open file object given in the + constructor. Either the binary or ASCII format will be used, depending on the + value of the *protocol* argument passed to the constructor. -.. method:: Pickler.clear_memo() + .. method:: clear_memo() - Clears the pickler's "memo". The memo is the data structure that remembers - which objects the pickler has already seen, so that shared or recursive objects - pickled by reference and not by value. This method is useful when re-using - picklers. + Clears the pickler's "memo". The memo is the data structure that remembers + which objects the pickler has already seen, so that shared or recursive objects + pickled by reference and not by value. This method is useful when re-using + picklers. - .. note:: + .. note:: - Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers - created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an - instance variable called :attr:`memo` which is a Python dictionary. So to clear - the memo for a :mod:`pickle` module pickler, you could do the following:: + Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers + created by :mod:`cPickle`. In the :mod:`pickle` module, picklers have an + instance variable called :attr:`memo` which is a Python dictionary. So to clear + the memo for a :mod:`pickle` module pickler, you could do the following:: - mypickler.memo.clear() + mypickler.memo.clear() - Code that does not need to support older versions of Python should simply use - :meth:`clear_memo`. + Code that does not need to support older versions of Python should simply use + :meth:`clear_memo`. It is possible to make multiple calls to the :meth:`dump` method of the same :class:`Pickler` instance. These must then be matched to the same number of @@ -296,29 +296,30 @@ instance. If the same object is pickled by multiple :meth:`dump` calls, the reading, a :mod:`StringIO` object, or any other custom object that meets this interface. -:class:`Unpickler` objects have one (or two) public methods: + :class:`Unpickler` objects have one (or two) public methods: -.. method:: Unpickler.load() + .. method:: load() - Read a pickled object representation from the open file object given in the - constructor, and return the reconstituted object hierarchy specified therein. + Read a pickled object representation from the open file object given in + the constructor, and return the reconstituted object hierarchy specified + therein. - This method automatically determines whether the data stream was written in - binary mode or not. + This method automatically determines whether the data stream was written + in binary mode or not. -.. method:: Unpickler.noload() + .. method:: noload() - This is just like :meth:`load` except that it doesn't actually create any - objects. This is useful primarily for finding what's called "persistent ids" - that may be referenced in a pickle data stream. See section - :ref:`pickle-protocol` below for more details. + This is just like :meth:`load` except that it doesn't actually create any + objects. This is useful primarily for finding what's called "persistent + ids" that may be referenced in a pickle data stream. See section + :ref:`pickle-protocol` below for more details. - **Note:** the :meth:`noload` method is currently only available on - :class:`Unpickler` objects created with the :mod:`cPickle` module. - :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload` - method. + **Note:** the :meth:`noload` method is currently only available on + :class:`Unpickler` objects created with the :mod:`cPickle` module. + :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload` + method. What can be pickled and unpickled? diff --git a/Doc/library/robotparser.rst b/Doc/library/robotparser.rst index 6cc7df8..b3a9a60 100644 --- a/Doc/library/robotparser.rst +++ b/Doc/library/robotparser.rst @@ -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. diff --git a/Doc/library/simplehttpserver.rst b/Doc/library/simplehttpserver.rst index aa834dd..2f1af89 100644 --- a/Doc/library/simplehttpserver.rst +++ b/Doc/library/simplehttpserver.rst @@ -23,57 +23,59 @@ The :mod:`SimpleHTTPServer` module defines the following class: :class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the :func:`do_GET` and :func:`do_HEAD` functions. -The :class:`SimpleHTTPRequestHandler` defines the following member variables: + The :class:`SimpleHTTPRequestHandler` defines the following member variables: -.. attribute:: SimpleHTTPRequestHandler.server_version + .. attribute:: server_version - This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is defined - in the module. + This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is + defined in the module. -.. attribute:: SimpleHTTPRequestHandler.extensions_map + .. attribute:: extensions_map - A dictionary mapping suffixes into MIME types. The default is signified by an - empty string, and is considered to be ``application/octet-stream``. The mapping - is used case-insensitively, and so should contain only lower-cased keys. + A dictionary mapping suffixes into MIME types. The default is signified by + an empty string, and is considered to be ``application/octet-stream``. The + mapping is used case-insensitively, and so should contain only lower-cased + keys. -The :class:`SimpleHTTPRequestHandler` defines the following methods: + The :class:`SimpleHTTPRequestHandler` defines the following methods: -.. method:: SimpleHTTPRequestHandler.do_HEAD() + .. method:: do_HEAD() - This method serves the ``'HEAD'`` request type: it sends the headers it would - send for the equivalent ``GET`` request. See the :meth:`do_GET` method for a - more complete explanation of the possible headers. + This method serves the ``'HEAD'`` request type: it sends the headers it + would send for the equivalent ``GET`` request. See the :meth:`do_GET` + method for a more complete explanation of the possible headers. -.. method:: SimpleHTTPRequestHandler.do_GET() + .. method:: do_GET() - The request is mapped to a local file by interpreting the request as a path - relative to the current working directory. + The request is mapped to a local file by interpreting the request as a + path relative to the current working directory. - If the request was mapped to a directory, the directory is checked for a file - named ``index.html`` or ``index.htm`` (in that order). If found, the file's - contents are returned; otherwise a directory listing is generated by calling the - :meth:`list_directory` method. This method uses :func:`os.listdir` to scan the - directory, and returns a ``404`` error response if the :func:`listdir` fails. + If the request was mapped to a directory, the directory is checked for a + file named ``index.html`` or ``index.htm`` (in that order). If found, the + file's contents are returned; otherwise a directory listing is generated + by calling the :meth:`list_directory` method. This method uses + :func:`os.listdir` to scan the directory, and returns a ``404`` error + response if the :func:`listdir` fails. - If the request was mapped to a file, it is opened and the contents are returned. - Any :exc:`IOError` exception in opening the requested file is mapped to a - ``404``, ``'File not found'`` error. Otherwise, the content type is guessed by - calling the :meth:`guess_type` method, which in turn uses the *extensions_map* - variable. + If the request was mapped to a file, it is opened and the contents are + returned. Any :exc:`IOError` exception in opening the requested file is + mapped to a ``404``, ``'File not found'`` error. Otherwise, the content + type is guessed by calling the :meth:`guess_type` method, which in turn + uses the *extensions_map* variable. - A ``'Content-type:'`` header with the guessed content type is output, followed - by a ``'Content-Length:'`` header with the file's size and a - ``'Last-Modified:'`` header with the file's modification time. + A ``'Content-type:'`` header with the guessed content type is output, + followed by a ``'Content-Length:'`` header with the file's size and a + ``'Last-Modified:'`` header with the file's modification time. - Then follows a blank line signifying the end of the headers, and then the - contents of the file are output. If the file's MIME type starts with ``text/`` - the file is opened in text mode; otherwise binary mode is used. + Then follows a blank line signifying the end of the headers, and then the + contents of the file are output. If the file's MIME type starts with + ``text/`` the file is opened in text mode; otherwise binary mode is used. - For example usage, see the implementation of the :func:`test` function. + For example usage, see the implementation of the :func:`test` function. .. seealso:: diff --git a/Doc/library/smtpd.rst b/Doc/library/smtpd.rst index 8927a64..2767516 100644 --- a/Doc/library/smtpd.rst +++ b/Doc/library/smtpd.rst @@ -27,14 +27,15 @@ SMTPServer Objects :mod:`asyncore`'s event loop on instantiation. -.. method:: SMTPServer.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). + .. 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). DebuggingServer Objects diff --git a/Doc/library/string.rst b/Doc/library/string.rst index b5fa4f7..99c2c80 100644 --- a/Doc/library/string.rst +++ b/Doc/library/string.rst @@ -452,29 +452,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: diff --git a/Doc/library/struct.rst b/Doc/library/struct.rst index 924cb60..a1832a1 100644 --- a/Doc/library/struct.rst +++ b/Doc/library/struct.rst @@ -242,37 +242,37 @@ The :mod:`struct` module also defines the following type: since the format string only needs to be compiled once. -Compiled Struct objects support the following methods and attributes: + Compiled Struct objects support the following methods and attributes: -.. method:: Struct.pack(v1, v2, ...) + .. method:: pack(v1, v2, ...) - Identical to the :func:`pack` function, using the compiled format. - (``len(result)`` will equal :attr:`self.size`.) + Identical to the :func:`pack` function, using the compiled format. + (``len(result)`` will equal :attr:`self.size`.) -.. method:: Struct.pack_into(buffer, offset, v1, v2, ...) + .. method:: pack_into(buffer, offset, v1, v2, ...) - Identical to the :func:`pack_into` function, using the compiled format. + Identical to the :func:`pack_into` function, using the compiled format. -.. method:: Struct.unpack(string) + .. method:: unpack(string) - Identical to the :func:`unpack` function, using the compiled format. - (``len(string)`` must equal :attr:`self.size`). + Identical to the :func:`unpack` function, using the compiled format. + (``len(string)`` must equal :attr:`self.size`). -.. method:: Struct.unpack_from(buffer[, offset=0]) + .. method:: unpack_from(buffer[, offset=0]) - Identical to the :func:`unpack_from` function, using the compiled format. - (``len(buffer[offset:])`` must be at least :attr:`self.size`). + Identical to the :func:`unpack_from` function, using the compiled format. + (``len(buffer[offset:])`` must be at least :attr:`self.size`). -.. attribute:: Struct.format + .. attribute:: format - The format string used to construct this Struct object. + The format string used to construct this Struct object. -.. attribute:: Struct.size + .. attribute:: size - The calculated size of the struct (and hence of the string) corresponding - to :attr:`format`. + The calculated size of the struct (and hence of the string) corresponding + to :attr:`format`. diff --git a/Doc/library/textwrap.rst b/Doc/library/textwrap.rst index 350354c..9b2ad11 100644 --- a/Doc/library/textwrap.rst +++ b/Doc/library/textwrap.rst @@ -85,103 +85,104 @@ indentation from strings that have unwanted whitespace to the left of the text. change any of its options through direct assignment to instance attributes between uses. -The :class:`TextWrapper` instance attributes (and keyword arguments to the -constructor) are as follows: + The :class:`TextWrapper` instance attributes (and keyword arguments to the + constructor) are as follows: -.. attribute:: TextWrapper.width + .. attribute:: width - (default: ``70``) The maximum length of wrapped lines. As long as there are no - individual words in the input text longer than :attr:`width`, - :class:`TextWrapper` guarantees that no output line will be longer than - :attr:`width` characters. + (default: ``70``) The maximum length of wrapped lines. As long as there + are no individual words in the input text longer than :attr:`width`, + :class:`TextWrapper` guarantees that no output line will be longer than + :attr:`width` characters. -.. attribute:: TextWrapper.expand_tabs + .. attribute:: expand_tabs - (default: ``True``) If true, then all tab characters in *text* will be expanded - to spaces using the :meth:`expandtabs` method of *text*. + (default: ``True``) If true, then all tab characters in *text* will be + expanded to spaces using the :meth:`expandtabs` method of *text*. -.. attribute:: TextWrapper.replace_whitespace + .. attribute:: replace_whitespace - (default: ``True``) If true, each whitespace character (as defined by - ``string.whitespace``) remaining after tab expansion will be replaced by a - single space. + (default: ``True``) If true, each whitespace character (as defined by + ``string.whitespace``) remaining after tab expansion will be replaced by a + single space. - .. note:: + .. note:: - If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, each tab - character will be replaced by a single space, which is *not* the same as tab - expansion. + If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true, + each tab character will be replaced by a single space, which is *not* + the same as tab expansion. -.. attribute:: TextWrapper.drop_whitespace + .. attribute:: drop_whitespace - (default: ``True``) If true, whitespace that, after wrapping, happens to end up - at the beginning or end of a line is dropped (leading whitespace in the first - line is always preserved, though). + (default: ``True``) If true, whitespace that, after wrapping, happens to + end up at the beginning or end of a line is dropped (leading whitespace in + the first line is always preserved, though). -.. attribute:: TextWrapper.initial_indent + .. attribute:: initial_indent - (default: ``''``) String that will be prepended to the first line of wrapped - output. Counts towards the length of the first line. + (default: ``''``) String that will be prepended to the first line of + wrapped output. Counts towards the length of the first line. -.. attribute:: TextWrapper.subsequent_indent + .. attribute:: subsequent_indent - (default: ``''``) String that will be prepended to all lines of wrapped output - except the first. Counts towards the length of each line except the first. + (default: ``''``) String that will be prepended to all lines of wrapped + output except the first. Counts towards the length of each line except + the first. -.. attribute:: TextWrapper.fix_sentence_endings + .. attribute:: fix_sentence_endings - (default: ``False``) If true, :class:`TextWrapper` attempts to detect sentence - endings and ensure that sentences are always separated by exactly two spaces. - This is generally desired for text in a monospaced font. However, the sentence - detection algorithm is imperfect: it assumes that a sentence ending consists of - a lowercase letter followed by one of ``'.'``, ``'!'``, or ``'?'``, possibly - followed by one of ``'"'`` or ``"'"``, followed by a space. One problem with - this is algorithm is that it is unable to detect the difference between "Dr." in - :: + (default: ``False``) If true, :class:`TextWrapper` attempts to detect + sentence endings and ensure that sentences are always separated by exactly + two spaces. This is generally desired for text in a monospaced font. + However, the sentence detection algorithm is imperfect: it assumes that a + sentence ending consists of a lowercase letter followed by one of ``'.'``, + ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``, + followed by a space. One problem with this is algorithm is that it is + unable to detect the difference between "Dr." in :: - [...] Dr. Frankenstein's monster [...] + [...] Dr. Frankenstein's monster [...] - and "Spot." in :: + and "Spot." in :: - [...] See Spot. See Spot run [...] + [...] See Spot. See Spot run [...] - :attr:`fix_sentence_endings` is false by default. + :attr:`fix_sentence_endings` is false by default. - Since the sentence detection algorithm relies on ``string.lowercase`` for the - definition of "lowercase letter," and a convention of using two spaces after - a period to separate sentences on the same line, it is specific to - English-language texts. + Since the sentence detection algorithm relies on ``string.lowercase`` for + the definition of "lowercase letter," and a convention of using two spaces + after a period to separate sentences on the same line, it is specific to + English-language texts. -.. attribute:: TextWrapper.break_long_words + .. attribute:: break_long_words - (default: ``True``) If true, then words longer than :attr:`width` will be broken - in order to ensure that no lines are longer than :attr:`width`. If it is false, - long words will not be broken, and some lines may be longer than :attr:`width`. - (Long words will be put on a line by themselves, in order to minimize the amount - by which :attr:`width` is exceeded.) + (default: ``True``) If true, then words longer than :attr:`width` will be + broken in order to ensure that no lines are longer than :attr:`width`. If + it is false, long words will not be broken, and some lines may be longer + than :attr:`width`. (Long words will be put on a line by themselves, in + order to minimize the amount by which :attr:`width` is exceeded.) -:class:`TextWrapper` also provides two public methods, analogous to the -module-level convenience functions: + :class:`TextWrapper` also provides two public methods, analogous to the + module-level convenience functions: -.. method:: TextWrapper.wrap(text) + .. method:: wrap(text) - Wraps the single paragraph in *text* (a string) so every line is at most - :attr:`width` characters long. All wrapping options are taken from instance - attributes of the :class:`TextWrapper` instance. Returns a list of output lines, - without final newlines. + Wraps the single paragraph in *text* (a string) so every line is at most + :attr:`width` characters long. All wrapping options are taken from + instance attributes of the :class:`TextWrapper` instance. Returns a list + of output lines, without final newlines. -.. method:: TextWrapper.fill(text) + .. method:: fill(text) - Wraps the single paragraph in *text*, and returns a single string containing the - wrapped paragraph. + Wraps the single paragraph in *text*, and returns a single string + containing the wrapped paragraph. diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst index 61bc559..fde4fa6 100644 --- a/Doc/library/xml.etree.elementtree.rst +++ b/Doc/library/xml.etree.elementtree.rst @@ -304,61 +304,63 @@ ElementTree Objects XML *file* if given. -.. method:: ElementTree._setroot(element) + .. method:: _setroot(element) - Replaces the root element for this tree. This discards the current contents of - the tree, and replaces it with the given element. Use with care. *element* is - an element instance. + Replaces the root element for this tree. This discards the current + contents of the tree, and replaces it with the given element. Use with + care. *element* is an element instance. -.. method:: ElementTree.find(path) + .. method:: find(path) - Finds the first toplevel element with given tag. Same as getroot().find(path). - *path* is the element to look for. Returns the first matching element, or - ``None`` if no element was found. + Finds the first toplevel element with given tag. Same as + getroot().find(path). *path* is the element to look for. Returns the + first matching element, or ``None`` if no element was found. -.. method:: ElementTree.findall(path) + .. method:: findall(path) - Finds all toplevel elements with the given tag. Same as getroot().findall(path). - *path* is the element to look for. Returns a list or :term:`iterator` containing all - matching elements, in document order. + Finds all toplevel elements with the given tag. Same as + getroot().findall(path). *path* is the element to look for. Returns a + list or :term:`iterator` containing all matching elements, in document + order. -.. method:: ElementTree.findtext(path[, default]) + .. method:: findtext(path[, default]) - Finds the element text for the first toplevel element with given tag. Same as - getroot().findtext(path). *path* is the toplevel element to look for. *default* - is the value to return if the element was not found. Returns the text content of - the first matching element, or the default value no element was found. Note - that if the element has is found, but has no text content, this method returns - an empty string. + Finds the element text for the first toplevel element with given tag. + Same as getroot().findtext(path). *path* is the toplevel element to look + for. *default* is the value to return if the element was not + found. Returns the text content of the first matching element, or the + default value no element was found. Note that if the element has is + found, but has no text content, this method returns an empty string. -.. method:: ElementTree.getiterator([tag]) + .. method:: getiterator([tag]) - Creates and returns a tree iterator for the root element. The iterator loops - over all elements in this tree, in section order. *tag* is the tag to look for - (default is to return all elements) + Creates and returns a tree iterator for the root element. The iterator + loops over all elements in this tree, in section order. *tag* is the tag + to look for (default is to return all elements) -.. method:: ElementTree.getroot() + .. method:: getroot() - Returns the root element for this tree. + Returns the root element for this tree. -.. method:: ElementTree.parse(source[, parser]) + .. method:: parse(source[, parser]) - Loads an external XML section into this element tree. *source* is a file name or - file object. *parser* is an optional parser instance. If not given, the - standard XMLTreeBuilder parser is used. Returns the section root element. + Loads an external XML section into this element tree. *source* is a file + name or file object. *parser* is an optional parser instance. If not + given, the standard XMLTreeBuilder parser is used. Returns the section + root element. -.. method:: ElementTree.write(file[, encoding]) + .. method:: write(file[, encoding]) - Writes the element tree to a file, as XML. *file* is a file name, or a file - object opened for writing. *encoding* [1]_ is the output encoding (default is - US-ASCII). + Writes the element tree to a file, as XML. *file* is a file name, or a + file object opened for writing. *encoding* [1]_ is the output encoding + (default is US-ASCII). This is the XML file that is going to be manipulated:: @@ -419,28 +421,28 @@ TreeBuilder Objects Element instances when given. -.. method:: TreeBuilder.close() + .. method:: close() - Flushes the parser buffers, and returns the toplevel document element. Returns an - Element instance. + Flushes the parser buffers, and returns the toplevel document + element. Returns an Element instance. -.. method:: TreeBuilder.data(data) + .. method:: data(data) - Adds text to the current element. *data* is a string. This should be either an - ASCII-only :class:`bytes` object or a :class:`str` object. + Adds text to the current element. *data* is a string. This should be + either an ASCII-only :class:`bytes` object or a :class:`str` object. -.. method:: TreeBuilder.end(tag) + .. method:: end(tag) - Closes the current element. *tag* is the element name. Returns the closed - element. + Closes the current element. *tag* is the element name. Returns the closed + element. -.. method:: TreeBuilder.start(tag, attrs) + .. method:: start(tag, attrs) - Opens a new element. *tag* is the element name. *attrs* is a dictionary - containing element attributes. Returns the opened element. + Opens a new element. *tag* is the element name. *attrs* is a dictionary + containing element attributes. Returns the opened element. .. _elementtree-xmltreebuilder-objects: @@ -457,20 +459,20 @@ XMLTreeBuilder Objects instance of the standard TreeBuilder class. -.. method:: XMLTreeBuilder.close() + .. method:: close() - Finishes feeding data to the parser. Returns an element structure. + Finishes feeding data to the parser. Returns an element structure. -.. method:: XMLTreeBuilder.doctype(name, pubid, system) + .. method:: doctype(name, pubid, system) - Handles a doctype declaration. *name* is the doctype name. *pubid* is the public - identifier. *system* is the system identifier. + Handles a doctype declaration. *name* is the doctype name. *pubid* is the + public identifier. *system* is the system identifier. -.. method:: XMLTreeBuilder.feed(data) + .. method:: feed(data) - Feeds data to the parser. *data* is encoded data. + Feeds data to the parser. *data* is encoded data. :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method for each opening tag, its :meth:`end` method for each closing tag, diff --git a/Doc/library/zipimport.rst b/Doc/library/zipimport.rst index f8d0b1d..8972c06 100644 --- a/Doc/library/zipimport.rst +++ b/Doc/library/zipimport.rst @@ -70,55 +70,57 @@ zipimporter Objects (provided that it exists). -.. method:: zipimporter.find_module(fullname[, path]) + .. method:: find_module(fullname[, path]) - Search for a module specified by *fullname*. *fullname* must be the fully - qualified (dotted) module name. It returns the zipimporter instance itself if - the module was found, or :const:`None` if it wasn't. The optional *path* - argument is ignored---it's there for compatibility with the importer protocol. + Search for a module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the zipimporter instance itself + if the module was found, or :const:`None` if it wasn't. The optional + *path* argument is ignored---it's there for compatibility with the + importer protocol. -.. method:: zipimporter.get_code(fullname) + .. method:: get_code(fullname) - Return the code object for the specified module. Raise :exc:`ZipImportError` if - the module couldn't be found. + Return the code object for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found. -.. method:: zipimporter.get_data(pathname) + .. method:: get_data(pathname) - Return the data associated with *pathname*. Raise :exc:`IOError` if the file - wasn't found. + Return the data associated with *pathname*. Raise :exc:`IOError` if the + file wasn't found. -.. method:: zipimporter.get_source(fullname) + .. method:: get_source(fullname) - Return the source code for the specified module. Raise :exc:`ZipImportError` if - the module couldn't be found, return :const:`None` if the archive does contain - the module, but has no source for it. + Return the source code for the specified module. Raise + :exc:`ZipImportError` if the module couldn't be found, return + :const:`None` if the archive does contain the module, but has no source + for it. -.. method:: zipimporter.is_package(fullname) + .. method:: is_package(fullname) - Return True if the module specified by *fullname* is a package. Raise - :exc:`ZipImportError` if the module couldn't be found. + Return True if the module specified by *fullname* is a package. Raise + :exc:`ZipImportError` if the module couldn't be found. -.. method:: zipimporter.load_module(fullname) + .. method:: load_module(fullname) - Load the module specified by *fullname*. *fullname* must be the fully qualified - (dotted) module name. It returns the imported module, or raises - :exc:`ZipImportError` if it wasn't found. + Load the module specified by *fullname*. *fullname* must be the fully + qualified (dotted) module name. It returns the imported module, or raises + :exc:`ZipImportError` if it wasn't found. -.. attribute:: zipimporter.archive + .. attribute:: archive - The file name of the importer's associated ZIP file. + The file name of the importer's associated ZIP file. -.. attribute:: zipimporter.prefix + .. attribute:: prefix - The path within the ZIP file where modules are searched; see - :class:`zipimporter` for details. + The path within the ZIP file where modules are searched; see + :class:`zipimporter` for details. .. _zipimport-examples: |