More fixes by Tim Hatch.

This commit is contained in:
Georg Brandl 2007-08-13 20:52:56 +00:00
parent 4d962a12f7
commit ba4557f58f
33 changed files with 367 additions and 229 deletions

View File

@ -41,8 +41,8 @@ these modules is installed, the slow-but-simple implementation in module
.. exception:: error .. exception:: error
A tuple containing the exceptions that can be raised by each of the supported A tuple containing the exceptions that can be raised by each of the supported
modules, with a unique exception :exc:`anydbm.error` as the first item --- the modules, with a unique exception also named :exc:`anydbm.error` as the first
latter is used when :exc:`anydbm.error` is raised. item --- the latter is used when :exc:`anydbm.error` is raised.
The object returned by :func:`open` supports most of the same functionality as The object returned by :func:`open` supports most of the same functionality as
dictionaries; keys and their corresponding values can be stored, retrieved, and dictionaries; keys and their corresponding values can be stored, retrieved, and

View File

@ -37,29 +37,30 @@ The functions are:
.. function:: asinh(x) .. function:: asinh(x)
Return the hyperbolic arc sine of *x*. There are two branch cuts, extending left Return the hyperbolic arc sine of *x*. There are two branch cuts, extending
from ±``1j`` to ±-∞``j``, both continuous from above. These branch cuts should left from ``±1j`` to ``±∞j``, both continuous from above. These branch cuts
be considered a bug to be corrected in a future release. The correct branch cuts should be considered a bug to be corrected in a future release. The correct
should extend along the imaginary axis, one from ``1j`` up to``j`` and branch cuts should extend along the imaginary axis, one from ``1j`` up to
continuous from the right, and one from -\ ``1j`` down to -∞``j`` and continuous ``∞j`` and continuous from the right, and one from ``-1j`` down to ``-∞j``
from the left. and continuous from the left.
.. function:: atan(x) .. function:: atan(x)
Return the arc tangent of *x*. There are two branch cuts: One extends from Return the arc tangent of *x*. There are two branch cuts: One extends from
``1j`` along the imaginary axis to ``j``, continuous from the left. The other ``1j`` along the imaginary axis to ``j``, continuous from the left. The
extends from -\ ``1j`` along the imaginary axis to -∞``j``, continuous from the other extends from ``-1j`` along the imaginary axis to ``-∞j``, continuous
left. (This should probably be changed so the upper cut becomes continuous from from the left. (This should probably be changed so the upper cut becomes
the other side.) continuous from the other side.)
.. function:: atanh(x) .. function:: atanh(x)
Return the hyperbolic arc tangent of *x*. There are two branch cuts: One extends Return the hyperbolic arc tangent of *x*. There are two branch cuts: One
from 1 along the real axis to ∞, continuous from above. The other extends from extends from ``1`` along the real axis to ````, continuous from above. The
-1 along the real axis to -∞, continuous from above. (This should probably be other extends from ``-1`` along the real axis to ``-∞``, continuous from
changed so the right cut becomes continuous from the other side.) above. (This should probably be changed so the right cut becomes continuous
from the other side.)
.. function:: cos(x) .. function:: cos(x)
@ -122,12 +123,12 @@ The module also defines two mathematical constants:
.. data:: pi .. data:: pi
The mathematical constant *pi*, as a real. The mathematical constant *pi*, as a float.
.. data:: e .. data:: e
The mathematical constant *e*, as a real. The mathematical constant *e*, as a float.
.. index:: module: math .. index:: module: math

View File

@ -28,10 +28,26 @@ This module provides an exception and a function:
Open a ``db`` database and return the database object. The *path* argument is Open a ``db`` database and return the database object. The *path* argument is
the name of the database file. the name of the database file.
The *flag* argument can be ``'r'`` (the default), ``'w'``, ``'c'`` (which The *flag* argument can be:
creates the database if it doesn't exist), or ``'n'`` (which always creates a
new empty database). For platforms on which the BSD ``db`` library supports +---------+-------------------------------------------+
locking, an ``'l'`` can be appended to indicate that locking should be used. | Value | Meaning |
+=========+===========================================+
| ``'r'`` | Open existing database for reading only |
| | (default) |
+---------+-------------------------------------------+
| ``'w'`` | Open existing database for reading and |
| | writing |
+---------+-------------------------------------------+
| ``'c'`` | Open database for reading and writing, |
| | creating it if it doesn't exist |
+---------+-------------------------------------------+
| ``'n'`` | Always create a new, empty database, open |
| | for reading and writing |
+---------+-------------------------------------------+
For platforms on which the BSD ``db`` library supports locking, an ``'l'``
can be appended to indicate that locking should be used.
The optional *mode* parameter is used to indicate the Unix permission bits that The optional *mode* parameter is used to indicate the Unix permission bits that
should be set if a new database must be created; this will be masked by the should be set if a new database must be created; this will be masked by the

View File

@ -7,8 +7,8 @@
:synopsis: The standard "database" interface, based on ndbm. :synopsis: The standard "database" interface, based on ndbm.
The :mod:`dbm` module provides an interface to the Unix (``n``)``dbm`` library. The :mod:`dbm` module provides an interface to the Unix "(n)dbm" library. Dbm
Dbm objects behave like mappings (dictionaries), except that keys and values are objects behave like mappings (dictionaries), except that keys and values are
always strings. Printing a dbm object doesn't print the keys and values, and the always strings. Printing a dbm object doesn't print the keys and values, and the
:meth:`items` and :meth:`values` methods are not supported. :meth:`items` and :meth:`values` methods are not supported.
@ -57,7 +57,8 @@ The module defines the following:
+---------+-------------------------------------------+ +---------+-------------------------------------------+
The optional *mode* argument is the Unix mode of the file, used only when the The optional *mode* argument is the Unix mode of the file, used only when the
database has to be created. It defaults to octal ``0666``. database has to be created. It defaults to octal ``0666`` (and will be
modified by the prevailing umask).
.. seealso:: .. seealso::

View File

@ -44,9 +44,9 @@ The :mod:`filecmp` module defines the following functions:
Example:: Example::
>>> import filecmp >>> import filecmp
>>> filecmp.cmp('libundoc.tex', 'libundoc.tex') >>> filecmp.cmp('undoc.rst', 'undoc.rst')
True True
>>> filecmp.cmp('libundoc.tex', 'lib.tex') >>> filecmp.cmp('undoc.rst', 'index.rst')
False False

View File

@ -34,14 +34,14 @@ Empty files are opened and immediately closed; the only time their presence in
the list of filenames is noticeable at all is when the last file opened is the list of filenames is noticeable at all is when the last file opened is
empty. empty.
It is possible that the last line of a file does not end in a newline character; Lines are returned with any newlines intact, which means that the last line in
lines are returned including the trailing newline when it is present. a file may not have one.
You can control how files are opened by providing an opening hook via the You can control how files are opened by providing an opening hook via the
*openhook* parameter to :func:`input` or :class:`FileInput()`. The hook must be *openhook* parameter to :func:`fileinput.input` or :class:`FileInput()`. The
a function that takes two arguments, *filename* and *mode*, and returns an hook must be a function that takes two arguments, *filename* and *mode*, and
accordingly opened file-like object. Two useful hooks are already provided by returns an accordingly opened file-like object. Two useful hooks are already
this module. provided by this module.
The following function is the primary interface of this module: The following function is the primary interface of this module:
@ -56,8 +56,8 @@ The following function is the primary interface of this module:
.. versionchanged:: 2.5 .. versionchanged:: 2.5
Added the *mode* and *openhook* parameters. Added the *mode* and *openhook* parameters.
The following functions use the global state created by :func:`input`; if there The following functions use the global state created by :func:`fileinput.input`;
is no active state, :exc:`RuntimeError` is raised. if there is no active state, :exc:`RuntimeError` is raised.
.. function:: filename() .. function:: filename()
@ -121,7 +121,7 @@ available for subclassing as well:
.. class:: FileInput([files[, inplace[, backup[, mode[, openhook]]]]]) .. class:: FileInput([files[, inplace[, backup[, mode[, openhook]]]]])
Class :class:`FileInput` is the implementation; its methods :meth:`filename`, Class :class:`FileInput` is the implementation; its methods :meth:`filename`,
:meth:`fileno`, :meth:`lineno`, :meth:`fileline`, :meth:`isfirstline`, :meth:`fileno`, :meth:`lineno`, :meth:`filelineno`, :meth:`isfirstline`,
:meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the functions :meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the functions
of the same name in the module. In addition it has a :meth:`readline` method of the same name in the module. In addition it has a :meth:`readline` method
which returns the next input line, and a :meth:`__getitem__` method which which returns the next input line, and a :meth:`__getitem__` method which
@ -139,14 +139,15 @@ available for subclassing as well:
Added the *mode* and *openhook* parameters. Added the *mode* and *openhook* parameters.
**Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed **Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed
to :func:`input` or to the :class:`FileInput` constructor, the file is moved to to :func:`fileinput.input` or to the :class:`FileInput` constructor, the file is
a backup file and standard output is directed to the input file (if a file of moved to a backup file and standard output is directed to the input file (if a
the same name as the backup file already exists, it will be replaced silently). file of the same name as the backup file already exists, it will be replaced
This makes it possible to write a filter that rewrites its input file in place. silently). This makes it possible to write a filter that rewrites its input
If the keyword argument ``backup='.<some extension>'`` is also given, it file in place. If the *backup* parameter is given (typically as
specifies the extension for the backup file, and the backup file remains around; ``backup='.<some extension>'``), it specifies the extension for the backup file,
by default, the extension is ``'.bak'`` and it is deleted when the output file and the backup file remains around; by default, the extension is ``'.bak'`` and
is closed. In-place filtering is disabled when standard input is read. it is deleted when the output file is closed. In-place filtering is disabled
when standard input is read.
**Caveat:** The current implementation does not work for MS-DOS 8+3 filesystems. **Caveat:** The current implementation does not work for MS-DOS 8+3 filesystems.

View File

@ -107,19 +107,19 @@ The :mod:`functools` module defines the following function:
have three read-only attributes: have three read-only attributes:
.. attribute:: callable.func .. attribute:: partial.func
A callable object or function. Calls to the :class:`partial` object will be A callable object or function. Calls to the :class:`partial` object will be
forwarded to :attr:`func` with new arguments and keywords. forwarded to :attr:`func` with new arguments and keywords.
.. attribute:: tuple.args .. attribute:: partial.args
The leftmost positional arguments that will be prepended to the positional The leftmost positional arguments that will be prepended to the positional
arguments provided to a :class:`partial` object call. arguments provided to a :class:`partial` object call.
.. attribute:: dict.keywords .. attribute:: partial.keywords
The keyword arguments that will be supplied when the :class:`partial` object is The keyword arguments that will be supplied when the :class:`partial` object is
called. called.

View File

@ -32,24 +32,42 @@ The module defines the following constant and functions:
Open a ``gdbm`` database and return a ``gdbm`` object. The *filename* argument Open a ``gdbm`` database and return a ``gdbm`` object. The *filename* argument
is the name of the database file. is the name of the database file.
The optional *flag* argument can be ``'r'`` (to open an existing database for The optional *flag* argument can be:
reading only --- default), ``'w'`` (to open an existing database for reading and
writing), ``'c'`` (which creates the database if it doesn't exist), or ``'n'``
(which always creates a new empty database).
The following additional characters may be appended to the flag to control how +---------+-------------------------------------------+
the database is opened: | Value | Meaning |
+=========+===========================================+
| ``'r'`` | Open existing database for reading only |
| | (default) |
+---------+-------------------------------------------+
| ``'w'`` | Open existing database for reading and |
| | writing |
+---------+-------------------------------------------+
| ``'c'`` | Open database for reading and writing, |
| | creating it if it doesn't exist |
+---------+-------------------------------------------+
| ``'n'`` | Always create a new, empty database, open |
| | for reading and writing |
+---------+-------------------------------------------+
* ``'f'`` --- Open the database in fast mode. Writes to the database will not The following additional characters may be appended to the flag to control
be synchronized. how the database is opened:
* ``'s'`` --- Synchronized mode. This will cause changes to the database will be +---------+--------------------------------------------+
immediately written to the file. | Value | Meaning |
+=========+============================================+
* ``'u'`` --- Do not lock database. | ``'f'`` | Open the database in fast mode. Writes |
| | to the database will not be synchronized. |
+---------+--------------------------------------------+
| ``'s'`` | Synchronized mode. This will cause changes |
| | to the database to be immediately written |
| | to the file. |
+---------+--------------------------------------------+
| ``'u'`` | Do not lock database. |
+---------+--------------------------------------------+
Not all flags are valid for all versions of ``gdbm``. The module constant Not all flags are valid for all versions of ``gdbm``. The module constant
``open_flags`` is a string of supported flag characters. The exception :const:`open_flags` is a string of supported flag characters. The exception
:exc:`error` is raised if an invalid flag is specified. :exc:`error` is raised if an invalid flag is specified.
The optional *mode* argument is the Unix mode of the file, used only when the The optional *mode* argument is the Unix mode of the file, used only when the

View File

@ -311,7 +311,7 @@ loops that truncate the stream.
If one of the iterables is potentially infinite, then the :func:`izip_longest` If one of the iterables is potentially infinite, then the :func:`izip_longest`
function should be wrapped with something that limits the number of calls (for function should be wrapped with something that limits the number of calls (for
example :func:`islice` or :func:`take`). example :func:`islice` or :func:`takewhile`).
.. versionadded:: 2.6 .. versionadded:: 2.6
@ -414,7 +414,7 @@ can be combined. ::
64 64
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
'', 'martin', '', 'walter', '', 'mark'] ... '', 'martin', '', 'walter', '', 'mark']
>>> for name in islice(reportlines, 3, None, 2): >>> for name in islice(reportlines, 3, None, 2):
... print name.title() ... print name.title()
... ...

View File

@ -30,8 +30,8 @@ de-serializing Python objects, use the :mod:`pickle` module instead.
.. warning:: .. warning::
The :mod:`marshal` module is not intended to be secure against erroneous or The :mod:`marshal` module is not intended to be secure against erroneous or
maliciously constructed data. Never unmarshal data received from an untrusted maliciously constructed data. Never unmarshal data received from an
or unauthenticated source. untrusted or unauthenticated source.
Not all Python object types are supported; in general, only objects whose value Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by is independent from a particular invocation of Python can be written and read by
@ -59,25 +59,27 @@ The module defines these functions:
.. function:: dump(value, file[, version]) .. function:: dump(value, file[, version])
Write the value on the open file. The value must be a supported type. The file Write the value on the open file. The value must be a supported type. The
must be an open file object such as ``sys.stdout`` or returned by :func:`open` file must be an open file object such as ``sys.stdout`` or returned by
or :func:`posix.popen`. It must be opened in binary mode (``'wb'`` or :func:`open` or :func:`os.popen`. It must be opened in binary mode (``'wb'``
``'w+b'``). or ``'w+b'``).
If the value has (or contains an object that has) an unsupported type, a If the value has (or contains an object that has) an unsupported type, a
:exc:`ValueError` exception is raised --- but garbage data will also be written :exc:`ValueError` exception is raised --- but garbage data will also be written
to the file. The object will not be properly read back by :func:`load`. to the file. The object will not be properly read back by :func:`load`.
.. versionadded:: 2.4 .. versionadded:: 2.4
The *version* argument indicates the data format that ``dump`` should use (see The *version* argument indicates the data format that ``dump`` should use
below). (see below).
.. function:: load(file) .. function:: load(file)
Read one value from the open file and return it. If no valid value is read, Read one value from the open file and return it. If no valid value is read
raise :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. The file must be (e.g. because the data has a different Python version's incompatible marshal
an open file object opened in binary mode (``'rb'`` or ``'r+b'``). format), raise :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. The
file must be an open file object opened in binary mode (``'rb'`` or
``'r+b'``).
.. warning:: .. warning::
@ -92,8 +94,8 @@ The module defines these functions:
has (or contains an object that has) an unsupported type. has (or contains an object that has) an unsupported type.
.. versionadded:: 2.4 .. versionadded:: 2.4
The *version* argument indicates the data format that ``dumps`` should use (see The *version* argument indicates the data format that ``dumps`` should use
below). (see below).
.. function:: loads(string) .. function:: loads(string)
@ -102,8 +104,8 @@ The module defines these functions:
:exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. Extra characters in the :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. Extra characters in the
string are ignored. string are ignored.
In addition, the following constants are defined:
In addition, the following constants are defined:
.. data:: version .. data:: version
@ -114,6 +116,7 @@ In addition, the following constants are defined:
.. versionadded:: 2.4 .. versionadded:: 2.4
.. rubric:: Footnotes .. rubric:: Footnotes
.. [#] The name of this module stems from a bit of terminology used by the designers of .. [#] The name of this module stems from a bit of terminology used by the designers of

View File

@ -118,7 +118,9 @@ The mathematical and bitwise operations are the most numerous:
__invert__(o) __invert__(o)
Return the bitwise inverse of the number *o*. This is equivalent to ``~o``. Return the bitwise inverse of the number *o*. This is equivalent to ``~o``.
The names :func:`invert` and :func:`__invert__` were added in Python 2.0.
.. versionadded:: 2.0
The names :func:`invert` and :func:`__invert__`.
.. function:: lshift(a, b) .. function:: lshift(a, b)
@ -199,8 +201,8 @@ The mathematical and bitwise operations are the most numerous:
.. versionadded:: 2.5 .. versionadded:: 2.5
Operations which work with sequences include:
Operations which work with sequences include:
.. function:: concat(a, b) .. function:: concat(a, b)
__concat__(a, b) __concat__(a, b)
@ -211,8 +213,10 @@ Operations which work with sequences include:
.. function:: contains(a, b) .. function:: contains(a, b)
__contains__(a, b) __contains__(a, b)
Return the outcome of the test ``b in a``. Note the reversed operands. The Return the outcome of the test ``b in a``. Note the reversed operands.
name :func:`__contains__` was added in Python 2.0.
.. versionadded:: 2.0
The name :func:`__contains__`.
.. function:: countOf(a, b) .. function:: countOf(a, b)
@ -477,6 +481,8 @@ their character equivalents. ::
>>> vals = map(chr, keys) >>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals) >>> map(operator.setitem, [d]*len(keys), keys, vals)
.. XXX: find a better, readable, example
The :mod:`operator` module also defines tools for generalized attribute and item The :mod:`operator` module also defines tools for generalized attribute and item
lookups. These are useful for making fast field extractors as arguments for lookups. These are useful for making fast field extractors as arguments for
:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
@ -537,11 +543,11 @@ Python syntax and the functions in the :mod:`operator` module.
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Containment Test | ``o in seq`` | ``contains(seq, o)`` | | Containment Test | ``o in seq`` | ``contains(seq, o)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Division | ``a / b`` | ``div(a, b) #`` without | | Division | ``a / b`` | ``div(a, b)`` (without |
| | | ``__future__.division`` | | | | ``__future__.division``) |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Division | ``a / b`` | ``truediv(a, b) #`` with | | Division | ``a / b`` | ``truediv(a, b)`` (with |
| | | ``__future__.division`` | | | | ``__future__.division``) |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Division | ``a // b`` | ``floordiv(a, b)`` | | Division | ``a // b`` | ``floordiv(a, b)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
@ -579,7 +585,7 @@ Python syntax and the functions in the :mod:`operator` module.
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` | | Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Slice Assignment | ``seq[i:j]`` = *values* | ``setslice(seq, i, j, values)`` | | Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` | | Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+

View File

@ -182,7 +182,7 @@ write files see :func:`open`, and for accessing the filesystem see the
the concatenation of *path1*, and optionally *path2*, etc., with exactly one the concatenation of *path1*, and optionally *path2*, etc., with exactly one
directory separator (``os.sep``) inserted between components, unless *path2* is directory separator (``os.sep``) inserted between components, unless *path2* is
empty. Note that on Windows, since there is a current directory for each drive, empty. Note that on Windows, since there is a current directory for each drive,
:func:`os.path.join("c:", "foo")` represents a path relative to the current ``os.path.join("c:", "foo")`` represents a path relative to the current
directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
@ -267,12 +267,12 @@ write files see :func:`open`, and for accessing the filesystem see the
Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext == Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
path``, and *ext* is empty or begins with a period and contains at most one path``, and *ext* is empty or begins with a period and contains at most one
period. Leading periods on the basename are ignored; ``splitext.('.cshrc')`` period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
returns ``('.cshrc', '')``. returns ``('.cshrc', '')``.
.. versionchanged:: 2.6 .. versionchanged:: 2.6
Earlier versions could produce an empty root when the only period was the first Earlier versions could produce an empty root when the only period was the
character. first character.
.. function:: splitunc(path) .. function:: splitunc(path)

View File

@ -124,7 +124,7 @@ There are currently 3 different protocols which can be used for pickling.
* Protocol version 2 was introduced in Python 2.3. It provides much more * Protocol version 2 was introduced in Python 2.3. It provides much more
efficient pickling of new-style classes. efficient pickling of new-style classes.
Refer to PEP 307 for more information. Refer to :pep:`307` for more information.
If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified
as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version
@ -249,7 +249,8 @@ The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
This takes a file-like object to which it will write a pickle data stream. This takes a file-like object to which it will write a pickle data stream.
If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
specified as a negative value, the highest protocol version will be used. specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest
protocol version will be used.
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Introduced the *protocol* parameter. Introduced the *protocol* parameter.
@ -317,6 +318,9 @@ instance. If the same object is pickled by multiple :meth:`dump` calls, the
Read a pickled object representation from the open file object given in the Read a pickled object representation from the open file object given in the
constructor, and return the reconstituted object hierarchy specified therein. constructor, and return the reconstituted object hierarchy specified therein.
This method automatically determines whether the data stream was written in
binary mode or not.
.. method:: Unpickler.noload() .. method:: Unpickler.noload()
@ -713,6 +717,8 @@ member are saved. When the instance is unpickled, the file is reopened, and
reading resumes from the last location. The :meth:`__setstate__` and reading resumes from the last location. The :meth:`__setstate__` and
:meth:`__getstate__` methods are used to implement this behavior. :: :meth:`__getstate__` methods are used to implement this behavior. ::
#!/usr/local/bin/python
class TextReader: class TextReader:
"""Print and number lines in a text file.""" """Print and number lines in a text file."""
def __init__(self, file): def __init__(self, file):
@ -749,11 +755,12 @@ A sample usage might be something like this::
>>> obj = TextReader.TextReader("TextReader.py") >>> obj = TextReader.TextReader("TextReader.py")
>>> obj.readline() >>> obj.readline()
'1: #!/usr/local/bin/python' '1: #!/usr/local/bin/python'
>>> # (more invocations of obj.readline() here) >>> obj.readline()
... obj.readline() '2: '
'7: class TextReader:' >>> obj.readline()
'3: class TextReader:'
>>> import pickle >>> import pickle
>>> pickle.dump(obj,open('save.p', 'wb')) >>> pickle.dump(obj, open('save.p', 'wb'))
If you want to see that :mod:`pickle` works across Python processes, start If you want to see that :mod:`pickle` works across Python processes, start
another Python session, before continuing. What follows can happen from either another Python session, before continuing. What follows can happen from either
@ -762,7 +769,7 @@ the same process or a new process. ::
>>> import pickle >>> import pickle
>>> reader = pickle.load(open('save.p', 'rb')) >>> reader = pickle.load(open('save.p', 'rb'))
>>> reader.readline() >>> reader.readline()
'8: "Print and number lines in a text file."' '4: """Print and number lines in a text file."""'
.. seealso:: .. seealso::

View File

@ -103,7 +103,7 @@ Bookkeeping functions:
.. versionadded:: 2.1 .. versionadded:: 2.1
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Instead of jumping to a specific state, *n* steps ahead, :meth:`jumpahead(n)` Instead of jumping to a specific state, *n* steps ahead, ``jumpahead(n)``
jumps to another state likely to be separated by many steps. jumps to another state likely to be separated by many steps.
@ -185,7 +185,7 @@ be found in any statistics text.
.. function:: uniform(a, b) .. function:: uniform(a, b)
Return a random real number *N* such that ``a <= N < b``. Return a random floating point number *N* such that ``a <= N < b``.
.. function:: betavariate(alpha, beta) .. function:: betavariate(alpha, beta)
@ -228,10 +228,10 @@ be found in any statistics text.
.. function:: vonmisesvariate(mu, kappa) .. function:: vonmisesvariate(mu, kappa)
*mu* is the mean angle, expressed in radians between 0 and 2\**pi*, and *kappa* *mu* is the mean angle, expressed in radians between 0 and 2\*\ *pi*, and *kappa*
is the concentration parameter, which must be greater than or equal to zero. If is the concentration parameter, which must be greater than or equal to zero. If
*kappa* is equal to zero, this distribution reduces to a uniform random angle *kappa* is equal to zero, this distribution reduces to a uniform random angle
over the range 0 to 2\**pi*. over the range 0 to 2\*\ *pi*.
.. function:: paretovariate(alpha) .. function:: paretovariate(alpha)
@ -244,8 +244,8 @@ be found in any statistics text.
Weibull distribution. *alpha* is the scale parameter and *beta* is the shape Weibull distribution. *alpha* is the scale parameter and *beta* is the shape
parameter. parameter.
Alternative Generators:
Alternative Generators:
.. class:: WichmannHill([seed]) .. class:: WichmannHill([seed])

View File

@ -66,7 +66,7 @@ codes will not be correct.
.. function:: copy2(src, dst) .. function:: copy2(src, dst)
Similar to :func:`copy`, but last access time and last modification time are Similar to :func:`copy`, but last access time and last modification time are
copied as well. This is similar to the Unix command :program:`cp` :option:`-p`. copied as well. This is similar to the Unix command :program:`cp -p`.
.. function:: copytree(src, dst[, symlinks]) .. function:: copytree(src, dst[, symlinks])
@ -137,9 +137,10 @@ This example is the implementation of the :func:`copytree` function, described
above, with the docstring omitted. It demonstrates many of the other functions above, with the docstring omitted. It demonstrates many of the other functions
provided by this module. :: provided by this module. ::
def copytree(src, dst, symlinks=0): def copytree(src, dst, symlinks=False):
names = os.listdir(src) names = os.listdir(src)
os.mkdir(dst) os.makedirs(dst)
errors = []
for name in names: for name in names:
srcname = os.path.join(src, name) srcname = os.path.join(src, name)
dstname = os.path.join(dst, name) dstname = os.path.join(dst, name)
@ -151,6 +152,19 @@ provided by this module. ::
copytree(srcname, dstname, symlinks) copytree(srcname, dstname, symlinks)
else: else:
copy2(srcname, dstname) copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error), why: except (IOError, os.error), why:
print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why)) errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError, why:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors

View File

@ -81,12 +81,13 @@ The module defines the following user-callable functions:
.. function:: mkstemp([suffix[, prefix[, dir[, text]]]]) .. function:: mkstemp([suffix[, prefix[, dir[, text]]]])
Creates a temporary file in the most secure manner possible. There are no race Creates a temporary file in the most secure manner possible. There are no
conditions in the file's creation, assuming that the platform properly race conditions in the file's creation, assuming that the platform properly
implements the :const:`O_EXCL` flag for :func:`os.open`. The file is readable implements the :const:`os.O_EXCL` flag for :func:`os.open`. The file is
and writable only by the creating user ID. If the platform uses permission bits readable and writable only by the creating user ID. If the platform uses
to indicate whether a file is executable, the file is executable by no one. The permission bits to indicate whether a file is executable, the file is
file descriptor is not inherited by child processes. executable by no one. The file descriptor is not inherited by child
processes.
Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible for Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible for
deleting the temporary file when done with it. deleting the temporary file when done with it.
@ -173,7 +174,7 @@ function arguments, instead.
* On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment * On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment
variable. variable.
* On Windows, the directories :file:`C:$\\TEMP`, :file:`C:$\\TMP`, * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
:file:`\\TEMP`, and :file:`\\TMP`, in that order. :file:`\\TEMP`, and :file:`\\TMP`, in that order.
* On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
@ -185,8 +186,8 @@ function arguments, instead.
.. function:: gettempdir() .. function:: gettempdir()
Return the directory currently selected to create temporary files in. If Return the directory currently selected to create temporary files in. If
``tempdir`` is not ``None``, this simply returns its contents; otherwise, the :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
search described above is performed, and the result returned. the search described above is performed, and the result returned.
.. data:: template .. data:: template

View File

@ -41,8 +41,8 @@ these modules is installed, the slow-but-simple implementation in module
.. exception:: error .. exception:: error
A tuple containing the exceptions that can be raised by each of the supported A tuple containing the exceptions that can be raised by each of the supported
modules, with a unique exception :exc:`anydbm.error` as the first item --- the modules, with a unique exception also named :exc:`anydbm.error` as the first
latter is used when :exc:`anydbm.error` is raised. item --- the latter is used when :exc:`anydbm.error` is raised.
The object returned by :func:`open` supports most of the same functionality as The object returned by :func:`open` supports most of the same functionality as
dictionaries; keys and their corresponding values can be stored, retrieved, and dictionaries; keys and their corresponding values can be stored, retrieved, and

View File

@ -37,29 +37,30 @@ The functions are:
.. function:: asinh(x) .. function:: asinh(x)
Return the hyperbolic arc sine of *x*. There are two branch cuts, extending left Return the hyperbolic arc sine of *x*. There are two branch cuts, extending
from ±``1j`` to ±-∞``j``, both continuous from above. These branch cuts should left from ``±1j`` to ``±∞j``, both continuous from above. These branch cuts
be considered a bug to be corrected in a future release. The correct branch cuts should be considered a bug to be corrected in a future release. The correct
should extend along the imaginary axis, one from ``1j`` up to``j`` and branch cuts should extend along the imaginary axis, one from ``1j`` up to
continuous from the right, and one from -\ ``1j`` down to -∞``j`` and continuous ``∞j`` and continuous from the right, and one from ``-1j`` down to ``-∞j``
from the left. and continuous from the left.
.. function:: atan(x) .. function:: atan(x)
Return the arc tangent of *x*. There are two branch cuts: One extends from Return the arc tangent of *x*. There are two branch cuts: One extends from
``1j`` along the imaginary axis to ``j``, continuous from the left. The other ``1j`` along the imaginary axis to ``j``, continuous from the left. The
extends from -\ ``1j`` along the imaginary axis to -∞``j``, continuous from the other extends from ``-1j`` along the imaginary axis to ``-∞j``, continuous
left. (This should probably be changed so the upper cut becomes continuous from from the left. (This should probably be changed so the upper cut becomes
the other side.) continuous from the other side.)
.. function:: atanh(x) .. function:: atanh(x)
Return the hyperbolic arc tangent of *x*. There are two branch cuts: One extends Return the hyperbolic arc tangent of *x*. There are two branch cuts: One
from 1 along the real axis to ∞, continuous from above. The other extends from extends from ``1`` along the real axis to ````, continuous from above. The
-1 along the real axis to -∞, continuous from above. (This should probably be other extends from ``-1`` along the real axis to ``-∞``, continuous from
changed so the right cut becomes continuous from the other side.) above. (This should probably be changed so the right cut becomes continuous
from the other side.)
.. function:: cos(x) .. function:: cos(x)
@ -122,12 +123,12 @@ The module also defines two mathematical constants:
.. data:: pi .. data:: pi
The mathematical constant *pi*, as a real. The mathematical constant *pi*, as a float.
.. data:: e .. data:: e
The mathematical constant *e*, as a real. The mathematical constant *e*, as a float.
.. index:: module: math .. index:: module: math

View File

@ -28,10 +28,26 @@ This module provides an exception and a function:
Open a ``db`` database and return the database object. The *path* argument is Open a ``db`` database and return the database object. The *path* argument is
the name of the database file. the name of the database file.
The *flag* argument can be ``'r'`` (the default), ``'w'``, ``'c'`` (which The *flag* argument can be:
creates the database if it doesn't exist), or ``'n'`` (which always creates a
new empty database). For platforms on which the BSD ``db`` library supports +---------+-------------------------------------------+
locking, an ``'l'`` can be appended to indicate that locking should be used. | Value | Meaning |
+=========+===========================================+
| ``'r'`` | Open existing database for reading only |
| | (default) |
+---------+-------------------------------------------+
| ``'w'`` | Open existing database for reading and |
| | writing |
+---------+-------------------------------------------+
| ``'c'`` | Open database for reading and writing, |
| | creating it if it doesn't exist |
+---------+-------------------------------------------+
| ``'n'`` | Always create a new, empty database, open |
| | for reading and writing |
+---------+-------------------------------------------+
For platforms on which the BSD ``db`` library supports locking, an ``'l'``
can be appended to indicate that locking should be used.
The optional *mode* parameter is used to indicate the Unix permission bits that The optional *mode* parameter is used to indicate the Unix permission bits that
should be set if a new database must be created; this will be masked by the should be set if a new database must be created; this will be masked by the

View File

@ -7,8 +7,8 @@
:synopsis: The standard "database" interface, based on ndbm. :synopsis: The standard "database" interface, based on ndbm.
The :mod:`dbm` module provides an interface to the Unix (``n``)``dbm`` library. The :mod:`dbm` module provides an interface to the Unix "(n)dbm" library. Dbm
Dbm objects behave like mappings (dictionaries), except that keys and values are objects behave like mappings (dictionaries), except that keys and values are
always strings. Printing a dbm object doesn't print the keys and values, and the always strings. Printing a dbm object doesn't print the keys and values, and the
:meth:`items` and :meth:`values` methods are not supported. :meth:`items` and :meth:`values` methods are not supported.
@ -57,7 +57,8 @@ The module defines the following:
+---------+-------------------------------------------+ +---------+-------------------------------------------+
The optional *mode* argument is the Unix mode of the file, used only when the The optional *mode* argument is the Unix mode of the file, used only when the
database has to be created. It defaults to octal ``0666``. database has to be created. It defaults to octal ``0666`` (and will be
modified by the prevailing umask).
.. seealso:: .. seealso::

View File

@ -44,9 +44,9 @@ The :mod:`filecmp` module defines the following functions:
Example:: Example::
>>> import filecmp >>> import filecmp
>>> filecmp.cmp('libundoc.tex', 'libundoc.tex') >>> filecmp.cmp('undoc.rst', 'undoc.rst')
True True
>>> filecmp.cmp('libundoc.tex', 'lib.tex') >>> filecmp.cmp('undoc.rst', 'index.rst')
False False

View File

@ -34,14 +34,14 @@ Empty files are opened and immediately closed; the only time their presence in
the list of filenames is noticeable at all is when the last file opened is the list of filenames is noticeable at all is when the last file opened is
empty. empty.
It is possible that the last line of a file does not end in a newline character; Lines are returned with any newlines intact, which means that the last line in
lines are returned including the trailing newline when it is present. a file may not have one.
You can control how files are opened by providing an opening hook via the You can control how files are opened by providing an opening hook via the
*openhook* parameter to :func:`input` or :class:`FileInput()`. The hook must be *openhook* parameter to :func:`fileinput.input` or :class:`FileInput()`. The
a function that takes two arguments, *filename* and *mode*, and returns an hook must be a function that takes two arguments, *filename* and *mode*, and
accordingly opened file-like object. Two useful hooks are already provided by returns an accordingly opened file-like object. Two useful hooks are already
this module. provided by this module.
The following function is the primary interface of this module: The following function is the primary interface of this module:
@ -56,8 +56,8 @@ The following function is the primary interface of this module:
.. versionchanged:: 2.5 .. versionchanged:: 2.5
Added the *mode* and *openhook* parameters. Added the *mode* and *openhook* parameters.
The following functions use the global state created by :func:`input`; if there The following functions use the global state created by :func:`fileinput.input`;
is no active state, :exc:`RuntimeError` is raised. if there is no active state, :exc:`RuntimeError` is raised.
.. function:: filename() .. function:: filename()
@ -121,7 +121,7 @@ available for subclassing as well:
.. class:: FileInput([files[, inplace[, backup[, mode[, openhook]]]]]) .. class:: FileInput([files[, inplace[, backup[, mode[, openhook]]]]])
Class :class:`FileInput` is the implementation; its methods :meth:`filename`, Class :class:`FileInput` is the implementation; its methods :meth:`filename`,
:meth:`fileno`, :meth:`lineno`, :meth:`fileline`, :meth:`isfirstline`, :meth:`fileno`, :meth:`lineno`, :meth:`filelineno`, :meth:`isfirstline`,
:meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the functions :meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the functions
of the same name in the module. In addition it has a :meth:`readline` method of the same name in the module. In addition it has a :meth:`readline` method
which returns the next input line, and a :meth:`__getitem__` method which which returns the next input line, and a :meth:`__getitem__` method which
@ -139,14 +139,15 @@ available for subclassing as well:
Added the *mode* and *openhook* parameters. Added the *mode* and *openhook* parameters.
**Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed **Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed
to :func:`input` or to the :class:`FileInput` constructor, the file is moved to to :func:`fileinput.input` or to the :class:`FileInput` constructor, the file is
a backup file and standard output is directed to the input file (if a file of moved to a backup file and standard output is directed to the input file (if a
the same name as the backup file already exists, it will be replaced silently). file of the same name as the backup file already exists, it will be replaced
This makes it possible to write a filter that rewrites its input file in place. silently). This makes it possible to write a filter that rewrites its input
If the keyword argument ``backup='.<some extension>'`` is also given, it file in place. If the *backup* parameter is given (typically as
specifies the extension for the backup file, and the backup file remains around; ``backup='.<some extension>'``), it specifies the extension for the backup file,
by default, the extension is ``'.bak'`` and it is deleted when the output file and the backup file remains around; by default, the extension is ``'.bak'`` and
is closed. In-place filtering is disabled when standard input is read. it is deleted when the output file is closed. In-place filtering is disabled
when standard input is read.
**Caveat:** The current implementation does not work for MS-DOS 8+3 filesystems. **Caveat:** The current implementation does not work for MS-DOS 8+3 filesystems.

View File

@ -119,19 +119,19 @@ The :mod:`functools` module defines the following function:
have three read-only attributes: have three read-only attributes:
.. attribute:: callable.func .. attribute:: partial.func
A callable object or function. Calls to the :class:`partial` object will be A callable object or function. Calls to the :class:`partial` object will be
forwarded to :attr:`func` with new arguments and keywords. forwarded to :attr:`func` with new arguments and keywords.
.. attribute:: tuple.args .. attribute:: partial.args
The leftmost positional arguments that will be prepended to the positional The leftmost positional arguments that will be prepended to the positional
arguments provided to a :class:`partial` object call. arguments provided to a :class:`partial` object call.
.. attribute:: dict.keywords .. attribute:: partial.keywords
The keyword arguments that will be supplied when the :class:`partial` object is The keyword arguments that will be supplied when the :class:`partial` object is
called. called.

View File

@ -32,24 +32,42 @@ The module defines the following constant and functions:
Open a ``gdbm`` database and return a ``gdbm`` object. The *filename* argument Open a ``gdbm`` database and return a ``gdbm`` object. The *filename* argument
is the name of the database file. is the name of the database file.
The optional *flag* argument can be ``'r'`` (to open an existing database for The optional *flag* argument can be:
reading only --- default), ``'w'`` (to open an existing database for reading and
writing), ``'c'`` (which creates the database if it doesn't exist), or ``'n'``
(which always creates a new empty database).
The following additional characters may be appended to the flag to control how +---------+-------------------------------------------+
the database is opened: | Value | Meaning |
+=========+===========================================+
| ``'r'`` | Open existing database for reading only |
| | (default) |
+---------+-------------------------------------------+
| ``'w'`` | Open existing database for reading and |
| | writing |
+---------+-------------------------------------------+
| ``'c'`` | Open database for reading and writing, |
| | creating it if it doesn't exist |
+---------+-------------------------------------------+
| ``'n'`` | Always create a new, empty database, open |
| | for reading and writing |
+---------+-------------------------------------------+
* ``'f'`` --- Open the database in fast mode. Writes to the database will not The following additional characters may be appended to the flag to control
be synchronized. how the database is opened:
* ``'s'`` --- Synchronized mode. This will cause changes to the database will be +---------+--------------------------------------------+
immediately written to the file. | Value | Meaning |
+=========+============================================+
* ``'u'`` --- Do not lock database. | ``'f'`` | Open the database in fast mode. Writes |
| | to the database will not be synchronized. |
+---------+--------------------------------------------+
| ``'s'`` | Synchronized mode. This will cause changes |
| | to the database to be immediately written |
| | to the file. |
+---------+--------------------------------------------+
| ``'u'`` | Do not lock database. |
+---------+--------------------------------------------+
Not all flags are valid for all versions of ``gdbm``. The module constant Not all flags are valid for all versions of ``gdbm``. The module constant
``open_flags`` is a string of supported flag characters. The exception :const:`open_flags` is a string of supported flag characters. The exception
:exc:`error` is raised if an invalid flag is specified. :exc:`error` is raised if an invalid flag is specified.
The optional *mode* argument is the Unix mode of the file, used only when the The optional *mode* argument is the Unix mode of the file, used only when the

View File

@ -311,7 +311,7 @@ loops that truncate the stream.
If one of the iterables is potentially infinite, then the :func:`izip_longest` If one of the iterables is potentially infinite, then the :func:`izip_longest`
function should be wrapped with something that limits the number of calls (for function should be wrapped with something that limits the number of calls (for
example :func:`islice` or :func:`take`). example :func:`islice` or :func:`takewhile`).
.. versionadded:: 2.6 .. versionadded:: 2.6
@ -414,7 +414,7 @@ can be combined. ::
64 64
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
'', 'martin', '', 'walter', '', 'mark'] ... '', 'martin', '', 'walter', '', 'mark']
>>> for name in islice(reportlines, 3, None, 2): >>> for name in islice(reportlines, 3, None, 2):
... print name.title() ... print name.title()
... ...

View File

@ -30,8 +30,8 @@ de-serializing Python objects, use the :mod:`pickle` module instead.
.. warning:: .. warning::
The :mod:`marshal` module is not intended to be secure against erroneous or The :mod:`marshal` module is not intended to be secure against erroneous or
maliciously constructed data. Never unmarshal data received from an untrusted maliciously constructed data. Never unmarshal data received from an
or unauthenticated source. untrusted or unauthenticated source.
Not all Python object types are supported; in general, only objects whose value Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by is independent from a particular invocation of Python can be written and read by
@ -59,25 +59,27 @@ The module defines these functions:
.. function:: dump(value, file[, version]) .. function:: dump(value, file[, version])
Write the value on the open file. The value must be a supported type. The file Write the value on the open file. The value must be a supported type. The
must be an open file object such as ``sys.stdout`` or returned by :func:`open` file must be an open file object such as ``sys.stdout`` or returned by
or :func:`posix.popen`. It must be opened in binary mode (``'wb'`` or :func:`open` or :func:`os.popen`. It must be opened in binary mode (``'wb'``
``'w+b'``). or ``'w+b'``).
If the value has (or contains an object that has) an unsupported type, a If the value has (or contains an object that has) an unsupported type, a
:exc:`ValueError` exception is raised --- but garbage data will also be written :exc:`ValueError` exception is raised --- but garbage data will also be written
to the file. The object will not be properly read back by :func:`load`. to the file. The object will not be properly read back by :func:`load`.
.. versionadded:: 2.4 .. versionadded:: 2.4
The *version* argument indicates the data format that ``dump`` should use (see The *version* argument indicates the data format that ``dump`` should use
below). (see below).
.. function:: load(file) .. function:: load(file)
Read one value from the open file and return it. If no valid value is read, Read one value from the open file and return it. If no valid value is read
raise :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. The file must be (e.g. because the data has a different Python version's incompatible marshal
an open file object opened in binary mode (``'rb'`` or ``'r+b'``). format), raise :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. The
file must be an open file object opened in binary mode (``'rb'`` or
``'r+b'``).
.. warning:: .. warning::
@ -92,8 +94,8 @@ The module defines these functions:
has (or contains an object that has) an unsupported type. has (or contains an object that has) an unsupported type.
.. versionadded:: 2.4 .. versionadded:: 2.4
The *version* argument indicates the data format that ``dumps`` should use (see The *version* argument indicates the data format that ``dumps`` should use
below). (see below).
.. function:: loads(string) .. function:: loads(string)
@ -102,8 +104,8 @@ The module defines these functions:
:exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. Extra characters in the :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`. Extra characters in the
string are ignored. string are ignored.
In addition, the following constants are defined:
In addition, the following constants are defined:
.. data:: version .. data:: version
@ -114,6 +116,7 @@ In addition, the following constants are defined:
.. versionadded:: 2.4 .. versionadded:: 2.4
.. rubric:: Footnotes .. rubric:: Footnotes
.. [#] The name of this module stems from a bit of terminology used by the designers of .. [#] The name of this module stems from a bit of terminology used by the designers of

View File

@ -118,7 +118,9 @@ The mathematical and bitwise operations are the most numerous:
__invert__(o) __invert__(o)
Return the bitwise inverse of the number *o*. This is equivalent to ``~o``. Return the bitwise inverse of the number *o*. This is equivalent to ``~o``.
The names :func:`invert` and :func:`__invert__` were added in Python 2.0.
.. versionadded:: 2.0
The names :func:`invert` and :func:`__invert__`.
.. function:: lshift(a, b) .. function:: lshift(a, b)
@ -199,8 +201,8 @@ The mathematical and bitwise operations are the most numerous:
.. versionadded:: 2.5 .. versionadded:: 2.5
Operations which work with sequences include:
Operations which work with sequences include:
.. function:: concat(a, b) .. function:: concat(a, b)
__concat__(a, b) __concat__(a, b)
@ -211,8 +213,10 @@ Operations which work with sequences include:
.. function:: contains(a, b) .. function:: contains(a, b)
__contains__(a, b) __contains__(a, b)
Return the outcome of the test ``b in a``. Note the reversed operands. The Return the outcome of the test ``b in a``. Note the reversed operands.
name :func:`__contains__` was added in Python 2.0.
.. versionadded:: 2.0
The name :func:`__contains__`.
.. function:: countOf(a, b) .. function:: countOf(a, b)
@ -477,6 +481,8 @@ their character equivalents. ::
>>> vals = map(chr, keys) >>> vals = map(chr, keys)
>>> map(operator.setitem, [d]*len(keys), keys, vals) >>> map(operator.setitem, [d]*len(keys), keys, vals)
.. XXX: find a better, readable, example
The :mod:`operator` module also defines tools for generalized attribute and item The :mod:`operator` module also defines tools for generalized attribute and item
lookups. These are useful for making fast field extractors as arguments for lookups. These are useful for making fast field extractors as arguments for
:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that :func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
@ -537,11 +543,11 @@ Python syntax and the functions in the :mod:`operator` module.
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Containment Test | ``o in seq`` | ``contains(seq, o)`` | | Containment Test | ``o in seq`` | ``contains(seq, o)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Division | ``a / b`` | ``div(a, b) #`` without | | Division | ``a / b`` | ``div(a, b)`` (without |
| | | ``__future__.division`` | | | | ``__future__.division``) |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Division | ``a / b`` | ``truediv(a, b) #`` with | | Division | ``a / b`` | ``truediv(a, b)`` (with |
| | | ``__future__.division`` | | | | ``__future__.division``) |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Division | ``a // b`` | ``floordiv(a, b)`` | | Division | ``a // b`` | ``floordiv(a, b)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
@ -579,7 +585,7 @@ Python syntax and the functions in the :mod:`operator` module.
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` | | Sequence Repitition | ``seq * i`` | ``repeat(seq, i)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Slice Assignment | ``seq[i:j]`` = *values* | ``setslice(seq, i, j, values)`` | | Slice Assignment | ``seq[i:j] = values`` | ``setslice(seq, i, j, values)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+
| Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` | | Slice Deletion | ``del seq[i:j]`` | ``delslice(seq, i, j)`` |
+-----------------------+-------------------------+---------------------------------+ +-----------------------+-------------------------+---------------------------------+

View File

@ -182,7 +182,7 @@ write files see :func:`open`, and for accessing the filesystem see the
the concatenation of *path1*, and optionally *path2*, etc., with exactly one the concatenation of *path1*, and optionally *path2*, etc., with exactly one
directory separator (``os.sep``) inserted between components, unless *path2* is directory separator (``os.sep``) inserted between components, unless *path2* is
empty. Note that on Windows, since there is a current directory for each drive, empty. Note that on Windows, since there is a current directory for each drive,
:func:`os.path.join("c:", "foo")` represents a path relative to the current ``os.path.join("c:", "foo")`` represents a path relative to the current
directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`. directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.
@ -267,12 +267,12 @@ write files see :func:`open`, and for accessing the filesystem see the
Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext == Split the pathname *path* into a pair ``(root, ext)`` such that ``root + ext ==
path``, and *ext* is empty or begins with a period and contains at most one path``, and *ext* is empty or begins with a period and contains at most one
period. Leading periods on the basename are ignored; ``splitext.('.cshrc')`` period. Leading periods on the basename are ignored; ``splitext('.cshrc')``
returns ``('.cshrc', '')``. returns ``('.cshrc', '')``.
.. versionchanged:: 2.6 .. versionchanged:: 2.6
Earlier versions could produce an empty root when the only period was the first Earlier versions could produce an empty root when the only period was the
character. first character.
.. function:: splitunc(path) .. function:: splitunc(path)

View File

@ -124,7 +124,7 @@ There are currently 3 different protocols which can be used for pickling.
* Protocol version 2 was introduced in Python 2.3. It provides much more * Protocol version 2 was introduced in Python 2.3. It provides much more
efficient pickling of new-style classes. efficient pickling of new-style classes.
Refer to PEP 307 for more information. Refer to :pep:`307` for more information.
If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified
as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version
@ -249,7 +249,8 @@ The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
This takes a file-like object to which it will write a pickle data stream. This takes a file-like object to which it will write a pickle data stream.
If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
specified as a negative value, the highest protocol version will be used. specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest
protocol version will be used.
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Introduced the *protocol* parameter. Introduced the *protocol* parameter.
@ -317,6 +318,9 @@ instance. If the same object is pickled by multiple :meth:`dump` calls, the
Read a pickled object representation from the open file object given in the Read a pickled object representation from the open file object given in the
constructor, and return the reconstituted object hierarchy specified therein. constructor, and return the reconstituted object hierarchy specified therein.
This method automatically determines whether the data stream was written in
binary mode or not.
.. method:: Unpickler.noload() .. method:: Unpickler.noload()
@ -713,6 +717,8 @@ member are saved. When the instance is unpickled, the file is reopened, and
reading resumes from the last location. The :meth:`__setstate__` and reading resumes from the last location. The :meth:`__setstate__` and
:meth:`__getstate__` methods are used to implement this behavior. :: :meth:`__getstate__` methods are used to implement this behavior. ::
#!/usr/local/bin/python
class TextReader: class TextReader:
"""Print and number lines in a text file.""" """Print and number lines in a text file."""
def __init__(self, file): def __init__(self, file):
@ -749,11 +755,12 @@ A sample usage might be something like this::
>>> obj = TextReader.TextReader("TextReader.py") >>> obj = TextReader.TextReader("TextReader.py")
>>> obj.readline() >>> obj.readline()
'1: #!/usr/local/bin/python' '1: #!/usr/local/bin/python'
>>> # (more invocations of obj.readline() here) >>> obj.readline()
... obj.readline() '2: '
'7: class TextReader:' >>> obj.readline()
'3: class TextReader:'
>>> import pickle >>> import pickle
>>> pickle.dump(obj,open('save.p', 'wb')) >>> pickle.dump(obj, open('save.p', 'wb'))
If you want to see that :mod:`pickle` works across Python processes, start If you want to see that :mod:`pickle` works across Python processes, start
another Python session, before continuing. What follows can happen from either another Python session, before continuing. What follows can happen from either
@ -762,7 +769,7 @@ the same process or a new process. ::
>>> import pickle >>> import pickle
>>> reader = pickle.load(open('save.p', 'rb')) >>> reader = pickle.load(open('save.p', 'rb'))
>>> reader.readline() >>> reader.readline()
'8: "Print and number lines in a text file."' '4: """Print and number lines in a text file."""'
.. seealso:: .. seealso::

View File

@ -103,7 +103,7 @@ Bookkeeping functions:
.. versionadded:: 2.1 .. versionadded:: 2.1
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Instead of jumping to a specific state, *n* steps ahead, :meth:`jumpahead(n)` Instead of jumping to a specific state, *n* steps ahead, ``jumpahead(n)``
jumps to another state likely to be separated by many steps. jumps to another state likely to be separated by many steps.
@ -185,7 +185,7 @@ be found in any statistics text.
.. function:: uniform(a, b) .. function:: uniform(a, b)
Return a random real number *N* such that ``a <= N < b``. Return a random floating point number *N* such that ``a <= N < b``.
.. function:: betavariate(alpha, beta) .. function:: betavariate(alpha, beta)
@ -228,10 +228,10 @@ be found in any statistics text.
.. function:: vonmisesvariate(mu, kappa) .. function:: vonmisesvariate(mu, kappa)
*mu* is the mean angle, expressed in radians between 0 and 2\**pi*, and *kappa* *mu* is the mean angle, expressed in radians between 0 and 2\*\ *pi*, and *kappa*
is the concentration parameter, which must be greater than or equal to zero. If is the concentration parameter, which must be greater than or equal to zero. If
*kappa* is equal to zero, this distribution reduces to a uniform random angle *kappa* is equal to zero, this distribution reduces to a uniform random angle
over the range 0 to 2\**pi*. over the range 0 to 2\*\ *pi*.
.. function:: paretovariate(alpha) .. function:: paretovariate(alpha)
@ -244,8 +244,8 @@ be found in any statistics text.
Weibull distribution. *alpha* is the scale parameter and *beta* is the shape Weibull distribution. *alpha* is the scale parameter and *beta* is the shape
parameter. parameter.
Alternative Generators:
Alternative Generators:
.. class:: WichmannHill([seed]) .. class:: WichmannHill([seed])

View File

@ -66,7 +66,7 @@ codes will not be correct.
.. function:: copy2(src, dst) .. function:: copy2(src, dst)
Similar to :func:`copy`, but last access time and last modification time are Similar to :func:`copy`, but last access time and last modification time are
copied as well. This is similar to the Unix command :program:`cp` :option:`-p`. copied as well. This is similar to the Unix command :program:`cp -p`.
.. function:: copytree(src, dst[, symlinks]) .. function:: copytree(src, dst[, symlinks])
@ -137,9 +137,10 @@ This example is the implementation of the :func:`copytree` function, described
above, with the docstring omitted. It demonstrates many of the other functions above, with the docstring omitted. It demonstrates many of the other functions
provided by this module. :: provided by this module. ::
def copytree(src, dst, symlinks=0): def copytree(src, dst, symlinks=False):
names = os.listdir(src) names = os.listdir(src)
os.mkdir(dst) os.makedirs(dst)
errors = []
for name in names: for name in names:
srcname = os.path.join(src, name) srcname = os.path.join(src, name)
dstname = os.path.join(dst, name) dstname = os.path.join(dst, name)
@ -151,6 +152,20 @@ provided by this module. ::
copytree(srcname, dstname, symlinks) copytree(srcname, dstname, symlinks)
else: else:
copy2(srcname, dstname) copy2(srcname, dstname)
# XXX What about devices, sockets etc.?
except (IOError, os.error) as why: except (IOError, os.error) as why:
print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why)) errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error as err:
errors.extend(err.args[0])
try:
copystat(src, dst)
except WindowsError:
# can't copy file access times on Windows
pass
except OSError as why:
errors.extend((src, dst, str(why)))
if errors:
raise Error, errors

View File

@ -81,12 +81,13 @@ The module defines the following user-callable functions:
.. function:: mkstemp([suffix[, prefix[, dir[, text]]]]) .. function:: mkstemp([suffix[, prefix[, dir[, text]]]])
Creates a temporary file in the most secure manner possible. There are no race Creates a temporary file in the most secure manner possible. There are no
conditions in the file's creation, assuming that the platform properly race conditions in the file's creation, assuming that the platform properly
implements the :const:`O_EXCL` flag for :func:`os.open`. The file is readable implements the :const:`os.O_EXCL` flag for :func:`os.open`. The file is
and writable only by the creating user ID. If the platform uses permission bits readable and writable only by the creating user ID. If the platform uses
to indicate whether a file is executable, the file is executable by no one. The permission bits to indicate whether a file is executable, the file is
file descriptor is not inherited by child processes. executable by no one. The file descriptor is not inherited by child
processes.
Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible for Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible for
deleting the temporary file when done with it. deleting the temporary file when done with it.
@ -173,7 +174,7 @@ function arguments, instead.
* On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment * On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment
variable. variable.
* On Windows, the directories :file:`C:$\\TEMP`, :file:`C:$\\TMP`, * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
:file:`\\TEMP`, and :file:`\\TMP`, in that order. :file:`\\TEMP`, and :file:`\\TMP`, in that order.
* On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
@ -185,8 +186,8 @@ function arguments, instead.
.. function:: gettempdir() .. function:: gettempdir()
Return the directory currently selected to create temporary files in. If Return the directory currently selected to create temporary files in. If
``tempdir`` is not ``None``, this simply returns its contents; otherwise, the :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
search described above is performed, and the result returned. the search described above is performed, and the result returned.
.. data:: template .. data:: template

1
TODO
View File

@ -9,3 +9,4 @@ Global TODO
- look at the old tools/ scripts, what functionality should be rewritten - look at the old tools/ scripts, what functionality should be rewritten
- add search via Xapian? - add search via Xapian?
- optionally have a contents tree view in the sidebar (AJAX based)? - optionally have a contents tree view in the sidebar (AJAX based)?
- .. caveat?