Kaydet (Commit) e41251e8 authored tarafından Benjamin Peterson's avatar Benjamin Peterson

Merged revisions 62490 via svnmerge from

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

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

  reformat some documentation of classes so methods and attributes are under the class directive
........
üst 768db92b
...@@ -197,10 +197,10 @@ asynchat - Auxiliary Classes and Functions ...@@ -197,10 +197,10 @@ asynchat - Auxiliary Classes and Functions
the data no larger than *buffer_size*. the data no larger than *buffer_size*.
.. method:: simple_producer.more() .. method:: more()
Produces the next chunk of information from the producer, or returns the Produces the next chunk of information from the producer, or returns the
empty string. empty string.
.. class:: fifo([list=None]) .. class:: fifo([list=None])
...@@ -212,26 +212,26 @@ asynchat - Auxiliary Classes and Functions ...@@ -212,26 +212,26 @@ asynchat - Auxiliary Classes and Functions
producers or data items to be written to the channel. producers or data items to be written to the channel.
.. method:: fifo.is_empty() .. method:: is_empty()
Returns ``True`` if and only if the fifo is empty. Returns ``True`` if and only if the fifo is empty.
.. method:: fifo.first() .. method:: first()
Returns the least-recently :meth:`push`\ ed item from the fifo. Returns the least-recently :meth:`push`\ ed item from the fifo.
.. method:: fifo.push(data) .. method:: push(data)
Adds the given data (which may be a string or a producer object) to the Adds the given data (which may be a string or a producer object) to the
producer fifo. producer fifo.
.. method:: fifo.pop() .. method:: pop()
If the fifo is not empty, returns ``True, first()``, deleting the popped If the fifo is not empty, returns ``True, first()``, deleting the popped
item. Returns ``False, None`` for an empty fifo. item. Returns ``False, None`` for an empty fifo.
The :mod:`asynchat` module also defines one utility function, which may be of The :mod:`asynchat` module also defines one utility function, which may be of
use in network and textual analysis operations. use in network and textual analysis operations.
......
...@@ -95,132 +95,132 @@ any that have been added to the map during asynchronous service) is closed. ...@@ -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 should be added to the list of channels :cfunc:`select`\ ed or
:cfunc:`poll`\ ed for read and write events. :cfunc:`poll`\ ed for read and write events.
Thus, the set of channel events is larger than the basic socket events. The Thus, the set of channel events is larger than the basic socket events. The
full set of methods that can be overridden in your subclass follows: full set of methods that can be overridden in your subclass follows:
.. method:: dispatcher.handle_read() .. method:: handle_read()
Called when the asynchronous loop detects that a :meth:`read` call on the Called when the asynchronous loop detects that a :meth:`read` call on the
channel's socket will succeed. channel's socket will succeed.
.. method:: dispatcher.handle_write() .. method:: handle_write()
Called when the asynchronous loop detects that a writable socket can be Called when the asynchronous loop detects that a writable socket can be
written. Often this method will implement the necessary buffering for written. Often this method will implement the necessary buffering for
performance. For example:: performance. For example::
def handle_write(self): def handle_write(self):
sent = self.send(self.buffer) sent = self.send(self.buffer)
self.buffer = self.buffer[sent:] self.buffer = self.buffer[sent:]
.. method:: dispatcher.handle_expt() .. method:: handle_expt()
Called when there is out of band (OOB) data for a socket connection. This Called when there is out of band (OOB) data for a socket connection. This
will almost never happen, as OOB is tenuously supported and rarely used. will almost never happen, as OOB is tenuously supported and rarely used.
.. method:: dispatcher.handle_connect() .. method:: handle_connect()
Called when the active opener's socket actually makes a connection. Might Called when the active opener's socket actually makes a connection. Might
send a "welcome" banner, or initiate a protocol negotiation with the remote send a "welcome" banner, or initiate a protocol negotiation with the
endpoint, for example. remote endpoint, for example.
.. method:: dispatcher.handle_close() .. method:: handle_close()
Called when the socket is closed. Called when the socket is closed.
.. method:: dispatcher.handle_error() .. method:: handle_error()
Called when an exception is raised and not otherwise handled. The default Called when an exception is raised and not otherwise handled. The default
version prints a condensed traceback. version prints a condensed traceback.
.. method:: dispatcher.handle_accept() .. method:: handle_accept()
Called on listening channels (passive openers) when a connection can be Called on listening channels (passive openers) when a connection can be
established with a new remote endpoint that has issued a :meth:`connect` established with a new remote endpoint that has issued a :meth:`connect`
call for the local endpoint. call for the local endpoint.
.. method:: dispatcher.readable() .. method:: readable()
Called each time around the asynchronous loop to determine whether a Called each time around the asynchronous loop to determine whether a
channel's socket should be added to the list on which read events can channel's socket should be added to the list on which read events can
occur. The default method simply returns ``True``, indicating that by occur. The default method simply returns ``True``, indicating that by
default, all channels will be interested in read events. default, all channels will be interested in read events.
.. method:: dispatcher.writable() .. method:: writable()
Called each time around the asynchronous loop to determine whether a Called each time around the asynchronous loop to determine whether a
channel's socket should be added to the list on which write events can channel's socket should be added to the list on which write events can
occur. The default method simply returns ``True``, indicating that by occur. The default method simply returns ``True``, indicating that by
default, all channels will be interested in write events. default, all channels will be interested in write events.
In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.
In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.
.. method:: dispatcher.create_socket(family, type)
This is identical to the creation of a normal socket, and will use the same .. method:: create_socket(family, type)
options for creation. Refer to the :mod:`socket` documentation for
information on creating sockets.
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 .. method:: connect(address)
element the host to connect to, and the second the port number.
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. .. method:: recv(buffer_size)
An empty string implies that the channel has been closed from the other
end.
Read at most *buffer_size* bytes from the socket's remote end-point. An
empty string implies that the channel has been closed from the other end.
.. method:: dispatcher.listen(backlog)
Listen for connections made to the socket. The *backlog* argument .. method:: listen(backlog)
specifies the maximum number of queued connections and should be at least
1; the maximum value is system-dependent (usually 5).
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 .. method:: bind(address)
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.
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 .. method:: accept()
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.
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. .. method:: close()
The remote end-point will receive no more data (after queued data is
flushed). Sockets are automatically closed when they are Close the socket. All future operations on the socket object will fail.
garbage-collected. 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: .. _asyncore-example:
......
This diff is collapsed.
This diff is collapsed.
...@@ -44,75 +44,77 @@ Handling of compressed files is offered by the :class:`BZ2File` class. ...@@ -44,75 +44,77 @@ Handling of compressed files is offered by the :class:`BZ2File` class.
.. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]]) .. 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 or writing. When opened for writing, the file will be created if it doesn't
exist, and truncated otherwise. If *buffering* is given, ``0`` means unbuffered, exist, and truncated otherwise. If *buffering* is given, ``0`` means
and larger numbers specify the buffer size; the default is ``0``. If unbuffered, and larger numbers specify the buffer size; the default is
*compresslevel* is given, it must be a number between ``1`` and ``9``; the ``0``. If *compresslevel* is given, it must be a number between ``1`` and
default is ``9``. Add a ``'U'`` to mode to open the file for input with ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input
universal newline support. Any line ending in the input file will be seen as a with universal newline support. Any line ending in the input file will be
``'\n'`` in Python. Also, a file so opened gains the attribute seen as a ``'\n'`` in Python. Also, a file so opened gains the attribute
:attr:`newlines`; the value for this attribute is one of ``None`` (no newline :attr:`newlines`; the value for this attribute is one of ``None`` (no newline
read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the newline read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the
types seen. Universal newlines are available only when reading. Instances newline types seen. Universal newlines are available only when
support iteration in the same way as normal :class:`file` instances. reading. Instances support iteration in the same way as normal :class:`file`
instances.
.. method:: BZ2File.close() .. method:: close()
Close the file. Sets data attribute :attr:`closed` to true. A closed file cannot Close the file. Sets data attribute :attr:`closed` to true. A closed file
be used for further I/O operations. :meth:`close` may be called more than once cannot be used for further I/O operations. :meth:`close` may be called
without error. more than once without error.
.. method:: BZ2File.read([size]) .. method:: read([size])
Read at most *size* uncompressed bytes, returned as a string. If the *size* Read at most *size* uncompressed bytes, returned as a string. If the
argument is negative or omitted, read until EOF is reached. *size* argument is negative or omitted, read until EOF is reached.
.. method:: BZ2File.readline([size]) .. method:: readline([size])
Return the next line from the file, as a string, retaining newline. A Return the next line from the file, as a string, retaining newline. A
non-negative *size* argument limits the maximum number of bytes to return (an non-negative *size* argument limits the maximum number of bytes to return
incomplete line may be returned then). Return an empty string at EOF. (an incomplete line may be returned then). Return an empty string at EOF.
.. method:: BZ2File.readlines([size]) .. method:: readlines([size])
Return a list of lines read. The optional *size* argument, if given, is an Return a list of lines read. The optional *size* argument, if given, is an
approximate bound on the total number of bytes in the lines returned. approximate bound on the total number of bytes in the lines returned.
.. method:: BZ2File.seek(offset[, whence]) .. method:: seek(offset[, whence])
Move to new file position. Argument *offset* is a byte count. Optional argument Move to new file position. Argument *offset* is a byte count. Optional
*whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start of file; offset argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start
should be ``>= 0``); other values are ``os.SEEK_CUR`` or ``1`` (move relative to of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or
current position; offset can be positive or negative), and ``os.SEEK_END`` or ``1`` (move relative to current position; offset can be positive or
``2`` (move relative to end of file; offset is usually negative, although many negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file;
platforms allow seeking beyond the end of a file). offset is usually negative, although many platforms allow seeking beyond
the end of a file).
Note that seeking of bz2 files is emulated, and depending on the parameters the Note that seeking of bz2 files is emulated, and depending on the
operation may be extremely slow. parameters the operation may be extremely slow.
.. method:: BZ2File.tell() .. method:: tell()
Return the current file position, an integer. Return the current file position, an integer.
.. method:: BZ2File.write(data) .. method:: write(data)
Write string *data* to file. Note that due to buffering, :meth:`close` may be Write string *data* to file. Note that due to buffering, :meth:`close` may
needed before the file on disk reflects the data written. be needed before the file on disk reflects the data written.
.. method:: BZ2File.writelines(sequence_of_strings) .. method:: writelines(sequence_of_strings)
Write the sequence of strings to the file. Note that newlines are not added. The Write the sequence of strings to the file. Note that newlines are not
sequence can be any iterable object producing strings. This is equivalent to added. The sequence can be any iterable object producing strings. This is
calling write() for each string. equivalent to calling write() for each string.
Sequential (de)compression Sequential (de)compression
...@@ -125,23 +127,23 @@ Sequential compression and decompression is done using the classes ...@@ -125,23 +127,23 @@ Sequential compression and decompression is done using the classes
.. class:: BZ2Compressor([compresslevel]) .. class:: BZ2Compressor([compresslevel])
Create a new compressor object. This object may be used to compress data Create a new compressor object. This object may be used to compress data
sequentially. If you want to compress data in one shot, use the :func:`compress` sequentially. If you want to compress data in one shot, use the
function instead. The *compresslevel* parameter, if given, must be a number :func:`compress` function instead. The *compresslevel* parameter, if given,
between ``1`` and ``9``; the default is ``9``. must be a number between ``1`` and ``9``; the default is ``9``.
.. method:: BZ2Compressor.compress(data) .. method:: compress(data)
Provide more data to the compressor object. It will return chunks of compressed Provide more data to the compressor object. It will return chunks of
data whenever possible. When you've finished providing data to compress, call compressed data whenever possible. When you've finished providing data to
the :meth:`flush` method to finish the compression process, and return what is compress, call the :meth:`flush` method to finish the compression process,
left in internal buffers. and return what is left in internal buffers.
.. method:: BZ2Compressor.flush() .. method:: flush()
Finish the compression process and return what is left in internal buffers. You Finish the compression process and return what is left in internal
must not use the compressor object after calling this method. buffers. You must not use the compressor object after calling this method.
.. class:: BZ2Decompressor() .. class:: BZ2Decompressor()
...@@ -151,12 +153,13 @@ Sequential compression and decompression is done using the classes ...@@ -151,12 +153,13 @@ Sequential compression and decompression is done using the classes
:func:`decompress` function instead. :func:`decompress` function instead.
.. method:: BZ2Decompressor.decompress(data) .. method:: decompress(data)
Provide more data to the decompressor object. It will return chunks of Provide more data to the decompressor object. It will return chunks of
decompressed data whenever possible. If you try to decompress data after the end decompressed data whenever possible. If you try to decompress data after
of stream is found, :exc:`EOFError` will be raised. If any data was found after the end of stream is found, :exc:`EOFError` will be raised. If any data
the end of stream, it'll be ignored and saved in :attr:`unused_data` attribute. was found after the end of stream, it'll be ignored and saved in
:attr:`unused_data` attribute.
One-shot (de)compression One-shot (de)compression
...@@ -168,13 +171,13 @@ and :func:`decompress` functions. ...@@ -168,13 +171,13 @@ and :func:`decompress` functions.
.. function:: compress(data[, compresslevel]) .. function:: compress(data[, compresslevel])
Compress *data* in one shot. If you want to compress data sequentially, use an Compress *data* in one shot. If you want to compress data sequentially, use
instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter, if an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter,
given, must be a number between ``1`` and ``9``; the default is ``9``. if given, must be a number between ``1`` and ``9``; the default is ``9``.
.. function:: decompress(data) .. function:: decompress(data)
Decompress *data* in one shot. If you want to decompress data sequentially, use Decompress *data* in one shot. If you want to decompress data sequentially,
an instance of :class:`BZ2Decompressor` instead. use an instance of :class:`BZ2Decompressor` instead.
This diff is collapsed.
...@@ -43,22 +43,22 @@ The :mod:`CGIHTTPServer` module defines the following class: ...@@ -43,22 +43,22 @@ The :mod:`CGIHTTPServer` module defines the following class:
and serve the output, instead of serving files, if the request leads to and serve the output, instead of serving files, if the request leads to
somewhere below the ``cgi_directories`` path. somewhere below the ``cgi_directories`` path.
The :class:`CGIHTTPRequestHandler` defines the following data member: The :class:`CGIHTTPRequestHandler` defines the following data member:
.. attribute:: CGIHTTPRequestHandler.cgi_directories .. attribute:: cgi_directories
This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to treat This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
as containing CGI scripts. treat as containing CGI scripts.
The :class:`CGIHTTPRequestHandler` defines the following methods: The :class:`CGIHTTPRequestHandler` defines the following methods:
.. method:: CGIHTTPRequestHandler.do_POST() .. method:: do_POST()
This method serves the ``'POST'`` request type, only allowed for CGI scripts. This method serves the ``'POST'`` request type, only allowed for CGI
Error 501, "Can only POST to CGI scripts", is output when trying to POST to a scripts. Error 501, "Can only POST to CGI scripts", is output when trying
non-CGI url. to POST to a non-CGI url.
Note that CGI scripts will be run with UID of user nobody, for security reasons. Note that CGI scripts will be run with UID of user nobody, for security reasons.
Problems with the CGI script will be translated to error 403. Problems with the CGI script will be translated to error 403.
......
...@@ -66,62 +66,64 @@ instance will fail with a :exc:`EOFError` exception. ...@@ -66,62 +66,64 @@ instance will fail with a :exc:`EOFError` exception.
optional argument *inclheader* is true, the size given in the chunk header optional argument *inclheader* is true, the size given in the chunk header
includes the size of the header. The default value is false. includes the size of the header. The default value is false.
A :class:`Chunk` object supports the following methods: A :class:`Chunk` object supports the following methods:
.. method:: Chunk.getname() .. method:: getname()
Returns the name (ID) of the chunk. This is the first 4 bytes of the chunk. Returns the name (ID) of the chunk. This is the first 4 bytes of the
chunk.
.. method:: Chunk.getsize() .. method:: getsize()
Returns the size of the chunk. Returns the size of the chunk.
.. method:: Chunk.close() .. method:: close()
Close and skip to the end of the chunk. This does not close the underlying Close and skip to the end of the chunk. This does not close the
file. underlying file.
The remaining methods will raise :exc:`IOError` if called after the The remaining methods will raise :exc:`IOError` if called after the
:meth:`close` method has been called. :meth:`close` method has been called.
.. method:: Chunk.isatty() .. method:: isatty()
Returns ``False``. Returns ``False``.
.. method:: Chunk.seek(pos[, whence]) .. method:: seek(pos[, whence])
Set the chunk's current position. The *whence* argument is optional and Set the chunk's current position. The *whence* argument is optional and
defaults to ``0`` (absolute file positioning); other values are ``1`` (seek defaults to ``0`` (absolute file positioning); other values are ``1``
relative to the current position) and ``2`` (seek relative to the file's end). (seek relative to the current position) and ``2`` (seek relative to the
There is no return value. If the underlying file does not allow seek, only file's end). There is no return value. If the underlying file does not
forward seeks are allowed. allow seek, only forward seeks are allowed.
.. method:: Chunk.tell() .. method:: tell()
Return the current position into the chunk. Return the current position into the chunk.
.. method:: Chunk.read([size]) .. method:: read([size])
Read at most *size* bytes from the chunk (less if the read hits the end of the Read at most *size* bytes from the chunk (less if the read hits the end of
chunk before obtaining *size* bytes). If the *size* argument is negative or the chunk before obtaining *size* bytes). If the *size* argument is
omitted, read all data until the end of the chunk. The bytes are returned as a negative or omitted, read all data until the end of the chunk. The bytes
string object. An empty string is returned when the end of the chunk is are returned as a string object. An empty string is returned when the end
encountered immediately. of the chunk is encountered immediately.
.. method:: Chunk.skip() .. method:: skip()
Skip to the end of the chunk. All further calls to :meth:`read` for the
chunk will return ``''``. If you are not interested in the contents of
the chunk, this method should be called so that the file points to the
start of the next chunk.
Skip to the end of the chunk. All further calls to :meth:`read` for the chunk
will return ``''``. If you are not interested in the contents of the chunk,
this method should be called so that the file points to the start of the next
chunk.
.. rubric:: Footnotes .. rubric:: Footnotes
......
This diff is collapsed.
...@@ -166,59 +166,60 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin: ...@@ -166,59 +166,60 @@ Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
where only the most recent activity is of interest. where only the most recent activity is of interest.
Deque objects support the following methods: Deque objects support the following methods:
.. method:: deque.append(x) .. method:: append(x)
Add *x* to the right side of the deque. Add *x* to the right side of the deque.
.. method:: deque.appendleft(x) .. method:: appendleft(x)
Add *x* to the left side of the deque. Add *x* to the left side of the deque.
.. method:: deque.clear() .. method:: clear()
Remove all elements from the deque leaving it with length 0. Remove all elements from the deque leaving it with length 0.
.. method:: deque.extend(iterable) .. method:: extend(iterable)
Extend the right side of the deque by appending elements from the iterable Extend the right side of the deque by appending elements from the iterable
argument. argument.
.. method:: deque.extendleft(iterable) .. method:: extendleft(iterable)
Extend the left side of the deque by appending elements from *iterable*. Note, Extend the left side of the deque by appending elements from *iterable*.
the series of left appends results in reversing the order of elements in the Note, the series of left appends results in reversing the order of
iterable argument. elements in the iterable argument.
.. method:: deque.pop() .. method:: pop()
Remove and return an element from the right side of the deque. If no elements Remove and return an element from the right side of the deque. If no
are present, raises an :exc:`IndexError`. elements are present, raises an :exc:`IndexError`.
.. method:: deque.popleft() .. method:: popleft()
Remove and return an element from the left side of the deque. If no elements are Remove and return an element from the left side of the deque. If no
present, raises an :exc:`IndexError`. elements are present, raises an :exc:`IndexError`.
.. method:: deque.remove(value) .. method:: remove(value)
Removed the first occurrence of *value*. If not found, raises a Removed the first occurrence of *value*. If not found, raises a
:exc:`ValueError`. :exc:`ValueError`.
.. method:: deque.rotate(n) .. method:: rotate(n)
Rotate the deque *n* steps to the right. If *n* is negative, rotate to
the 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)``, In addition to the above, deques support iteration, pickling, ``len(d)``,
``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
...@@ -348,32 +349,34 @@ in Unix:: ...@@ -348,32 +349,34 @@ in Unix::
arguments. arguments.
:class:`defaultdict` objects support the following method in addition to the :class:`defaultdict` objects support the following method in addition to the
standard :class:`dict` operations: standard :class:`dict` operations:
.. method:: defaultdict.__missing__(key)
.. method:: defaultdict.__missing__(key) If the :attr:`default_factory` attribute is ``None``, this raises an
:exc:`KeyError` exception with the *key* as argument.
If the :attr:`default_factory` attribute is ``None``, this raises an If :attr:`default_factory` is not ``None``, it is called without arguments
:exc:`KeyError` exception with the *key* as argument. 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 If calling :attr:`default_factory` raises an exception this exception is
provide a default value for the given *key*, this value is inserted in the propagated unchanged.
dictionary for the *key*, and returned.
If calling :attr:`default_factory` raises an exception this exception is This method is called by the :meth:`__getitem__` method of the
propagated unchanged. :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 This attribute is used by the :meth:`__missing__` method; it is
the first argument to the constructor, if present, or to ``None``, if absent. initialized from the first argument to the constructor, if present, or to
``None``, if absent.
.. _defaultdict-examples: .. _defaultdict-examples:
......
...@@ -209,19 +209,20 @@ The :mod:`csv` module defines the following classes: ...@@ -209,19 +209,20 @@ The :mod:`csv` module defines the following classes:
The :class:`Sniffer` class is used to deduce the format of a CSV file. The :class:`Sniffer` class is used to deduce the format of a CSV file.
The :class:`Sniffer` class provides two methods: The :class:`Sniffer` class provides two methods:
.. method:: Sniffer.sniff(sample[, delimiters=None]) .. method:: sniff(sample[, delimiters=None])
Analyze the given *sample* and return a :class:`Dialect` subclass reflecting the Analyze the given *sample* and return a :class:`Dialect` subclass
parameters found. If the optional *delimiters* parameter is given, it is reflecting the parameters found. If the optional *delimiters* parameter
interpreted as a string containing possible valid delimiter characters. is given, it is interpreted as a string containing possible valid
delimiter characters.
.. method:: Sniffer.has_header(sample) .. method:: has_header(sample)
Analyze the sample text (presumed to be in CSV format) and return :const:`True` Analyze the sample text (presumed to be in CSV format) and return
if the first row appears to be a series of column headers. :const:`True` if the first row appears to be a series of column headers.
An example for :class:`Sniffer` use:: An example for :class:`Sniffer` use::
......
This diff is collapsed.
...@@ -1567,92 +1567,94 @@ You can instantiate a :class:`Textbox` object as follows: ...@@ -1567,92 +1567,94 @@ You can instantiate a :class:`Textbox` object as follows:
containing window, with coordinates ``(0, 0)``. The instance's containing window, with coordinates ``(0, 0)``. The instance's
:attr:`stripspaces` flag is initially on. :attr:`stripspaces` flag is initially on.
:class:`Textbox` objects have the following methods: :class:`Textbox` objects have the following methods:
.. method:: Textbox.edit([validator]) .. method:: edit([validator])
This is the entry point you will normally use. It accepts editing keystrokes This is the entry point you will normally use. It accepts editing
until one of the termination keystrokes is entered. If *validator* is supplied, keystrokes until one of the termination keystrokes is entered. If
it must be a function. It will be called for each keystroke entered with the *validator* is supplied, it must be a function. It will be called for
keystroke as a parameter; command dispatch is done on the result. This method each keystroke entered with the keystroke as a parameter; command dispatch
returns the window contents as a string; whether blanks in the window are is done on the result. This method returns the window contents as a
included is affected by the :attr:`stripspaces` member. string; whether blanks in the window are included is affected by the
:attr:`stripspaces` member.
.. method:: Textbox.do_command(ch)
.. method:: do_command(ch)
Process a single command keystroke. Here are the supported special keystrokes:
Process a single command keystroke. Here are the supported special
+------------------+-------------------------------------------+ keystrokes:
| Keystroke | Action |
+==================+===========================================+ +------------------+-------------------------------------------+
| :kbd:`Control-A` | Go to left edge of window. | | Keystroke | Action |
+------------------+-------------------------------------------+ +==================+===========================================+
| :kbd:`Control-B` | Cursor left, wrapping to previous line if | | :kbd:`Control-A` | Go to left edge of window. |
| | appropriate. | +------------------+-------------------------------------------+
+------------------+-------------------------------------------+ | :kbd:`Control-B` | Cursor left, wrapping to previous line if |
| :kbd:`Control-D` | Delete character under cursor. | | | appropriate. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-E` | Go to right edge (stripspaces off) or end | | :kbd:`Control-D` | Delete character under cursor. |
| | of line (stripspaces on). | +------------------+-------------------------------------------+
+------------------+-------------------------------------------+ | :kbd:`Control-E` | Go to right edge (stripspaces off) or end |
| :kbd:`Control-F` | Cursor right, wrapping to next line when | | | of line (stripspaces on). |
| | appropriate. | +------------------+-------------------------------------------+
+------------------+-------------------------------------------+ | :kbd:`Control-F` | Cursor right, wrapping to next line when |
| :kbd:`Control-G` | Terminate, returning the window contents. | | | appropriate. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-H` | Delete character backward. | | :kbd:`Control-G` | Terminate, returning the window contents. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-J` | Terminate if the window is 1 line, | | :kbd:`Control-H` | Delete character backward. |
| | otherwise insert newline. | +------------------+-------------------------------------------+
+------------------+-------------------------------------------+ | :kbd:`Control-J` | Terminate if the window is 1 line, |
| :kbd:`Control-K` | If line is blank, delete it, otherwise | | | otherwise insert newline. |
| | clear to end of line. | +------------------+-------------------------------------------+
+------------------+-------------------------------------------+ | :kbd:`Control-K` | If line is blank, delete it, otherwise |
| :kbd:`Control-L` | Refresh screen. | | | clear to end of line. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-N` | Cursor down; move down one line. | | :kbd:`Control-L` | Refresh screen. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-O` | Insert a blank line at cursor location. | | :kbd:`Control-N` | Cursor down; move down one line. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-P` | Cursor up; move up one line. | | :kbd:`Control-O` | Insert a blank line at cursor location. |
+------------------+-------------------------------------------+ +------------------+-------------------------------------------+
| :kbd:`Control-P` | Cursor up; move up one line. |
Move operations do nothing if the cursor is at an edge where the movement is not +------------------+-------------------------------------------+
possible. The following synonyms are supported where possible:
Move operations do nothing if the cursor is at an edge where the movement
+------------------------+------------------+ is not possible. The following synonyms are supported where possible:
| Constant | Keystroke |
+========================+==================+ +------------------------+------------------+
| :const:`KEY_LEFT` | :kbd:`Control-B` | | Constant | Keystroke |
+------------------------+------------------+ +========================+==================+
| :const:`KEY_RIGHT` | :kbd:`Control-F` | | :const:`KEY_LEFT` | :kbd:`Control-B` |
+------------------------+------------------+ +------------------------+------------------+
| :const:`KEY_UP` | :kbd:`Control-P` | | :const:`KEY_RIGHT` | :kbd:`Control-F` |
+------------------------+------------------+ +------------------------+------------------+
| :const:`KEY_DOWN` | :kbd:`Control-N` | | :const:`KEY_UP` | :kbd:`Control-P` |
+------------------------+------------------+ +------------------------+------------------+
| :const:`KEY_BACKSPACE` | :kbd:`Control-h` | | :const:`KEY_DOWN` | :kbd:`Control-N` |
+------------------------+------------------+ +------------------------+------------------+
| :const:`KEY_BACKSPACE` | :kbd:`Control-h` |
All other keystrokes are treated as a command to insert the given character and +------------------------+------------------+
move right (with line wrapping).
All other keystrokes are treated as a command to insert the given
character and move right (with line wrapping).
.. method:: Textbox.gather()
This method returns the window contents as a string; whether blanks in the .. method:: gather()
window are included is affected by the :attr:`stripspaces` member.
This method returns the window contents as a string; whether blanks in the
window are included is affected by the :attr:`stripspaces` member.
.. attribute:: Textbox.stripspaces
This data member is a flag which controls the interpretation of blanks in the .. attribute:: stripspaces
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 This data member is a flag which controls the interpretation of blanks in
line instead, and trailing blanks are stripped when the window contents are the window. When it is on, trailing blanks on each line are ignored; any
gathered. 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 :mod:`curses.wrapper` --- Terminal handler for curses programs
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -44,35 +44,34 @@ Here are the public methods of the :class:`Generator` class, imported from the ...@@ -44,35 +44,34 @@ Here are the public methods of the :class:`Generator` class, imported from the
:mod:`email.header.Header` class. Set to zero to disable header wrapping. The :mod:`email.header.Header` class. Set to zero to disable header wrapping. The
default is 78, as recommended (but not required) by :rfc:`2822`. default is 78, as recommended (but not required) by :rfc:`2822`.
The other public :class:`Generator` methods are: The other public :class:`Generator` methods are:
.. method:: Generator.flatten(msg[, unixfrom]) .. method:: flatten(msg[, unixfrom])
Print the textual representation of the message object structure rooted at *msg* Print the textual representation of the message object structure rooted at
to the output file specified when the :class:`Generator` instance was created. *msg* to the output file specified when the :class:`Generator` instance
Subparts are visited depth-first and the resulting text will be properly MIME was created. Subparts are visited depth-first and the resulting text will
encoded. be properly MIME encoded.
Optional *unixfrom* is a flag that forces the printing of the envelope header Optional *unixfrom* is a flag that forces the printing of the envelope
delimiter before the first :rfc:`2822` header of the root message object. If header delimiter before the first :rfc:`2822` header of the root message
the root object has no envelope header, a standard one is crafted. By default, object. If the root object has no envelope header, a standard one is
this is set to ``False`` to inhibit the printing of the envelope delimiter. crafted. By default, this is set to ``False`` to inhibit the printing of
the envelope delimiter.
Note that for subparts, no envelope header is ever printed. Note that for subparts, no envelope header is ever printed.
.. method:: clone(fp)
.. method:: Generator.clone(fp) Return an independent clone of this :class:`Generator` instance with the
exact same options.
Return an independent clone of this :class:`Generator` instance with the exact .. method:: write(s)
same options.
Write the string *s* to the underlying file object, i.e. *outfp* passed to
.. method:: Generator.write(s) :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 As a convenience, see the methods :meth:`Message.as_string` and
``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation
......
...@@ -74,65 +74,66 @@ Here is the :class:`Header` class description: ...@@ -74,65 +74,66 @@ Here is the :class:`Header` class description:
and is usually either a space or a hard tab character. This character will be and is usually either a space or a hard tab character. This character will be
prepended to continuation lines. prepended to continuation lines.
Optional *errors* is passed straight through to the :meth:`append` method. Optional *errors* is passed straight through to the :meth:`append` method.
.. method:: Header.append(s[, charset[, errors]]) .. method:: append(s[, charset[, errors]])
Append the string *s* to the MIME header. Append the string *s* to the MIME header.
Optional *charset*, if given, should be a :class:`Charset` instance (see Optional *charset*, if given, should be a :class:`Charset` instance (see
:mod:`email.charset`) or the name of a character set, which will be converted to :mod:`email.charset`) or the name of a character set, which will be
a :class:`Charset` instance. A value of ``None`` (the default) means that the converted to a :class:`Charset` instance. A value of ``None`` (the
*charset* given in the constructor is used. default) means that the *charset* given in the constructor is used.
*s* may be an instance of :class:`bytes` or :class:`str`. If it is an instance *s* may be an instance of :class:`bytes` or :class:`str`. If it is an
of :class:`bytes`, then *charset* is the encoding of that byte string, and a instance of :class:`bytes`, then *charset* is the encoding of that byte
:exc:`UnicodeError` will be raised if the string cannot be decoded with that string, and a :exc:`UnicodeError` will be raised if the string cannot be
character set. decoded with that character set.
If *s* is an instance of :class:`str`, then *charset* is a hint specifying the If *s* is an instance of :class:`str`, then *charset* is a hint specifying
character set of the characters in the string. In this case, when producing an the character set of the characters in the string. In this case, when
:rfc:`2822`\ -compliant header using :rfc:`2047` rules, the Unicode string will producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the
be encoded using the following charsets in order: ``us-ascii``, the *charset* Unicode string will be encoded using the following charsets in order:
hint, ``utf-8``. The first character set to not provoke a :exc:`UnicodeError` ``us-ascii``, the *charset* hint, ``utf-8``. The first character set to
is used. not provoke a :exc:`UnicodeError` is used.
Optional *errors* is passed through to any :func:`encode` or Optional *errors* is passed through to any :func:`encode` or
:func:`ustr.encode` call, and defaults to "strict". :func:`ustr.encode` call, and defaults to "strict".
.. method:: Header.encode([splitchars]) .. method:: encode([splitchars])
Encode a message header into an RFC-compliant format, possibly wrapping long Encode a message header into an RFC-compliant format, possibly wrapping
lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings. long lines and encapsulating non-ASCII parts in base64 or quoted-printable
Optional *splitchars* is a string containing characters to split long ASCII encodings. Optional *splitchars* is a string containing characters to
lines on, in rough support of :rfc:`2822`'s *highest level syntactic breaks*. split long ASCII lines on, in rough support of :rfc:`2822`'s *highest
This doesn't affect :rfc:`2047` encoded lines. level syntactic breaks*. This doesn't affect :rfc:`2047` encoded lines.
The :class:`Header` class also provides a number of methods to support standard The :class:`Header` class also provides a number of methods to support
operators and built-in functions. standard operators and built-in functions.
.. method:: Header.__str__() .. method:: __str__()
A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``. A synonym for :meth:`Header.encode`. Useful for ``str(aHeader)``.
.. method:: Header.__unicode__() .. method:: __unicode__()
A helper for :class:`str`'s :func:`encode` method. Returns the header as a A helper for :class:`str`'s :func:`encode` method. Returns the header as
Unicode string. a Unicode string.
.. method:: __eq__(other)
.. method:: Header.__eq__(other) This method allows you to compare two :class:`Header` instances for
equality.
This method allows you to compare two :class:`Header` instances for equality.
.. method:: __ne__(other)
.. method:: Header.__ne__(other) This method allows you to compare two :class:`Header` instances for
inequality.
This method allows you to compare two :class:`Header` instances for inequality.
The :mod:`email.header` module also provides the following convenient functions. The :mod:`email.header` module also provides the following convenient functions.
......
This diff is collapsed.
...@@ -65,20 +65,21 @@ Here is the API for the :class:`FeedParser`: ...@@ -65,20 +65,21 @@ Here is the API for the :class:`FeedParser`:
defaults to the :class:`email.message.Message` class. defaults to the :class:`email.message.Message` class.
.. method:: FeedParser.feed(data) .. method:: feed(data)
Feed the :class:`FeedParser` some more data. *data* should be a string Feed the :class:`FeedParser` some more data. *data* should be a string
containing one or more lines. The lines can be partial and the containing one or more lines. The lines can be partial and the
:class:`FeedParser` will stitch such partial lines together properly. The lines :class:`FeedParser` will stitch such partial lines together properly. The
in the string can have any of the common three line endings, carriage return, lines in the string can have any of the common three line endings,
newline, or carriage return and newline (they can even be mixed). carriage return, newline, or carriage return and newline (they can even be
mixed).
.. method:: FeedParser.close() .. method:: close()
Closing a :class:`FeedParser` completes the parsing of all previously fed data, Closing a :class:`FeedParser` completes the parsing of all previously fed
and returns the root message object. It is undefined what happens if you feed data, and returns the root message object. It is undefined what happens
more data to a closed :class:`FeedParser`. if you feed more data to a closed :class:`FeedParser`.
Parser class API Parser class API
...@@ -111,33 +112,33 @@ class. ...@@ -111,33 +112,33 @@ class.
effectively non-strict. You should simply stop passing a *strict* flag to effectively non-strict. You should simply stop passing a *strict* flag to
the :class:`Parser` constructor. the :class:`Parser` constructor.
The other public :class:`Parser` methods are: The other public :class:`Parser` methods are:
.. method:: Parser.parse(fp[, headersonly]) .. method:: parse(fp[, headersonly])
Read all the data from the file-like object *fp*, parse the resulting text, and Read all the data from the file-like object *fp*, parse the resulting
return the root message object. *fp* must support both the :meth:`readline` and text, and return the root message object. *fp* must support both the
the :meth:`read` methods on file-like objects. :meth:`readline` and the :meth:`read` methods on file-like objects.
The text contained in *fp* must be formatted as a block of :rfc:`2822` style The text contained in *fp* must be formatted as a block of :rfc:`2822`
headers and header continuation lines, optionally preceded by a envelope style headers and header continuation lines, optionally preceded by a
header. The header block is terminated either by the end of the data or by a envelope header. The header block is terminated either by the end of the
blank line. Following the header block is the body of the message (which may data or by a blank line. Following the header block is the body of the
contain MIME-encoded subparts). message (which may contain MIME-encoded subparts).
Optional *headersonly* is as with the :meth:`parse` method. Optional *headersonly* is as with the :meth:`parse` method.
.. method:: parsestr(text[, headersonly])
.. method:: Parser.parsestr(text[, headersonly]) Similar to the :meth:`parse` method, except it takes a string object
instead of a file-like object. Calling this method on a string is exactly
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 Optional *headersonly* is a flag specifying whether to stop parsing after
a file-like object. Calling this method on a string is exactly equivalent to reading the headers or not. The default is ``False``, meaning it parses
wrapping *text* in a :class:`StringIO` instance first and calling :meth:`parse`. 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 Since creating a message object structure from a string or a file object is such
......
...@@ -66,88 +66,91 @@ The :class:`dircmp` class ...@@ -66,88 +66,91 @@ The :class:`dircmp` class
'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir, 'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir,
os.pardir]``. os.pardir]``.
The :class:`dircmp` class provides the following methods: The :class:`dircmp` class provides the following methods:
.. method:: dircmp.report() .. method:: report()
Print (to ``sys.stdout``) a comparison between *a* and *b*. Print (to ``sys.stdout``) a comparison between *a* and *b*.
.. method:: dircmp.report_partial_closure() .. method:: report_partial_closure()
Print a comparison between *a* and *b* and common immediate subdirectories. Print a comparison between *a* and *b* and common immediate
subdirectories.
.. method:: dircmp.report_full_closure() .. method:: report_full_closure()
Print a comparison between *a* and *b* and common subdirectories (recursively). Print a comparison between *a* and *b* and common subdirectories
(recursively).
The :class:`dircmp` offers a number of interesting attributes that may be used The :class:`dircmp` offers a number of interesting attributes that may be
to get various bits of information about the directory trees being compared. used to get various bits of information about the directory trees being
compared.
Note that via :meth:`__getattr__` hooks, all attributes are computed lazily, so Note that via :meth:`__getattr__` hooks, all attributes are computed lazily,
there is no speed penalty if only those attributes which are lightweight to so there is no speed penalty if only those attributes which are lightweight
compute are used. to compute are used.
.. attribute:: dircmp.left_list .. attribute:: left_list
Files and subdirectories in *a*, filtered by *hide* and *ignore*. Files and subdirectories in *a*, filtered by *hide* and *ignore*.
.. attribute:: dircmp.right_list .. attribute:: right_list
Files and subdirectories in *b*, filtered by *hide* and *ignore*. Files and subdirectories in *b*, filtered by *hide* and *ignore*.
.. attribute:: dircmp.common .. attribute:: common
Files and subdirectories in both *a* and *b*. Files and subdirectories in both *a* and *b*.
.. attribute:: dircmp.left_only .. attribute:: left_only
Files and subdirectories only in *a*. Files and subdirectories only in *a*.
.. attribute:: dircmp.right_only .. attribute:: right_only
Files and subdirectories only in *b*. Files and subdirectories only in *b*.
.. attribute:: dircmp.common_dirs .. attribute:: common_dirs
Subdirectories in both *a* and *b*. Subdirectories in both *a* and *b*.
.. attribute:: dircmp.common_files .. attribute:: common_files
Files in both *a* and *b* Files in both *a* and *b*
.. attribute:: dircmp.common_funny .. attribute:: common_funny
Names in both *a* and *b*, such that the type differs between the directories, Names in both *a* and *b*, such that the type differs between the
or names for which :func:`os.stat` reports an error. directories, or names for which :func:`os.stat` reports an error.
.. attribute:: dircmp.same_files .. attribute:: same_files
Files which are identical in both *a* and *b*. Files which are identical in both *a* and *b*.
.. attribute:: dircmp.diff_files .. attribute:: diff_files
Files which are in both *a* and *b*, whose contents differ. Files which are in both *a* and *b*, whose contents differ.
.. attribute:: dircmp.funny_files .. attribute:: funny_files
Files which are in both *a* and *b*, but could not be compared. Files which are in both *a* and *b*, but could not be compared.
.. attribute:: dircmp.subdirs .. attribute:: subdirs
A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects. A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects.
...@@ -30,60 +30,58 @@ Rational number class. ...@@ -30,60 +30,58 @@ Rational number class.
:class:`numbers.Rational` and is immutable and hashable. :class:`numbers.Rational` and is immutable and hashable.
.. method:: Fraction.from_float(flt) .. method:: from_float(flt)
This classmethod constructs a :class:`Fraction` representing the This classmethod constructs a :class:`Fraction` representing the exact
exact value of *flt*, which must be a :class:`float`. Beware that value of *flt*, which must be a :class:`float`. Beware that
``Fraction.from_float(0.3)`` is not the same value as ``Rational(3, ``Fraction.from_float(0.3)`` is not the same value as ``Rational(3, 10)``
10)``
.. method:: Fraction.from_decimal(dec) .. method:: from_decimal(dec)
This classmethod constructs a :class:`Fraction` representing the This classmethod constructs a :class:`Fraction` representing the exact
exact value of *dec*, which must be a value of *dec*, which must be a :class:`decimal.Decimal`.
:class:`decimal.Decimal`.
.. method:: Fraction.limit_denominator(max_denominator=1000000) .. method:: limit_denominator(max_denominator=1000000)
Finds and returns the closest :class:`Fraction` to ``self`` that Finds and returns the closest :class:`Fraction` to ``self`` that has
has denominator at most max_denominator. This method is useful for denominator at most max_denominator. This method is useful for finding
finding rational approximations to a given floating-point number: rational approximations to a given floating-point number:
>>> from fractions import Fraction >>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000) >>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355L, 113L) 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 >>> from math import pi, cos
>>> Fraction.from_float(cos(pi/3)) >>> Fraction.from_float(cos(pi/3))
Fraction(4503599627370497L, 9007199254740992L) Fraction(4503599627370497L, 9007199254740992L)
>>> Fraction.from_float(cos(pi/3)).limit_denominator() >>> Fraction.from_float(cos(pi/3)).limit_denominator()
Fraction(1L, 2L) Fraction(1L, 2L)
.. method:: Fraction.__floor__() .. method:: __floor__()
Returns the greatest :class:`int` ``<= self``. Will be accessible Returns the greatest :class:`int` ``<= self``. Will be accessible through
through :func:`math.floor` in Py3k. :func:`math.floor` in Py3k.
.. method:: Fraction.__ceil__() .. method:: __ceil__()
Returns the least :class:`int` ``>= self``. Will be accessible Returns the least :class:`int` ``>= self``. Will be accessible through
through :func:`math.ceil` in Py3k. :func:`math.ceil` in Py3k.
.. method:: Fraction.__round__() .. method:: __round__()
Fraction.__round__(ndigits) __round__(ndigits)
The first version returns the nearest :class:`int` to ``self``, The first version returns the nearest :class:`int` to ``self``, rounding
rounding half to even. The second version rounds ``self`` to the half to even. The second version rounds ``self`` to the nearest multiple
nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if of ``Fraction(1, 10**ndigits)`` (logically, if ``ndigits`` is negative),
``ndigits`` is negative), again rounding half toward even. Will be again rounding half toward even. Will be accessible through :func:`round`
accessible through :func:`round` in Py3k. in Py3k.
.. seealso:: .. seealso::
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -27,14 +27,15 @@ SMTPServer Objects ...@@ -27,14 +27,15 @@ SMTPServer Objects
:mod:`asyncore`'s event loop on instantiation. :mod:`asyncore`'s event loop on instantiation.
.. method:: SMTPServer.process_message(peer, mailfrom, rcpttos, data) .. method:: process_message(peer, mailfrom, rcpttos, data)
Raise :exc:`NotImplementedError` exception. Override this in subclasses to do Raise :exc:`NotImplementedError` exception. Override this in subclasses to
something useful with this message. Whatever was passed in the constructor as do something useful with this message. Whatever was passed in the
*remoteaddr* will be available as the :attr:`_remoteaddr` attribute. *peer* is constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
the remote host's address, *mailfrom* is the envelope originator, *rcpttos* are attribute. *peer* is the remote host's address, *mailfrom* is the envelope
the envelope recipients and *data* is a string containing the contents of the originator, *rcpttos* are the envelope recipients and *data* is a string
e-mail (which should be in :rfc:`2822` format). containing the contents of the e-mail (which should be in :rfc:`2822`
format).
DebuggingServer Objects DebuggingServer Objects
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment