Merged revisions 73941-73943,74076,74094,74186,74211-74214,74247,74254,74262,74311,74334,74368 via svnmerge from

svn+ssh://svn.python.org/python/branches/py3k

................
  r73941 | georg.brandl | 2009-07-11 12:39:00 +0200 (Sa, 11 Jul 2009) | 9 lines

  Merged revisions 73940 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r73940 | georg.brandl | 2009-07-11 12:37:38 +0200 (Sa, 11 Jul 2009) | 1 line

    #6430: add note about size of "u" type.
  ........
................
  r73942 | georg.brandl | 2009-07-11 12:39:23 +0200 (Sa, 11 Jul 2009) | 1 line

  #6430: remove mention of "w" array typecode.
................
  r73943 | georg.brandl | 2009-07-11 12:43:08 +0200 (Sa, 11 Jul 2009) | 1 line

  #6421: The self argument of module-level PyCFunctions is now a reference to the module object.
................
  r74076 | georg.brandl | 2009-07-18 11:07:48 +0200 (Sa, 18 Jul 2009) | 1 line

  #6502: add missing comma in docstring.
................
  r74094 | georg.brandl | 2009-07-19 09:25:56 +0200 (So, 19 Jul 2009) | 10 lines

  Recorded merge of revisions 74089 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74089 | senthil.kumaran | 2009-07-19 04:43:43 +0200 (So, 19 Jul 2009) | 3 lines

    Fix for issue5102, timeout value propages between redirects, proxy, digest and
    auth handlers. Fixed tests to reflect the same.
  ........
................
  r74186 | georg.brandl | 2009-07-23 11:19:09 +0200 (Do, 23 Jul 2009) | 9 lines

  Recorded merge of revisions 74185 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74185 | georg.brandl | 2009-07-23 11:17:09 +0200 (Do, 23 Jul 2009) | 1 line

    Fix the "pylocals" gdb command.
  ........
................
  r74211 | georg.brandl | 2009-07-26 16:48:09 +0200 (So, 26 Jul 2009) | 9 lines

  Recorded merge of revisions 74210 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74210 | georg.brandl | 2009-07-26 16:44:23 +0200 (So, 26 Jul 2009) | 1 line

    Move member descriptions inside the classes.
  ........
................
  r74212 | georg.brandl | 2009-07-26 16:54:51 +0200 (So, 26 Jul 2009) | 9 lines

  Merged revisions 74209 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74209 | georg.brandl | 2009-07-26 16:37:28 +0200 (So, 26 Jul 2009) | 1 line

    builtin -> built-in.
  ........
................
  r74213 | georg.brandl | 2009-07-26 17:02:41 +0200 (So, 26 Jul 2009) | 9 lines

  Merged revisions 74207 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74207 | georg.brandl | 2009-07-26 16:19:57 +0200 (So, 26 Jul 2009) | 1 line

    #6577: fix (hopefully) all links to builtin instead of module/class-specific objects.
  ........
................
  r74214 | georg.brandl | 2009-07-26 17:03:49 +0200 (So, 26 Jul 2009) | 9 lines

  Merged revisions 74205 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74205 | georg.brandl | 2009-07-26 15:36:39 +0200 (So, 26 Jul 2009) | 1 line

    #6576: fix cross-refs in re docs.
  ........
................
  r74247 | georg.brandl | 2009-07-29 09:27:08 +0200 (Mi, 29 Jul 2009) | 9 lines

  Merged revisions 74239 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74239 | georg.brandl | 2009-07-28 18:55:32 +0000 (Di, 28 Jul 2009) | 1 line

    Clarify quote_plus() usage.
  ........
................
  r74254 | georg.brandl | 2009-07-29 18:14:16 +0200 (Mi, 29 Jul 2009) | 1 line

  #6586: fix return/argument type doc for os.read() and os.write().
................
  r74262 | alexandre.vassalotti | 2009-07-29 21:54:39 +0200 (Mi, 29 Jul 2009) | 57 lines

  Merged revisions 74074,74077,74111,74188,74192-74193,74200,74252-74253,74258-74261 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74074 | georg.brandl | 2009-07-18 05:03:10 -0400 (Sat, 18 Jul 2009) | 1 line

    #6513: fix example code: warning categories are classes, not instances.
  ........
    r74077 | georg.brandl | 2009-07-18 05:43:40 -0400 (Sat, 18 Jul 2009) | 1 line

    #6489: fix an ambiguity in getiterator() documentation.
  ........
    r74111 | benjamin.peterson | 2009-07-20 09:30:10 -0400 (Mon, 20 Jul 2009) | 1 line

    remove docs for deprecated -p option
  ........
    r74188 | benjamin.peterson | 2009-07-23 10:25:31 -0400 (Thu, 23 Jul 2009) | 1 line

    use bools
  ........
    r74192 | georg.brandl | 2009-07-24 12:28:38 -0400 (Fri, 24 Jul 2009) | 1 line

    Fix arg types of et#.
  ........
    r74193 | georg.brandl | 2009-07-24 12:46:38 -0400 (Fri, 24 Jul 2009) | 1 line

    Dont put "void" in signature for nullary functions.
  ........
    r74200 | georg.brandl | 2009-07-25 09:02:15 -0400 (Sat, 25 Jul 2009) | 1 line

    #6571: add index entries for more operators.
  ........
    r74252 | georg.brandl | 2009-07-29 12:06:31 -0400 (Wed, 29 Jul 2009) | 1 line

    #6593: fix link targets.
  ........
    r74253 | georg.brandl | 2009-07-29 12:09:17 -0400 (Wed, 29 Jul 2009) | 1 line

    #6591: add reference to ioctl in fcntl module for platforms other than Windows.
  ........
    r74258 | georg.brandl | 2009-07-29 12:57:05 -0400 (Wed, 29 Jul 2009) | 1 line

    Add a link to readline, and mention IPython and bpython.
  ........
    r74259 | georg.brandl | 2009-07-29 13:07:21 -0400 (Wed, 29 Jul 2009) | 1 line

    Fix some markup and small factual glitches found by M. Markert.
  ........
    r74260 | georg.brandl | 2009-07-29 13:15:20 -0400 (Wed, 29 Jul 2009) | 1 line

    Fix a few markup glitches.
  ........
    r74261 | georg.brandl | 2009-07-29 13:50:25 -0400 (Wed, 29 Jul 2009) | 1 line

    Rewrite the section about classes a bit; mostly tidbits, and a larger update to the section about "private" variables to reflect the Pythonic consensus better.
  ........
................
  r74311 | georg.brandl | 2009-08-04 22:29:27 +0200 (Di, 04 Aug 2009) | 1 line

  Slightly improve buffer-related error message.
................
  r74334 | georg.brandl | 2009-08-06 19:51:03 +0200 (Do, 06 Aug 2009) | 1 line

  #6648: mention surrogateescape handler where all standard handlers are listed.
................
  r74368 | georg.brandl | 2009-08-13 09:56:35 +0200 (Do, 13 Aug 2009) | 21 lines

  Merged revisions 74328,74332-74333,74365 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r74328 | georg.brandl | 2009-08-06 17:06:25 +0200 (Do, 06 Aug 2009) | 1 line

    Fix base keyword arg name for int() and long().
  ........
    r74332 | georg.brandl | 2009-08-06 19:23:21 +0200 (Do, 06 Aug 2009) | 1 line

    Fix punctuation and one copy-paste error.
  ........
    r74333 | georg.brandl | 2009-08-06 19:43:55 +0200 (Do, 06 Aug 2009) | 1 line

    #6658: fix two typos.
  ........
    r74365 | georg.brandl | 2009-08-13 09:48:05 +0200 (Do, 13 Aug 2009) | 1 line

    #6679: Remove mention that sub supports no flags.
  ........
................
This commit is contained in:
Georg Brandl 2009-08-13 08:26:44 +00:00
parent 084605518d
commit c5605dffdb
84 changed files with 536 additions and 535 deletions

View file

@ -160,7 +160,7 @@ variable(s) whose address should be passed.
In both cases, *\*buffer_length* is set to the length of the encoded data In both cases, *\*buffer_length* is set to the length of the encoded data
without the trailing NUL byte. without the trailing NUL byte.
``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer] ``et#`` (string, Unicode object or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
Same as ``es#`` except that string objects are passed through without recoding Same as ``es#`` except that string objects are passed through without recoding
them. Instead, the implementation assumes that the string object uses the them. Instead, the implementation assumes that the string object uses the
encoding passed in as parameter. encoding passed in as parameter.

View file

@ -144,7 +144,7 @@ Buffer related functions
kind of buffer the caller is prepared to deal with and therefore what kind of buffer the caller is prepared to deal with and therefore what
kind of buffer the exporter is allowed to return. The buffer interface kind of buffer the exporter is allowed to return. The buffer interface
allows for complicated memory sharing possibilities, but some caller may allows for complicated memory sharing possibilities, but some caller may
not be able to handle all the complexibity but may want to see if the not be able to handle all the complexity but may want to see if the
exporter will let them take a simpler view to its memory. exporter will let them take a simpler view to its memory.
Some exporters may not be able to share memory in every possible way and Some exporters may not be able to share memory in every possible way and

View file

@ -64,16 +64,16 @@ Floating Point Objects
around the header file :file:`float.h`. around the header file :file:`float.h`.
.. cfunction:: double PyFloat_GetMax(void) .. cfunction:: double PyFloat_GetMax()
Return the maximum representable finite float *DBL_MAX* as C :ctype:`double`. Return the maximum representable finite float *DBL_MAX* as C :ctype:`double`.
.. cfunction:: double PyFloat_GetMin(void) .. cfunction:: double PyFloat_GetMin()
Return the minimum normalized positive float *DBL_MIN* as C :ctype:`double`. Return the minimum normalized positive float *DBL_MIN* as C :ctype:`double`.
.. cfunction:: int PyFloat_ClearFreeList(void) .. cfunction:: int PyFloat_ClearFreeList()
Clear the float free list. Return the number of items that could not Clear the float free list. Return the number of items that could not
be freed. be freed.

View file

@ -137,7 +137,7 @@ Importing Modules
*path*, possibly by fetching it from the :data:`sys.path_importer_cache` *path*, possibly by fetching it from the :data:`sys.path_importer_cache`
dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook
is found that can handle the path item. Return ``None`` if no hook could; is found that can handle the path item. Return ``None`` if no hook could;
this tells our caller it should fall back to the builtin import mechanism. this tells our caller it should fall back to the built-in import mechanism.
Cache the result in :data:`sys.path_importer_cache`. Return a new reference Cache the result in :data:`sys.path_importer_cache`. Return a new reference
to the importer object. to the importer object.

View file

@ -94,7 +94,7 @@ no longer available.
Macro version of :cfunc:`PyMethod_Self` which avoids error checking. Macro version of :cfunc:`PyMethod_Self` which avoids error checking.
.. cfunction:: int PyMethod_ClearFreeList(void) .. cfunction:: int PyMethod_ClearFreeList()
Clear the free list. Return the total number of freed items. Clear the free list. Return the total number of freed items.

View file

@ -146,12 +146,10 @@ convention flags can be combined with a binding flag.
This is the typical calling convention, where the methods have the type This is the typical calling convention, where the methods have the type
:ctype:`PyCFunction`. The function expects two :ctype:`PyObject\*` values. :ctype:`PyCFunction`. The function expects two :ctype:`PyObject\*` values.
The first one is the *self* object for methods; for module functions, it The first one is the *self* object for methods; for module functions, it is
has the value given to :cfunc:`Py_InitModule4` (or *NULL* if the module object. The second parameter (often called *args*) is a tuple
:cfunc:`Py_InitModule` was used). The second parameter (often called object representing all arguments. This parameter is typically processed
*args*) is a tuple object representing all arguments. This parameter is using :cfunc:`PyArg_ParseTuple` or :cfunc:`PyArg_UnpackTuple`.
typically processed using :cfunc:`PyArg_ParseTuple` or
:cfunc:`PyArg_UnpackTuple`.
.. data:: METH_KEYWORDS .. data:: METH_KEYWORDS
@ -167,9 +165,9 @@ convention flags can be combined with a binding flag.
Methods without parameters don't need to check whether arguments are given if Methods without parameters don't need to check whether arguments are given if
they are listed with the :const:`METH_NOARGS` flag. They need to be of type they are listed with the :const:`METH_NOARGS` flag. They need to be of type
:ctype:`PyCFunction`. When used with object methods, the first parameter is :ctype:`PyCFunction`. The first parameter is typically named *self* and will
typically named ``self`` and will hold a reference to the object instance. hold a reference to the module or object instance. In all cases the second
In all cases the second parameter will be *NULL*. parameter will be *NULL*.
.. data:: METH_O .. data:: METH_O

View file

@ -73,7 +73,7 @@ accessible to C code. They all work with the current interpreter thread's
case *name* is deleted from the sys module. Returns ``0`` on success, ``-1`` case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
on error. on error.
.. cfunction:: void PySys_ResetWarnOptions(void) .. cfunction:: void PySys_ResetWarnOptions()
Reset :data:`sys.warnoptions` to an empty list. Reset :data:`sys.warnoptions` to an empty list.

View file

@ -107,6 +107,6 @@ Tuple Objects
raises :exc:`MemoryError` or :exc:`SystemError`. raises :exc:`MemoryError` or :exc:`SystemError`.
.. cfunction:: int PyTuple_ClearFreeList(void) .. cfunction:: int PyTuple_ClearFreeList()
Clear the free list. Return the total number of freed items. Clear the free list. Return the total number of freed items.

View file

@ -33,7 +33,7 @@ Type Objects
standard type object. Return false in all other cases. standard type object. Return false in all other cases.
.. cfunction:: unsigned int PyType_ClearCache(void) .. cfunction:: unsigned int PyType_ClearCache()
Clear the internal lookup cache. Return the current version tag. Clear the internal lookup cache. Return the current version tag.

View file

@ -84,10 +84,11 @@ access internal read-only data of Unicode objects:
:ctype:`PyUnicodeObject` (not checked). :ctype:`PyUnicodeObject` (not checked).
.. cfunction:: int PyUnicode_ClearFreeList(void) .. cfunction:: int PyUnicode_ClearFreeList()
Clear the free list. Return the total number of freed items. Clear the free list. Return the total number of freed items.
Unicode provides many different character properties. The most often needed ones Unicode provides many different character properties. The most often needed ones
are available through these macros which are mapped to C functions depending on are available through these macros which are mapped to C functions depending on
the Python configuration. the Python configuration.
@ -372,12 +373,12 @@ the system's :ctype:`wchar_t`.
Built-in Codecs Built-in Codecs
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
Python provides a set of builtin codecs which are written in C for speed. All of Python provides a set of built-in codecs which are written in C for speed. All of
these codecs are directly usable via the following functions. these codecs are directly usable via the following functions.
Many of the following APIs take two arguments encoding and errors. These Many of the following APIs take two arguments encoding and errors. These
parameters encoding and errors have the same semantics as the ones of the parameters encoding and errors have the same semantics as the ones of the
builtin unicode() Unicode object constructor. built-in :func:`unicode` Unicode object constructor.
Setting encoding to *NULL* causes the default encoding to be used Setting encoding to *NULL* causes the default encoding to be used
which is ASCII. The file system calls should use which is ASCII. The file system calls should use
@ -389,7 +390,7 @@ pointer to a static string, on others, it will change at run-time
Error handling is set by errors which may also be set to *NULL* meaning to use Error handling is set by errors which may also be set to *NULL* meaning to use
the default handling defined for the codec. Default error handling for all the default handling defined for the codec. Default error handling for all
builtin codecs is "strict" (:exc:`ValueError` is raised). built-in codecs is "strict" (:exc:`ValueError` is raised).
The codecs all use a similar interface. Only deviation from the following The codecs all use a similar interface. Only deviation from the following
generic ones are documented for simplicity. generic ones are documented for simplicity.
@ -403,7 +404,7 @@ These are the generic codec APIs:
Create a Unicode object by decoding *size* bytes of the encoded string *s*. Create a Unicode object by decoding *size* bytes of the encoded string *s*.
*encoding* and *errors* have the same meaning as the parameters of the same name *encoding* and *errors* have the same meaning as the parameters of the same name
in the :func:`unicode` builtin function. The codec to be used is looked up in the :func:`unicode` built-in function. The codec to be used is looked up
using the Python codec registry. Return *NULL* if an exception was raised by using the Python codec registry. Return *NULL* if an exception was raised by
the codec. the codec.

View file

@ -1601,7 +1601,7 @@ lines, and joining lines with backslashes.
+------------------+--------------------------------+---------+ +------------------+--------------------------------+---------+
Note that since *rstrip_ws* can strip the trailing newline, the semantics of Note that since *rstrip_ws* can strip the trailing newline, the semantics of
:meth:`readline` must differ from those of the builtin file object's :meth:`readline` must differ from those of the built-in file object's
:meth:`readline` method! In particular, :meth:`readline` returns ``None`` for :meth:`readline` method! In particular, :meth:`readline` returns ``None`` for
end-of-file: an empty string might just be a blank line (or an all-whitespace end-of-file: an empty string might just be a blank line (or an all-whitespace
line), if *rstrip_ws* is true but *skip_blanks* is not. line), if *rstrip_ws* is true but *skip_blanks* is not.
@ -1609,8 +1609,8 @@ lines, and joining lines with backslashes.
.. method:: TextFile.open(filename) .. method:: TextFile.open(filename)
Open a new file *filename*. This overrides any *file* or *filename* constructor Open a new file *filename*. This overrides any *file* or *filename*
arguments. constructor arguments.
.. method:: TextFile.close() .. method:: TextFile.close()

View file

@ -82,10 +82,8 @@ example, the single expression ``"ls -l"``) to the arguments passed to the C
function. The C function always has two arguments, conventionally named *self* function. The C function always has two arguments, conventionally named *self*
and *args*. and *args*.
The *self* argument is only used when the C function implements a built-in The *self* argument points to the module object for module-level functions;
method, not a function. In the example, *self* will always be a *NULL* pointer, for a method it would point to the object instance.
since we are defining a function, not a method. (This is done so that the
interpreter doesn't have to understand two different types of C functions.)
The *args* argument will be a pointer to a Python tuple object containing the The *args* argument will be a pointer to a Python tuple object containing the
arguments. Each item of the tuple corresponds to an argument in the call's arguments. Each item of the tuple corresponds to an argument in the call's

View file

@ -802,7 +802,7 @@ easily use the :class:`PyTypeObject` it needs. It can be difficult to share
these :class:`PyTypeObject` structures between extension modules. these :class:`PyTypeObject` structures between extension modules.
In this example we will create a :class:`Shoddy` type that inherits from the In this example we will create a :class:`Shoddy` type that inherits from the
builtin :class:`list` type. The new type will be completely compatible with built-in :class:`list` type. The new type will be completely compatible with
regular lists, but will have an additional :meth:`increment` method that regular lists, but will have an additional :meth:`increment` method that
increases an internal counter. :: increases an internal counter. ::

View file

@ -28,11 +28,11 @@ Glossary
abstract base class abstract base class
Abstract Base Classes (abbreviated ABCs) complement :term:`duck-typing` by Abstract Base Classes (abbreviated ABCs) complement :term:`duck-typing` by
providing a way to define interfaces when other techniques like :func:`hasattr` providing a way to define interfaces when other techniques like
would be clumsy. Python comes with many builtin ABCs for data structures :func:`hasattr` would be clumsy. Python comes with many built-in ABCs for
(in the :mod:`collections` module), numbers (in the :mod:`numbers` data structures (in the :mod:`collections` module), numbers (in the
module), and streams (in the :mod:`io` module). You can create your own :mod:`numbers` module), and streams (in the :mod:`io` module). You can
ABC with the :mod:`abc` module. create your own ABC with the :mod:`abc` module.
argument argument
A value passed to a function or method, assigned to a named local A value passed to a function or method, assigned to a named local
@ -83,7 +83,7 @@ Glossary
expressed as a sum of a real part and an imaginary part. Imaginary expressed as a sum of a real part and an imaginary part. Imaginary
numbers are real multiples of the imaginary unit (the square root of numbers are real multiples of the imaginary unit (the square root of
``-1``), often written ``i`` in mathematics or ``j`` in ``-1``), often written ``i`` in mathematics or ``j`` in
engineering. Python has builtin support for complex numbers, which are engineering. Python has built-in support for complex numbers, which are
written with this latter notation; the imaginary part is written with a written with this latter notation; the imaginary part is written with a
``j`` suffix, e.g., ``3+1j``. To get access to complex equivalents of the ``j`` suffix, e.g., ``3+1j``. To get access to complex equivalents of the
:mod:`math` module, use :mod:`cmath`. Use of complex numbers is a fairly :mod:`math` module, use :mod:`cmath`. Use of complex numbers is a fairly
@ -305,7 +305,7 @@ Glossary
define with an :meth:`__iter__` or :meth:`__getitem__` method. Iterables define with an :meth:`__iter__` or :meth:`__getitem__` method. Iterables
can be used in a :keyword:`for` loop and in many other places where a can be used in a :keyword:`for` loop and in many other places where a
sequence is needed (:func:`zip`, :func:`map`, ...). When an iterable sequence is needed (:func:`zip`, :func:`map`, ...). When an iterable
object is passed as an argument to the builtin function :func:`iter`, it object is passed as an argument to the built-in function :func:`iter`, it
returns an iterator for the object. This iterator is good for one pass returns an iterator for the object. This iterator is good for one pass
over the set of values. When using iterables, it is usually not necessary over the set of values. When using iterables, it is usually not necessary
to call :func:`iter` or deal with iterator objects yourself. The ``for`` to call :func:`iter` or deal with iterator objects yourself. The ``for``
@ -409,7 +409,7 @@ Glossary
namespace namespace
The place where a variable is stored. Namespaces are implemented as The place where a variable is stored. Namespaces are implemented as
dictionaries. There are the local, global and builtin namespaces as well dictionaries. There are the local, global and built-in namespaces as well
as nested namespaces in objects (in methods). Namespaces support as nested namespaces in objects (in methods). Namespaces support
modularity by preventing naming conflicts. For instance, the functions modularity by preventing naming conflicts. For instance, the functions
:func:`builtins.open` and :func:`os.open` are distinguished by their :func:`builtins.open` and :func:`os.open` are distinguished by their

View file

@ -228,7 +228,7 @@ Compare::
More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and
:func:`splitext`. :func:`splitext`.
There are also many useful builtin functions people seem not to be aware of for There are also many useful built-in functions people seem not to be aware of for
some reason: :func:`min` and :func:`max` can find the minimum/maximum of any some reason: :func:`min` and :func:`max` can find the minimum/maximum of any
sequence with comparable semantics, for example, yet many people write their own sequence with comparable semantics, for example, yet many people write their own
:func:`max`/:func:`min`. Another highly useful function is :func:`max`/:func:`min`. Another highly useful function is

View file

@ -182,10 +182,9 @@ which comes after we have a look at what happens when things go wrong.
Handling Exceptions Handling Exceptions
=================== ===================
*urlopen* raises :exc:`URLError` when it cannot handle a response (though as usual *urlopen* raises :exc:`URLError` when it cannot handle a response (though as
with Python APIs, builtin exceptions such as usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
:exc:`ValueError`, :exc:`TypeError` etc. may also :exc:`TypeError` etc. may also be raised).
be raised).
:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of :exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
HTTP URLs. HTTP URLs.

View file

@ -31,7 +31,7 @@ cur.execute("select ?", ("this is latin1 and would normally create errors" +
row = cur.fetchone() row = cur.fetchone()
assert type(row[0]) == str assert type(row[0]) == str
# sqlite3 offers a builtin optimized text_factory that will return bytestring # sqlite3 offers a built-in optimized text_factory that will return bytestring
# objects, if the data is in ASCII only, and otherwise return unicode objects # objects, if the data is in ASCII only, and otherwise return unicode objects
con.text_factory = sqlite3.OptimizedUnicode con.text_factory = sqlite3.OptimizedUnicode
cur.execute("select ?", (AUSTRIA,)) cur.execute("select ?", (AUSTRIA,))

View file

@ -86,13 +86,6 @@ document could also be refactored with this option.
The :option:`-v` option enables output of more information on the translation The :option:`-v` option enables output of more information on the translation
process. process.
When the :option:`-p` is passed, the :2to3fixer:`print` fixer ``print`` as a
function instead of a statement. This is useful when ``from __future__ import
print_function`` is being used. If this option is not given, the print fixer
will surround print calls in an extra set of parentheses because it cannot
differentiate between the print statement with parentheses (such as ``print
("a" + "b" + "c")``) and a true function call.
.. _2to3-fixers: .. _2to3-fixers:
@ -216,7 +209,7 @@ and off individually. They are described here in more detail.
.. 2to3fixer:: itertools .. 2to3fixer:: itertools
Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and
:func:`itertools.imap` to their builtin equivalents. :func:`itertools.imap` to their built-in equivalents.
:func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`. :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`.
.. 2to3fixer:: long .. 2to3fixer:: long
@ -246,8 +239,9 @@ and off individually. They are described here in more detail.
.. 2to3fixer:: next .. 2to3fixer:: next
Converts the use of iterator's :meth:`next` methods to the :func:`next` Converts the use of iterator's :meth:`~iterator.next` methods to the
function. It also renames :meth:`next` methods to :meth:`~object.__next__`. :func:`next` function. It also renames :meth:`next` methods to
:meth:`~object.__next__`.
.. 2to3fixer:: nonzero .. 2to3fixer:: nonzero

View file

@ -52,7 +52,7 @@ Instances of class :class:`_Feature` have two corresponding methods,
:meth:`getOptionalRelease` and :meth:`getMandatoryRelease`. :meth:`getOptionalRelease` and :meth:`getMandatoryRelease`.
*CompilerFlag* is the (bitfield) flag that should be passed in the fourth *CompilerFlag* is the (bitfield) flag that should be passed in the fourth
argument to the builtin function :func:`compile` to enable the feature in argument to the built-in function :func:`compile` to enable the feature in
dynamically compiled code. This flag is stored in the :attr:`compiler_flag` dynamically compiled code. This flag is stored in the :attr:`compiler_flag`
attribute on :class:`_Feature` instances. attribute on :class:`_Feature` instances.

View file

@ -48,7 +48,7 @@ Module :mod:`aifc` defines the following function:
time how many samples you are going to write in total and use time how many samples you are going to write in total and use
:meth:`writeframesraw` and :meth:`setnframes`. :meth:`writeframesraw` and :meth:`setnframes`.
Objects returned by :func:`open` when a file is opened for reading have the Objects returned by :func:`.open` when a file is opened for reading have the
following methods: following methods:
@ -133,7 +133,7 @@ following methods:
Close the AIFF file. After calling this method, the object can no longer be Close the AIFF file. After calling this method, the object can no longer be
used. used.
Objects returned by :func:`open` when a file is opened for writing have all the Objects returned by :func:`.open` when a file is opened for writing have all the
above methods, except for :meth:`readframes` and :meth:`setpos`. In addition above methods, except for :meth:`readframes` and :meth:`setpos`. In addition
the following methods exist. The :meth:`get\*` methods can only be called after the following methods exist. The :meth:`get\*` methods can only be called after
the corresponding :meth:`set\*` methods have been called. Before the first the corresponding :meth:`set\*` methods have been called. Before the first

View file

@ -21,7 +21,7 @@ defined:
+-----------+----------------+-------------------+-----------------------+ +-----------+----------------+-------------------+-----------------------+
| ``'B'`` | unsigned char | int | 1 | | ``'B'`` | unsigned char | int | 1 |
+-----------+----------------+-------------------+-----------------------+ +-----------+----------------+-------------------+-----------------------+
| ``'u'`` | Py_UNICODE | Unicode character | 2 | | ``'u'`` | Py_UNICODE | Unicode character | 2 (see note) |
+-----------+----------------+-------------------+-----------------------+ +-----------+----------------+-------------------+-----------------------+
| ``'h'`` | signed short | int | 2 | | ``'h'`` | signed short | int | 2 |
+-----------+----------------+-------------------+-----------------------+ +-----------+----------------+-------------------+-----------------------+
@ -40,6 +40,11 @@ defined:
| ``'d'`` | double | float | 8 | | ``'d'`` | double | float | 8 |
+-----------+----------------+-------------------+-----------------------+ +-----------+----------------+-------------------+-----------------------+
.. note::
The ``'u'`` typecode corresponds to Python's unicode character. On narrow
Unicode builds this is 2-bytes, on wide builds this is 4-bytes.
The actual representation of values is determined by the machine architecture The actual representation of values is determined by the machine architecture
(strictly speaking, by the C implementation). The actual size can be accessed (strictly speaking, by the C implementation). The actual size can be accessed
through the :attr:`itemsize` attribute. through the :attr:`itemsize` attribute.

View file

@ -16,7 +16,7 @@ Python release; this module helps to find out programmatically what the current
grammar looks like. grammar looks like.
An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as
a flag to the :func:`compile` builtin function, or using the :func:`parse` a flag to the :func:`compile` built-in function, or using the :func:`parse`
helper provided in this module. The result will be a tree of objects whose helper provided in this module. The result will be a tree of objects whose
classes all inherit from :class:`ast.AST`. An abstract syntax tree can be classes all inherit from :class:`ast.AST`. An abstract syntax tree can be
compiled into a Python code object using the built-in :func:`compile` function. compiled into a Python code object using the built-in :func:`compile` function.

View file

@ -222,7 +222,7 @@ The module defines the following variables and functions:
u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
width of the output fragment here. width of the output fragment here.
Note that operations such as :func:`mul` or :func:`max` make no distinction Note that operations such as :func:`.mul` or :func:`.max` make no distinction
between mono and stereo fragments, i.e. all samples are treated equal. If this between mono and stereo fragments, i.e. all samples are treated equal. If this
is a problem the stereo fragment should be split into two mono fragments first is a problem the stereo fragment should be split into two mono fragments first
and recombined later. Here is an example of how to do that:: and recombined later. Here is an example of how to do that::

View file

@ -132,8 +132,8 @@ commas::
If a field represents an uploaded file, accessing the value via the If a field represents an uploaded file, accessing the value via the
:attr:`value` attribute or the :func:`getvalue` method reads the entire file in :attr:`value` attribute or the :func:`getvalue` method reads the entire file in
memory as a string. This may not be what you want. You can test for an uploaded memory as a string. This may not be what you want. You can test for an uploaded
file by testing either the :attr:`filename` attribute or the :attr:`file` file by testing either the :attr:`filename` attribute or the :attr:`!file`
attribute. You can then read the data at leisure from the :attr:`file` attribute. You can then read the data at leisure from the :attr:`!file`
attribute:: attribute::
fileitem = form["userfile"] fileitem = form["userfile"]
@ -153,7 +153,7 @@ field will be set to the value -1.
The file upload draft standard entertains the possibility of uploading multiple The file upload draft standard entertains the possibility of uploading multiple
files from one field (using a recursive :mimetype:`multipart/\*` encoding). files from one field (using a recursive :mimetype:`multipart/\*` encoding).
When this occurs, the item will be a dictionary-like :class:`FieldStorage` item. When this occurs, the item will be a dictionary-like :class:`FieldStorage` item.
This can be determined by testing its :attr:`type` attribute, which should be This can be determined by testing its :attr:`!type` attribute, which should be
:mimetype:`multipart/form-data` (or perhaps another MIME type matching :mimetype:`multipart/form-data` (or perhaps another MIME type matching
:mimetype:`multipart/\*`). In this case, it can be iterated over recursively :mimetype:`multipart/\*`). In this case, it can be iterated over recursively
just like the top-level form object. just like the top-level form object.
@ -161,7 +161,7 @@ just like the top-level form object.
When a form is submitted in the "old" format (as the query string or as a single When a form is submitted in the "old" format (as the query string or as a single
data part of type :mimetype:`application/x-www-form-urlencoded`), the items will data part of type :mimetype:`application/x-www-form-urlencoded`), the items will
actually be instances of the class :class:`MiniFieldStorage`. In this case, the actually be instances of the class :class:`MiniFieldStorage`. In this case, the
:attr:`list`, :attr:`file`, and :attr:`filename` attributes are always ``None``. :attr:`!list`, :attr:`!file`, and :attr:`filename` attributes are always ``None``.
A form submitted via POST that also has a query string will contain both A form submitted via POST that also has a query string will contain both
:class:`FieldStorage` and :class:`MiniFieldStorage` items. :class:`FieldStorage` and :class:`MiniFieldStorage` items.

View file

@ -72,9 +72,10 @@ It defines the following functions:
encoding error), ``'replace'`` (replace malformed data with a suitable encoding error), ``'replace'`` (replace malformed data with a suitable
replacement marker, such as ``'?'``), ``'ignore'`` (ignore malformed data and replacement marker, such as ``'?'``), ``'ignore'`` (ignore malformed data and
continue without further notice), ``'xmlcharrefreplace'`` (replace with the continue without further notice), ``'xmlcharrefreplace'`` (replace with the
appropriate XML character reference (for encoding only)) and appropriate XML character reference (for encoding only)),
``'backslashreplace'`` (replace with backslashed escape sequences (for encoding ``'backslashreplace'`` (replace with backslashed escape sequences (for
only)) as well as any other error handling name defined via encoding only)), ``'surrogateescape'`` (replae with surrogate U+DCxx, see
:pep:`383`) as well as any other error handling name defined via
:func:`register_error`. :func:`register_error`.
In case a search function cannot find a given encoding, it should return In case a search function cannot find a given encoding, it should return

View file

@ -487,7 +487,7 @@ stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
.. class:: defaultdict([default_factory[, ...]]) .. class:: defaultdict([default_factory[, ...]])
Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the Returns a new dictionary-like object. :class:`defaultdict` is a subclass of the
builtin :class:`dict` class. It overrides one method and adds one writable built-in :class:`dict` class. It overrides one method and adds one writable
instance variable. The remaining functionality is the same as for the instance variable. The remaining functionality is the same as for the
:class:`dict` class and is not documented here. :class:`dict` class and is not documented here.

View file

@ -50,7 +50,7 @@ Default values can be specified by passing them into the :class:`ConfigParser`
constructor as a dictionary. Additional defaults may be passed into the constructor as a dictionary. Additional defaults may be passed into the
:meth:`get` method which will override all others. :meth:`get` method which will override all others.
Sections are normally stored in a builtin dictionary. An alternative dictionary Sections are normally stored in a built-in dictionary. An alternative dictionary
type can be passed to the :class:`ConfigParser` constructor. For example, if a type can be passed to the :class:`ConfigParser` constructor. For example, if a
dictionary type is passed that sorts its keys, the sections will be sorted on dictionary type is passed that sorts its keys, the sections will be sorted on
write-back, as will be the keys within each section. write-back, as will be the keys within each section.

View file

@ -50,7 +50,7 @@ The :mod:`csv` module defines the following functions:
Return a reader object which will iterate over lines in the given *csvfile*. Return a reader object which will iterate over lines in the given *csvfile*.
*csvfile* can be any object which supports the :term:`iterator` protocol and returns a *csvfile* can be any object which supports the :term:`iterator` protocol and returns a
string each time its :meth:`next` method is called --- file objects and list string each time its :meth:`!next` method is called --- file objects and list
objects are both suitable. If *csvfile* is a file object, it should be opened objects are both suitable. If *csvfile* is a file object, it should be opened
with ``newline=''``. [#]_ An optional with ``newline=''``. [#]_ An optional
*dialect* parameter can be given which is used to define a set of parameters *dialect* parameter can be given which is used to define a set of parameters

View file

@ -183,7 +183,7 @@ The module :mod:`curses` defines the following functions:
.. function:: filter() .. function:: filter()
The :func:`filter` routine, if used, must be called before :func:`initscr` is The :func:`.filter` routine, if used, must be called before :func:`initscr` is
called. The effect is that, during those calls, LINES is set to 1; the called. The effect is that, during those calls, LINES is set to 1; the
capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home
string is set to the value of cr. The effect is that the cursor is confined to string is set to the value of cr. The effect is that the cursor is confined to
@ -606,9 +606,9 @@ the following methods:
.. note:: .. note::
A *character* means a C character (an ASCII code), rather then a Python A *character* means a C character (an ASCII code), rather then a Python
character (a string of length 1). (This note is true whenever the documentation character (a string of length 1). (This note is true whenever the
mentions a character.) The builtin :func:`ord` is handy for conveying strings to documentation mentions a character.) The built-in :func:`ord` is handy for
codes. conveying strings to codes.
Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any
character previously painter at that location. By default, the character character previously painter at that location. By default, the character

View file

@ -61,7 +61,7 @@
modified by the prevailing umask). modified by the prevailing umask).
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
deleted, and the :keyword:`in` operator and the :meth:`keys` method are deleted, and the :keyword:`in` operator and the :meth:`keys` method are
available. Key and values are always stored as bytes. This means that when available. Key and values are always stored as bytes. This means that when

View file

@ -590,7 +590,7 @@ Decimal objects
.. method:: max_mag(other[, context]) .. method:: max_mag(other[, context])
Similar to the :meth:`max` method, but the comparison is done using the Similar to the :meth:`.max` method, but the comparison is done using the
absolute values of the operands. absolute values of the operands.
.. method:: min(other[, context]) .. method:: min(other[, context])
@ -602,7 +602,7 @@ Decimal objects
.. method:: min_mag(other[, context]) .. method:: min_mag(other[, context])
Similar to the :meth:`min` method, but the comparison is done using the Similar to the :meth:`.min` method, but the comparison is done using the
absolute values of the operands. absolute values of the operands.
.. method:: next_minus([context]) .. method:: next_minus([context])

View file

@ -514,7 +514,7 @@ are always available. They are listed here in alphabetical order.
to provide elaborate line editing and history features. to provide elaborate line editing and history features.
.. function:: int([number | string[, radix]]) .. function:: int([number | string[, base]])
Convert a number or string to an integer. If no arguments are given, return Convert a number or string to an integer. If no arguments are given, return
``0``. If a number is given, return ``number.__int__()``. Conversion of ``0``. If a number is given, return ``number.__int__()``. Conversion of
@ -522,10 +522,10 @@ are always available. They are listed here in alphabetical order.
a base-radix integer literal optionally preceded by '+' or '-' (with no space a base-radix integer literal optionally preceded by '+' or '-' (with no space
in between) and optionally surrounded by whitespace. A base-n literal in between) and optionally surrounded by whitespace. A base-n literal
consists of the digits 0 to n-1, with 'a' to 'z' (or 'A' to 'Z') having consists of the digits 0 to n-1, with 'a' to 'z' (or 'A' to 'Z') having
values 10 to 35. The default radix is 10. The allowed values are 0 and 2-36. values 10 to 35. The default *base* is 10. The allowed values are 0 and 2-36.
Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``, Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``,
``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Radix 0 ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Base 0
means to interpret exactly as a code literal, so that the actual radix is 2, means to interpret exactly as a code literal, so that the actual base is 2,
8, 10, or 16, and so that ``int('010', 0)`` is not legal, while 8, 10, or 16, and so that ``int('010', 0)`` is not legal, while
``int('010')`` is, as well as ``int('010', 8)``. ``int('010')`` is, as well as ``int('010', 8)``.

View file

@ -189,12 +189,12 @@ class can also install themselves in the built-in namespace as the function
.. function:: install(domain, localedir=None, codeset=None, names=None) .. function:: install(domain, localedir=None, codeset=None, names=None)
This installs the function :func:`_` in Python's builtin namespace, based on This installs the function :func:`_` in Python's builtins namespace, based on
*domain*, *localedir*, and *codeset* which are passed to the function *domain*, *localedir*, and *codeset* which are passed to the function
:func:`translation`. :func:`translation`.
For the *names* parameter, please see the description of the translation For the *names* parameter, please see the description of the translation
object's :meth:`install` method. object's :meth:`~NullTranslations.install` method.
As seen below, you usually mark the strings in your application that are As seen below, you usually mark the strings in your application that are
candidates for translation, by wrapping them in a call to the :func:`_` candidates for translation, by wrapping them in a call to the :func:`_`
@ -203,7 +203,7 @@ class can also install themselves in the built-in namespace as the function
print(_('This string will be translated.')) print(_('This string will be translated.'))
For convenience, you want the :func:`_` function to be installed in Python's For convenience, you want the :func:`_` function to be installed in Python's
builtin namespace, so it is easily accessible in all modules of your builtins namespace, so it is easily accessible in all modules of your
application. application.
@ -294,7 +294,7 @@ are the methods of :class:`NullTranslations`:
binding it to ``_``. binding it to ``_``.
If the *names* parameter is given, it must be a sequence containing the If the *names* parameter is given, it must be a sequence containing the
names of functions you want to install in the builtin namespace in names of functions you want to install in the builtins namespace in
addition to :func:`_`. Supported names are ``'gettext'`` (bound to addition to :func:`_`. Supported names are ``'gettext'`` (bound to
:meth:`self.gettext`), ``'ngettext'`` (bound to :meth:`self.ngettext`), :meth:`self.gettext`), ``'ngettext'`` (bound to :meth:`self.ngettext`),
``'lgettext'`` and ``'lngettext'``. ``'lgettext'`` and ``'lngettext'``.

View file

@ -134,7 +134,7 @@ The module also offers three general purpose functions based on heaps.
The latter two functions perform best for smaller values of *n*. For larger The latter two functions perform best for smaller values of *n*. For larger
values, it is more efficient to use the :func:`sorted` function. Also, when values, it is more efficient to use the :func:`sorted` function. Also, when
``n==1``, it is more efficient to use the builtin :func:`min` and :func:`max` ``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max`
functions. functions.

View file

@ -12,7 +12,7 @@
.. sectionauthor:: Benjamin Peterson <benjamin@python.org> .. sectionauthor:: Benjamin Peterson <benjamin@python.org>
The :mod:`io` module provides the Python interfaces to stream handling. The The :mod:`io` module provides the Python interfaces to stream handling. The
builtin :func:`open` function is defined in this module. built-in :func:`open` function is defined in this module.
At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It At the top of the I/O hierarchy is the abstract base class :class:`IOBase`. It
defines the basic interface to a stream. Note, however, that there is no defines the basic interface to a stream. Note, however, that there is no
@ -39,7 +39,7 @@ buffered text interface to a buffered raw stream
stream for text. stream for text.
Argument names are not part of the specification, and only the arguments of Argument names are not part of the specification, and only the arguments of
:func:`open` are intended to be used as keyword arguments. :func:`.open` are intended to be used as keyword arguments.
Module Interface Module Interface
@ -48,7 +48,7 @@ Module Interface
.. data:: DEFAULT_BUFFER_SIZE .. data:: DEFAULT_BUFFER_SIZE
An int containing the default buffer size used by the module's buffered I/O An int containing the default buffer size used by the module's buffered I/O
classes. :func:`open` uses the file's blksize (as obtained by classes. :func:`.open` uses the file's blksize (as obtained by
:func:`os.stat`) if possible. :func:`os.stat`) if possible.
.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True) .. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
@ -142,8 +142,8 @@ Module Interface
closed. If a filename is given *closefd* has no effect and must be ``True`` closed. If a filename is given *closefd* has no effect and must be ``True``
(the default). (the default).
The type of file object returned by the :func:`open` function depends on the The type of file object returned by the :func:`.open` function depends on the
mode. When :func:`open` is used to open a file in a text mode (``'w'``, mode. When :func:`.open` is used to open a file in a text mode (``'w'``,
``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
:class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open :class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open
a file in a binary mode with buffering, the returned class is a subclass of a file in a binary mode with buffering, the returned class is a subclass of
@ -256,7 +256,7 @@ I/O Base Classes
most *limit* bytes will be read. most *limit* bytes will be read.
The line terminator is always ``b'\n'`` for binary files; for text files, The line terminator is always ``b'\n'`` for binary files; for text files,
the *newlines* argument to :func:`open` can be used to select the line the *newlines* argument to :func:`.open` can be used to select the line
terminator(s) recognized. terminator(s) recognized.
.. method:: readlines(hint=-1) .. method:: readlines(hint=-1)

View file

@ -318,8 +318,8 @@ The :mod:`locale` module defines the following exception and functions:
.. data:: LC_NUMERIC .. data:: LC_NUMERIC
Locale category for formatting numbers. The functions :func:`format`, Locale category for formatting numbers. The functions :func:`.format`,
:func:`atoi`, :func:`atof` and :func:`str` of the :mod:`locale` module are :func:`atoi`, :func:`atof` and :func:`.str` of the :mod:`locale` module are
affected by that category. All other numeric formatting operations are not affected by that category. All other numeric formatting operations are not
affected. affected.
@ -504,7 +504,7 @@ document that your module is not compatible with non-\ ``C`` locale settings.
The only way to perform numeric operations according to the locale is to use the The only way to perform numeric operations according to the locale is to use the
special functions defined by this module: :func:`atof`, :func:`atoi`, special functions defined by this module: :func:`atof`, :func:`atoi`,
:func:`format`, :func:`str`. :func:`.format`, :func:`.str`.
There is no way to perform case conversions and character classifications There is no way to perform case conversions and character classifications
according to the locale. For (Unicode) text strings these are done according according to the locale. For (Unicode) text strings these are done according

View file

@ -998,7 +998,7 @@ instantiated directly, but always through the module-level function
Handles a record by passing it to all handlers associated with this logger and Handles a record by passing it to all handlers associated with this logger and
its ancestors (until a false value of *propagate* is found). This method is used its ancestors (until a false value of *propagate* is found). This method is used
for unpickled records received from a socket, as well as those created locally. for unpickled records received from a socket, as well as those created locally.
Logger-level filtering is applied using :meth:`filter`. Logger-level filtering is applied using :meth:`~Logger.filter`.
.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None) .. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)

View file

@ -1552,9 +1552,9 @@ with the :class:`Pool` class.
.. method:: apply(func[, args[, kwds]]) .. method:: apply(func[, args[, kwds]])
Call *func* with arguments *args* and keyword arguments *kwds*. It blocks Call *func* with arguments *args* and keyword arguments *kwds*. It blocks
till the result is ready. Given this blocks - :meth:`apply_async` is better suited till the result is ready. Given this blocks, :meth:`apply_async` is better
for performing work in parallel. Additionally, the passed suited for performing work in parallel. Additionally, the passed in
in function is only executed in one of the workers of the pool. function is only executed in one of the workers of the pool.
.. method:: apply_async(func[, args[, kwds[, callback]]]) .. method:: apply_async(func[, args[, kwds[, callback]]])
@ -1567,7 +1567,7 @@ with the :class:`Pool` class.
.. method:: map(func, iterable[, chunksize]) .. method:: map(func, iterable[, chunksize])
A parallel equivalent of the :func:`map` builtin function (it supports only A parallel equivalent of the :func:`map` built-in function (it supports only
one *iterable* argument though). It blocks till the result is ready. one *iterable* argument though). It blocks till the result is ready.
This method chops the iterable into a number of chunks which it submits to This method chops the iterable into a number of chunks which it submits to
@ -1576,7 +1576,7 @@ with the :class:`Pool` class.
.. method:: map_async(func, iterable[, chunksize[, callback]]) .. method:: map_async(func, iterable[, chunksize[, callback]])
A variant of the :meth:`map` method which returns a result object. A variant of the :meth:`.map` method which returns a result object.
If *callback* is specified then it should be a callable which accepts a If *callback* is specified then it should be a callable which accepts a
single argument. When the result becomes ready *callback* is applied to single argument. When the result becomes ready *callback* is applied to
@ -1592,7 +1592,7 @@ with the :class:`Pool` class.
make make the job complete **much** faster than using the default value of make make the job complete **much** faster than using the default value of
``1``. ``1``.
Also if *chunksize* is ``1`` then the :meth:`next` method of the iterator Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
returned by the :meth:`imap` method has an optional *timeout* parameter: returned by the :meth:`imap` method has an optional *timeout* parameter:
``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
result cannot be returned within *timeout* seconds. result cannot be returned within *timeout* seconds.

View file

@ -22,7 +22,7 @@ The numeric tower
.. class:: Complex .. class:: Complex
Subclasses of this type describe complex numbers and include the operations Subclasses of this type describe complex numbers and include the operations
that work on the builtin :class:`complex` type. These are: conversions to that work on the built-in :class:`complex` type. These are: conversions to
:class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``, :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``,
``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
except ``-`` and ``!=`` are abstract. except ``-`` and ``!=`` are abstract.

View file

@ -282,7 +282,7 @@ that's rarely necessary: by default it uses ``sys.argv[1:]``.)
* ``args``, the list of positional arguments leftover after parsing options * ``args``, the list of positional arguments leftover after parsing options
This tutorial section only covers the four most important option attributes: This tutorial section only covers the four most important option attributes:
:attr:`action`, :attr:`type`, :attr:`dest` (destination), and :attr:`help`. Of :attr:`action`, :attr:`!type`, :attr:`dest` (destination), and :attr:`help`. Of
these, :attr:`action` is the most fundamental. these, :attr:`action` is the most fundamental.
@ -829,7 +829,7 @@ this option on the command-line. The standard option actions hard-coded into
print a usage message including all options and the documentation for them print a usage message including all options and the documentation for them
(If you don't supply an action, the default is ``store``. For this action, you (If you don't supply an action, the default is ``store``. For this action, you
may also supply :attr:`type` and :attr:`dest` option attributes; see below.) may also supply :attr:`!type` and :attr:`dest` option attributes; see below.)
As you can see, most actions involve storing or updating a value somewhere. As you can see, most actions involve storing or updating a value somewhere.
:mod:`optparse` always creates a special object for this, conventionally called :mod:`optparse` always creates a special object for this, conventionally called
@ -860,7 +860,7 @@ then :mod:`optparse`, on seeing this option, will do the equivalent of ::
options.filename = "foo" options.filename = "foo"
The :attr:`type` and :attr:`dest` option attributes are almost as important as The :attr:`!type` and :attr:`dest` option attributes are almost as important as
:attr:`action`, but :attr:`action` is the only one that makes sense for *all* :attr:`action`, but :attr:`action` is the only one that makes sense for *all*
options. options.
@ -875,18 +875,18 @@ Most actions have several relevant option attributes which you may specify to
guide :mod:`optparse`'s behaviour; a few have required attributes, which you guide :mod:`optparse`'s behaviour; a few have required attributes, which you
must specify for any option using that action. must specify for any option using that action.
* ``store`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``] * ``store`` [relevant: :attr:`!type`, :attr:`dest`, ``nargs``, ``choices``]
The option must be followed by an argument, which is converted to a value The option must be followed by an argument, which is converted to a value
according to :attr:`type` and stored in :attr:`dest`. If ``nargs`` > 1, according to :attr:`!type` and stored in :attr:`dest`. If ``nargs`` > 1,
multiple arguments will be consumed from the command line; all will be converted multiple arguments will be consumed from the command line; all will be converted
according to :attr:`type` and stored to :attr:`dest` as a tuple. See the according to :attr:`!type` and stored to :attr:`dest` as a tuple. See the
"Option types" section below. "Option types" section below.
If ``choices`` is supplied (a list or tuple of strings), the type defaults to If ``choices`` is supplied (a list or tuple of strings), the type defaults to
``choice``. ``choice``.
If :attr:`type` is not supplied, it defaults to ``string``. If :attr:`!type` is not supplied, it defaults to ``string``.
If :attr:`dest` is not supplied, :mod:`optparse` derives a destination from the If :attr:`dest` is not supplied, :mod:`optparse` derives a destination from the
first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``). If there first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``). If there
@ -938,7 +938,7 @@ must specify for any option using that action.
parser.add_option("--clobber", action="store_true", dest="clobber") parser.add_option("--clobber", action="store_true", dest="clobber")
parser.add_option("--no-clobber", action="store_false", dest="clobber") parser.add_option("--no-clobber", action="store_false", dest="clobber")
* ``append`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``] * ``append`` [relevant: :attr:`!type`, :attr:`dest`, ``nargs``, ``choices``]
The option must be followed by an argument, which is appended to the list in The option must be followed by an argument, which is appended to the list in
:attr:`dest`. If no default value for :attr:`dest` is supplied, an empty list :attr:`dest`. If no default value for :attr:`dest` is supplied, an empty list
@ -946,7 +946,7 @@ must specify for any option using that action.
the command-line. If ``nargs`` > 1, multiple arguments are consumed, and a the command-line. If ``nargs`` > 1, multiple arguments are consumed, and a
tuple of length ``nargs`` is appended to :attr:`dest`. tuple of length ``nargs`` is appended to :attr:`dest`.
The defaults for :attr:`type` and :attr:`dest` are the same as for the ``store`` The defaults for :attr:`!type` and :attr:`dest` are the same as for the ``store``
action. action.
Example:: Example::
@ -988,7 +988,7 @@ must specify for any option using that action.
options.verbosity += 1 options.verbosity += 1
* ``callback`` [required: ``callback``; relevant: :attr:`type`, ``nargs``, * ``callback`` [required: ``callback``; relevant: :attr:`!type`, ``nargs``,
``callback_args``, ``callback_kwargs``] ``callback_args``, ``callback_kwargs``]
Call the function specified by ``callback``, which is called as :: Call the function specified by ``callback``, which is called as ::
@ -1061,7 +1061,7 @@ to a particular option, or fail to pass a required option attribute,
Determines :mod:`optparse`'s behaviour when this option is seen on the command Determines :mod:`optparse`'s behaviour when this option is seen on the command
line; the available options are documented above. line; the available options are documented above.
* :attr:`type` (default: ``"string"``) * :attr:`!type` (default: ``"string"``)
The argument type expected by this option (e.g., ``"string"`` or ``"int"``); the The argument type expected by this option (e.g., ``"string"`` or ``"int"``); the
available option types are documented below. available option types are documented below.
@ -1079,7 +1079,7 @@ to a particular option, or fail to pass a required option attribute,
* ``nargs`` (default: 1) * ``nargs`` (default: 1)
How many arguments of type :attr:`type` should be consumed when this option is How many arguments of type :attr:`!type` should be consumed when this option is
seen. If > 1, :mod:`optparse` will store a tuple of values to :attr:`dest`. seen. If > 1, :mod:`optparse` will store a tuple of values to :attr:`dest`.
* ``const`` * ``const``
@ -1410,15 +1410,15 @@ The four arguments to a callback are described below.
There are several other option attributes that you can supply when you define a There are several other option attributes that you can supply when you define a
callback option: callback option:
:attr:`type` :attr:`!type`
has its usual meaning: as with the ``store`` or ``append`` actions, it instructs has its usual meaning: as with the ``store`` or ``append`` actions, it instructs
:mod:`optparse` to consume one argument and convert it to :attr:`type`. Rather :mod:`optparse` to consume one argument and convert it to :attr:`!type`. Rather
than storing the converted value(s) anywhere, though, :mod:`optparse` passes it than storing the converted value(s) anywhere, though, :mod:`optparse` passes it
to your callback function. to your callback function.
``nargs`` ``nargs``
also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
consume ``nargs`` arguments, each of which must be convertible to :attr:`type`. consume ``nargs`` arguments, each of which must be convertible to :attr:`!type`.
It then passes a tuple of converted values to your callback. It then passes a tuple of converted values to your callback.
``callback_args`` ``callback_args``
@ -1450,8 +1450,8 @@ where
``value`` ``value``
is the argument to this option seen on the command-line. :mod:`optparse` will is the argument to this option seen on the command-line. :mod:`optparse` will
only expect an argument if :attr:`type` is set; the type of ``value`` will be only expect an argument if :attr:`!type` is set; the type of ``value`` will be
the type implied by the option's type. If :attr:`type` for this option is the type implied by the option's type. If :attr:`!type` for this option is
``None`` (no argument expected), then ``value`` will be ``None``. If ``nargs`` ``None`` (no argument expected), then ``value`` will be ``None``. If ``nargs``
> 1, ``value`` will be a tuple of values of the appropriate type. > 1, ``value`` will be a tuple of values of the appropriate type.
@ -1578,7 +1578,7 @@ Callback example 5: fixed arguments
Things get slightly more interesting when you define callback options that take Things get slightly more interesting when you define callback options that take
a fixed number of arguments. Specifying that a callback option takes arguments a fixed number of arguments. Specifying that a callback option takes arguments
is similar to defining a ``store`` or ``append`` option: if you define is similar to defining a ``store`` or ``append`` option: if you define
:attr:`type`, then the option takes one argument that must be convertible to :attr:`!type`, then the option takes one argument that must be convertible to
that type; if you further define ``nargs``, then the option takes ``nargs`` that type; if you further define ``nargs``, then the option takes ``nargs``
arguments. arguments.
@ -1757,7 +1757,7 @@ Adding new actions is a bit trickier, because you have to understand that
"typed" actions "typed" actions
actions that take a value from the command line and expect it to be of a certain actions that take a value from the command line and expect it to be of a certain
type; or rather, a string that can be converted to a certain type. These type; or rather, a string that can be converted to a certain type. These
options require a :attr:`type` attribute to the Option constructor. options require a :attr:`!type` attribute to the Option constructor.
These are overlapping sets: some default "store" actions are ``store``, These are overlapping sets: some default "store" actions are ``store``,
``store_const``, ``append``, and ``count``, while the default "typed" actions ``store_const``, ``append``, and ``count``, while the default "typed" actions

View file

@ -516,10 +516,10 @@ by file descriptors.
.. note:: .. note::
This function is intended for low-level I/O. For normal usage, use the built-in This function is intended for low-level I/O. For normal usage, use the
function :func:`open`, which returns a "file object" with :meth:`~file.read` and built-in function :func:`open`, which returns a "file object" with
:meth:`~file.write` methods (and many more). To wrap a file descriptor in a "file :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
object", use :func:`fdopen`. wrap a file descriptor in a "file object", use :func:`fdopen`.
.. function:: openpty() .. function:: openpty()
@ -540,9 +540,9 @@ by file descriptors.
.. function:: read(fd, n) .. function:: read(fd, n)
Read at most *n* bytes from file descriptor *fd*. Return a string containing the Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the
bytes read. If the end of the file referred to by *fd* has been reached, an bytes read. If the end of the file referred to by *fd* has been reached, an
empty string is returned. Availability: Unix, Windows. empty bytes object is returned. Availability: Unix, Windows.
.. note:: .. note::
@ -574,8 +574,8 @@ by file descriptors.
.. function:: write(fd, str) .. function:: write(fd, str)
Write the string *str* to file descriptor *fd*. Return the number of bytes Write the bytestring in *str* to file descriptor *fd*. Return the number of
actually written. Availability: Unix, Windows. bytes actually written. Availability: Unix, Windows.
.. note:: .. note::
@ -662,10 +662,10 @@ Files and Directories
.. note:: .. note::
Using :func:`access` to check if a user is authorized to e.g. open a file before Using :func:`access` to check if a user is authorized to e.g. open a file
actually doing so using :func:`open` creates a security hole, because the user before actually doing so using :func:`open` creates a security hole,
might exploit the short time interval between checking and opening the file to because the user might exploit the short time interval between checking
manipulate it. and opening the file to manipulate it.
.. note:: .. note::

View file

@ -118,7 +118,7 @@ Alternately, you can use the :meth:`setparameters` method to set all three audio
parameters at once. This is more convenient, but may not be as flexible in all parameters at once. This is more convenient, but may not be as flexible in all
cases. cases.
The audio device objects returned by :func:`open` define the following methods The audio device objects returned by :func:`.open` define the following methods
and (read-only) attributes: and (read-only) attributes:

View file

@ -13,7 +13,7 @@ Python data structures in a form which can be used as input to the interpreter.
If the formatted structures include objects which are not fundamental Python If the formatted structures include objects which are not fundamental Python
types, the representation may not be loadable. This may be the case if objects types, the representation may not be loadable. This may be the case if objects
such as files, sockets, classes, or instances are included, as well as many such as files, sockets, classes, or instances are included, as well as many
other builtin objects which are not representable as Python constants. other built-in objects which are not representable as Python constants.
The formatted representation keeps objects on a single line if it can, and The formatted representation keeps objects on a single line if it can, and
breaks them onto multiple lines if they don't fit within the allowed width. breaks them onto multiple lines if they don't fit within the allowed width.

View file

@ -78,7 +78,7 @@ members:
.. attribute:: Class.lineno .. attribute:: Class.lineno
The line number of the ``class`` statement within the file named by The line number of the ``class`` statement within the file named by
:attr:`file`. :attr:`~Class.file`.
.. _pyclbr-function-objects: .. _pyclbr-function-objects:
@ -109,5 +109,5 @@ The :class:`Function` objects used as values in the dictionary returned by
.. attribute:: Function.lineno .. attribute:: Function.lineno
The line number of the ``def`` statement within the file named by The line number of the ``def`` statement within the file named by
:attr:`file`. :attr:`~Function.file`.

View file

@ -221,7 +221,7 @@ The special characters are:
flags are described in :ref:`contents-of-module-re`.) This flags are described in :ref:`contents-of-module-re`.) This
is useful if you wish to include the flags as part of the regular is useful if you wish to include the flags as part of the regular
expression, instead of passing a *flag* argument to the expression, instead of passing a *flag* argument to the
:func:`compile` function. :func:`re.compile` function.
Note that the ``(?x)`` flag changes how the expression is parsed. It should be Note that the ``(?x)`` flag changes how the expression is parsed. It should be
used first in the expression string, or after one or more whitespace characters. used first in the expression string, or after one or more whitespace characters.
@ -464,9 +464,9 @@ form.
result = re.match(pattern, string) result = re.match(pattern, string)
but using :func:`compile` and saving the resulting regular expression object but using :func:`re.compile` and saving the resulting regular expression
for reuse is more efficient when the expression will be used several times object for reuse is more efficient when the expression will be used several
in a single program. times in a single program.
.. note:: .. note::
@ -564,7 +564,7 @@ form.
.. note:: .. note::
If you want to locate a match anywhere in *string*, use :meth:`search` If you want to locate a match anywhere in *string*, use :func:`search`
instead. instead.
@ -655,9 +655,7 @@ form.
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE) >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam' 'Baked Beans & Spam'
The pattern may be a string or an RE object; if you need to specify regular The pattern may be a string or an RE object.
expression flags, you must use a RE object, or use embedded modifiers in a
pattern; for example, ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``.
The optional argument *count* is the maximum number of pattern occurrences to be The optional argument *count* is the maximum number of pattern occurrences to be
replaced; *count* must be a non-negative integer. If omitted or zero, all replaced; *count* must be a non-negative integer. If omitted or zero, all
@ -720,8 +718,8 @@ attributes:
.. note:: .. note::
If you want to locate a match anywhere in *string*, use :meth:`search` If you want to locate a match anywhere in *string*, use
instead. :meth:`~RegexObject.search` instead.
The optional second parameter *pos* gives an index in the string where the The optional second parameter *pos* gives an index in the string where the
search is to start; it defaults to ``0``. This is not completely equivalent to search is to start; it defaults to ``0``. This is not completely equivalent to
@ -750,7 +748,7 @@ attributes:
is different from finding a zero-length match at some point in the string. is different from finding a zero-length match at some point in the string.
The optional *pos* and *endpos* parameters have the same meaning as for the The optional *pos* and *endpos* parameters have the same meaning as for the
:meth:`match` method. :meth:`~RegexObject.match` method.
.. method:: RegexObject.split(string[, maxsplit=0]) .. method:: RegexObject.split(string[, maxsplit=0])
@ -814,10 +812,10 @@ support the following methods and attributes:
.. method:: MatchObject.expand(template) .. method:: MatchObject.expand(template)
Return the string obtained by doing backslash substitution on the template Return the string obtained by doing backslash substitution on the template
string *template*, as done by the :meth:`sub` method. Escapes such as ``\n`` are string *template*, as done by the :meth:`~RegexObject.sub` method. Escapes
converted to the appropriate characters, and numeric backreferences (``\1``, such as ``\n`` are converted to the appropriate characters, and numeric
``\2``) and named backreferences (``\g<1>``, ``\g<name>``) are replaced by the backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
contents of the corresponding group. ``\g<name>``) are replaced by the contents of the corresponding group.
.. method:: MatchObject.group([group1, ...]) .. method:: MatchObject.group([group1, ...])
@ -938,16 +936,16 @@ support the following methods and attributes:
.. attribute:: MatchObject.pos .. attribute:: MatchObject.pos
The value of *pos* which was passed to the :func:`search` or :func:`match` The value of *pos* which was passed to the :meth:`~RegexObject.search` or
method of the :class:`RegexObject`. This is the index into the string at which :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
the RE engine started looking for a match. index into the string at which the RE engine started looking for a match.
.. attribute:: MatchObject.endpos .. attribute:: MatchObject.endpos
The value of *endpos* which was passed to the :func:`search` or :func:`match` The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
method of the :class:`RegexObject`. This is the index into the string beyond :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
which the RE engine will not go. index into the string beyond which the RE engine will not go.
.. attribute:: MatchObject.lastindex .. attribute:: MatchObject.lastindex
@ -967,13 +965,15 @@ support the following methods and attributes:
.. attribute:: MatchObject.re .. attribute:: MatchObject.re
The regular expression object whose :meth:`match` or :meth:`search` method The regular expression object whose :meth:`~RegexObject.match` or
produced this :class:`MatchObject` instance. :meth:`~RegexObject.search` method produced this :class:`MatchObject`
instance.
.. attribute:: MatchObject.string .. attribute:: MatchObject.string
The string passed to :func:`match` or :func:`search`. The string passed to :meth:`~RegexObject.match` or
:meth:`~RegexObject.search`.
Examples Examples
@ -1018,8 +1018,9 @@ To match this with a regular expression, one could use backreferences as such:
>>> displaymatch(pair.match("354aa")) # Pair of aces. >>> displaymatch(pair.match("354aa")) # Pair of aces.
"<Match: '354aa', groups=('a',)>" "<Match: '354aa', groups=('a',)>"
To find out what card the pair consists of, one could use the :func:`group` To find out what card the pair consists of, one could use the
method of :class:`MatchObject` in the following manner: :meth:`~MatchObject.group` method of :class:`MatchObject` in the following
manner:
.. doctest:: .. doctest::

View file

@ -23,16 +23,17 @@ This module provides a class, an instance, and a function:
.. data:: aRepr .. data:: aRepr
This is an instance of :class:`Repr` which is used to provide the :func:`repr` This is an instance of :class:`Repr` which is used to provide the
function described below. Changing the attributes of this object will affect :func:`.repr` function described below. Changing the attributes of this
the size limits used by :func:`repr` and the Python debugger. object will affect the size limits used by :func:`.repr` and the Python
debugger.
.. function:: repr(obj) .. function:: repr(obj)
This is the :meth:`repr` method of ``aRepr``. It returns a string similar to This is the :meth:`~Repr.repr` method of ``aRepr``. It returns a string
that returned by the built-in function of the same name, but with limits on similar to that returned by the built-in function of the same name, but with
most sizes. limits on most sizes.
.. _repr-objects: .. _repr-objects:
@ -92,7 +93,7 @@ which format specific object types.
.. method:: Repr.repr1(obj, level) .. method:: Repr.repr1(obj, level)
Recursive implementation used by :meth:`repr`. This uses the type of *obj* to Recursive implementation used by :meth:`.repr`. This uses the type of *obj* to
determine which formatting method to call, passing it *obj* and *level*. The determine which formatting method to call, passing it *obj* and *level*. The
type-specific methods should call :meth:`repr1` to perform recursive formatting, type-specific methods should call :meth:`repr1` to perform recursive formatting,
with ``level - 1`` for the value of *level* in the recursive call. with ``level - 1`` for the value of *level* in the recursive call.

View file

@ -299,7 +299,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.filter .. attribute:: kevent.filter
Name of the kernel filter Name of the kernel filter.
+---------------------------+---------------------------------------------+ +---------------------------+---------------------------------------------+
| Constant | Meaning | | Constant | Meaning |
@ -308,7 +308,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| | there is data available to read | | | there is data available to read |
+---------------------------+---------------------------------------------+ +---------------------------+---------------------------------------------+
| :const:`KQ_FILTER_WRITE` | Takes a descriptor and returns whenever | | :const:`KQ_FILTER_WRITE` | Takes a descriptor and returns whenever |
| | there is data available to read | | | there is data available to write |
+---------------------------+---------------------------------------------+ +---------------------------+---------------------------------------------+
| :const:`KQ_FILTER_AIO` | AIO requests | | :const:`KQ_FILTER_AIO` | AIO requests |
+---------------------------+---------------------------------------------+ +---------------------------+---------------------------------------------+
@ -328,7 +328,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.flags .. attribute:: kevent.flags
Filter action Filter action.
+---------------------------+---------------------------------------------+ +---------------------------+---------------------------------------------+
| Constant | Meaning | | Constant | Meaning |
@ -357,10 +357,9 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.fflags .. attribute:: kevent.fflags
Filter specific flags Filter specific flags.
:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags:
:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
| Constant | Meaning | | Constant | Meaning |
@ -368,8 +367,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| :const:`KQ_NOTE_LOWAT` | low water mark of a socket buffer | | :const:`KQ_NOTE_LOWAT` | low water mark of a socket buffer |
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
:const:`KQ_FILTER_VNODE` filter flags:
:const:`KQ_FILTER_VNODE` filter flags
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
| Constant | Meaning | | Constant | Meaning |
@ -389,8 +387,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| :const:`KQ_NOTE_REVOKE` | access to the file was revoked | | :const:`KQ_NOTE_REVOKE` | access to the file was revoked |
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
:const:`KQ_FILTER_PROC` filter flags:
:const:`KQ_FILTER_PROC` filter flags
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
| Constant | Meaning | | Constant | Meaning |
@ -413,7 +410,7 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
| :const:`KQ_NOTE_TRACKERR` | unable to attach to a child | | :const:`KQ_NOTE_TRACKERR` | unable to attach to a child |
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
:const:`KQ_FILTER_NETDEV` filter flags [not available on Mac OS X] :const:`KQ_FILTER_NETDEV` filter flags (not available on Mac OS X):
+----------------------------+--------------------------------------------+ +----------------------------+--------------------------------------------+
| Constant | Meaning | | Constant | Meaning |
@ -428,9 +425,9 @@ http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
.. attribute:: kevent.data .. attribute:: kevent.data
Filter specific data Filter specific data.
.. attribute:: kevent.udata .. attribute:: kevent.udata
User defined value User defined value.

View file

@ -101,7 +101,7 @@ Restrictions
.. class:: BsdDbShelf(dict[, protocol=None[, writeback=False]]) .. class:: BsdDbShelf(dict[, protocol=None[, writeback=False]])
A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`next`, A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`!next`,
:meth:`previous`, :meth:`last` and :meth:`set_location` which are available :meth:`previous`, :meth:`last` and :meth:`set_location` which are available
in the third-party :mod:`bsddb` module from `pybsddb in the third-party :mod:`bsddb` module from `pybsddb
<http://www.jcea.es/programacion/pybsddb.htm>`_ but not in other database <http://www.jcea.es/programacion/pybsddb.htm>`_ but not in other database
@ -117,7 +117,7 @@ Restrictions
A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like
object. The underlying file will be opened using :func:`dbm.open`. By object. The underlying file will be opened using :func:`dbm.open`. By
default, the file will be created and opened for both read and write. The default, the file will be created and opened for both read and write. The
optional *flag* parameter has the same interpretation as for the :func:`open` optional *flag* parameter has the same interpretation as for the :func:`.open`
function. The optional *protocol* and *writeback* parameters have the same function. The optional *protocol* and *writeback* parameters have the same
interpretation as for the :class:`Shelf` class. interpretation as for the :class:`Shelf` class.

View file

@ -555,6 +555,8 @@ correspond to Unix system calls applicable to sockets.
The :meth:`ioctl` method is a limited interface to the WSAIoctl system The :meth:`ioctl` method is a limited interface to the WSAIoctl system
interface. Please refer to the MSDN documentation for more information. interface. Please refer to the MSDN documentation for more information.
On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
functions may be used; they accept a socket object as their first argument.
.. method:: socket.listen(backlog) .. method:: socket.listen(backlog)

View file

@ -822,7 +822,7 @@ directly using only a single call on the :class:`Connection` object.
Accessing columns by name instead of by index Accessing columns by name instead of by index
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
One useful feature of the :mod:`sqlite3` module is the builtin One useful feature of the :mod:`sqlite3` module is the built-in
:class:`sqlite3.Row` class designed to be used as a row factory. :class:`sqlite3.Row` class designed to be used as a row factory.
Rows wrapped with this class can be accessed both by index (like tuples) and Rows wrapped with this class can be accessed both by index (like tuples) and

View file

@ -120,7 +120,17 @@ Notes:
Comparisons Comparisons
=========== ===========
.. index:: pair: chaining; comparisons .. index::
pair: chaining; comparisons
pair: operator; comparison
operator: ==
operator: <
operator: <=
operator: >
operator: >=
operator: !=
operator: is
operator: is not
There are eight comparison operations in Python. They all have the same There are eight comparison operations in Python. They all have the same
priority (which is higher than that of the Boolean operations). Comparisons can priority (which is higher than that of the Boolean operations). Comparisons can
@ -128,17 +138,6 @@ be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
y <= z``, except that *y* is evaluated only once (but in both cases *z* is not y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
evaluated at all when ``x < y`` is found to be false). evaluated at all when ``x < y`` is found to be false).
.. index::
pair: operator; comparison
operator: ==
operator: <
operator: >
operator: <=
operator: >=
operator: !=
operator: is
operator: is not
This table summarizes the comparison operations: This table summarizes the comparison operations:
+------------+-------------------------+ +------------+-------------------------+
@ -248,6 +247,13 @@ and imaginary parts.
builtin: int builtin: int
builtin: float builtin: float
builtin: complex builtin: complex
operator: +
operator: -
operator: *
operator: /
operator: //
operator: %
operator: **
Python fully supports mixed arithmetic: when a binary arithmetic operator has Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the "narrower" type is operands of different numeric types, the operand with the "narrower" type is
@ -368,7 +374,15 @@ modules.
Bit-string Operations on Integer Types Bit-string Operations on Integer Types
-------------------------------------- --------------------------------------
.. _bit-string-operations: .. index::
triple: operations on; integer; types
pair: bit-string; operations
pair: shifting; operations
pair: masking; operations
operator: ^
operator: &
operator: <<
operator: >>
Integers support additional operations that make sense only for bit-strings. Integers support additional operations that make sense only for bit-strings.
Negative numbers are treated as their 2's complement value (this assumes a Negative numbers are treated as their 2's complement value (this assumes a
@ -400,12 +414,6 @@ This table lists the bit-string operations sorted in ascending priority
| ``~x`` | the bits of *x* inverted | | | ``~x`` | the bits of *x* inverted | |
+------------+--------------------------------+----------+ +------------+--------------------------------+----------+
.. index::
triple: operations on; integer; types
pair: bit-string; operations
pair: shifting; operations
pair: masking; operations
Notes: Notes:
(1) (1)
@ -1595,7 +1603,7 @@ set``. Being an unordered collection, sets do not record element position or
order of insertion. Accordingly, sets do not support indexing, slicing, or order of insertion. Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior. other sequence-like behavior.
There are currently two builtin set types, :class:`set` and :class:`frozenset`. There are currently two built-in set types, :class:`set` and :class:`frozenset`.
The :class:`set` type is mutable --- the contents can be changed using methods The :class:`set` type is mutable --- the contents can be changed using methods
like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
and cannot be used as either a dictionary key or as an element of another set. and cannot be used as either a dictionary key or as an element of another set.

View file

@ -287,7 +287,7 @@ Format Specification Mini-Language
"Format specifications" are used within replacement fields contained within a "Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented (see format string to define how individual values are presented (see
:ref:`formatstrings`.) They can also be passed directly to the builtin :ref:`formatstrings`.) They can also be passed directly to the built-in
:func:`format` function. Each formattable type may define how the format :func:`format` function. Each formattable type may define how the format
specification is to be interpreted. specification is to be interpreted.

View file

@ -58,18 +58,18 @@ The :mod:`sunau` module defines the following functions:
.. function:: openfp(file, mode) .. function:: openfp(file, mode)
A synonym for :func:`open`, maintained for backwards compatibility. A synonym for :func:`.open`, maintained for backwards compatibility.
The :mod:`sunau` module defines the following exception: The :mod:`sunau` module defines the following exception:
.. exception:: Error .. exception:: Error
An error raised when something is impossible because of Sun AU specs or An error raised when something is impossible because of Sun AU specs or
implementation deficiency. implementation deficiency.
The :mod:`sunau` module defines the following data items:
The :mod:`sunau` module defines the following data items:
.. data:: AUDIO_FILE_MAGIC .. data:: AUDIO_FILE_MAGIC
@ -104,7 +104,7 @@ The :mod:`sunau` module defines the following data items:
AU_read Objects AU_read Objects
--------------- ---------------
AU_read objects, as returned by :func:`open` above, have the following methods: AU_read objects, as returned by :func:`.open` above, have the following methods:
.. method:: AU_read.close() .. method:: AU_read.close()
@ -197,7 +197,7 @@ and don't do anything interesting.
AU_write Objects AU_write Objects
---------------- ----------------
AU_write objects, as returned by :func:`open` above, have the following methods: AU_write objects, as returned by :func:`.open` above, have the following methods:
.. method:: AU_write.setnchannels(n) .. method:: AU_write.setnchannels(n)

View file

@ -736,7 +736,7 @@ always available.
``'c_call'`` ``'c_call'``
A C function is about to be called. This may be an extension function or A C function is about to be called. This may be an extension function or
a builtin. *arg* is the C function object. a built-in. *arg* is the C function object.
``'c_return'`` ``'c_return'``
A C function has returned. *arg* is ``None``. A C function has returned. *arg* is ``None``.

View file

@ -48,7 +48,7 @@ The module defines the following user-callable functions:
The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`. The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
The returned object is a true file object on POSIX platforms. On other The returned object is a true file object on POSIX platforms. On other
platforms, it is a file-like object whose :attr:`file` attribute is the platforms, it is a file-like object whose :attr:`!file` attribute is the
underlying true file object. This file-like object can be used in a underlying true file object. This file-like object can be used in a
:keyword:`with` statement, just like a normal file. :keyword:`with` statement, just like a normal file.
@ -63,7 +63,7 @@ The module defines the following user-callable functions:
still open, varies across platforms (it can be so used on Unix; it cannot still open, varies across platforms (it can be so used on Unix; it cannot
on Windows NT or later). If *delete* is true (the default), the file is on Windows NT or later). If *delete* is true (the default), the file is
deleted as soon as it is closed. deleted as soon as it is closed.
The returned object is always a file-like object whose :attr:`file` The returned object is always a file-like object whose :attr:`!file`
attribute is the underlying true file object. This file-like object can attribute is the underlying true file object. This file-like object can
be used in a :keyword:`with` statement, just like a normal file. be used in a :keyword:`with` statement, just like a normal file.

View file

@ -1,4 +1,3 @@
:mod:`threading` --- Higher-level threading interface :mod:`threading` --- Higher-level threading interface
===================================================== =====================================================
@ -55,8 +54,9 @@ This module defines the following functions and objects:
:noindex: :noindex:
A factory function that returns a new event object. An event manages a flag A factory function that returns a new event object. An event manages a flag
that can be set to true with the :meth:`set` method and reset to false with the that can be set to true with the :meth:`~Event.set` method and reset to false
:meth:`clear` method. The :meth:`wait` method blocks until the flag is true. with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
is true.
.. class:: local .. class:: local
@ -213,7 +213,8 @@ impossible to detect the termination of alien threads.
.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={}) .. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
This constructor should always be called with keyword arguments. Arguments are: This constructor should always be called with keyword arguments. Arguments
are:
*group* should be ``None``; reserved for future extension when a *group* should be ``None``; reserved for future extension when a
:class:`ThreadGroup` class is implemented. :class:`ThreadGroup` class is implemented.
@ -221,111 +222,103 @@ impossible to detect the termination of alien threads.
*target* is the callable object to be invoked by the :meth:`run` method. *target* is the callable object to be invoked by the :meth:`run` method.
Defaults to ``None``, meaning nothing is called. Defaults to ``None``, meaning nothing is called.
*name* is the thread name. By default, a unique name is constructed of the form *name* is the thread name. By default, a unique name is constructed of the
"Thread-*N*" where *N* is a small decimal number. form "Thread-*N*" where *N* is a small decimal number.
*args* is the argument tuple for the target invocation. Defaults to ``()``. *args* is the argument tuple for the target invocation. Defaults to ``()``.
*kwargs* is a dictionary of keyword arguments for the target invocation. *kwargs* is a dictionary of keyword arguments for the target invocation.
Defaults to ``{}``. Defaults to ``{}``.
If the subclass overrides the constructor, it must make sure to invoke the base If the subclass overrides the constructor, it must make sure to invoke the
class constructor (``Thread.__init__()``) before doing anything else to the base class constructor (``Thread.__init__()``) before doing anything else to
thread. the thread.
.. method:: start()
.. method:: Thread.start() Start the thread's activity.
Start the thread's activity. It must be called at most once per thread object. It arranges for the
object's :meth:`run` method to be invoked in a separate thread of control.
It must be called at most once per thread object. It arranges for the object's This method will raise a :exc:`RuntimeException` if called more than once
:meth:`run` method to be invoked in a separate thread of control. on the same thread object.
This method will raise a :exc:`RuntimeException` if called more than once on the .. method:: run()
same thread object.
Method representing the thread's activity.
.. method:: Thread.run() You may override this method in a subclass. The standard :meth:`run`
method invokes the callable object passed to the object's constructor as
the *target* argument, if any, with sequential and keyword arguments taken
from the *args* and *kwargs* arguments, respectively.
Method representing the thread's activity. .. method:: join([timeout])
You may override this method in a subclass. The standard :meth:`run` method Wait until the thread terminates. This blocks the calling thread until the
invokes the callable object passed to the object's constructor as the *target* thread whose :meth:`join` method is called terminates -- either normally
argument, if any, with sequential and keyword arguments taken from the *args* or through an unhandled exception -- or until the optional timeout occurs.
and *kwargs* arguments, respectively.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As :meth:`join` always returns ``None``, you must
call :meth:`is_alive` after :meth:`join` to decide whether a timeout
happened -- if the thread is still alive, the :meth:`join` call timed out.
.. method:: Thread.join([timeout]) When the *timeout* argument is not present or ``None``, the operation will
block until the thread terminates.
Wait until the thread terminates. This blocks the calling thread until the A thread can be :meth:`join`\ ed many times.
thread whose :meth:`join` method is called terminates -- either normally or
through an unhandled exception -- or until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a floating :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
point number specifying a timeout for the operation in seconds (or fractions the current thread as that would cause a deadlock. It is also an error to
thereof). As :meth:`join` always returns ``None``, you must call :meth:`is_alive` :meth:`join` a thread before it has been started and attempts to do so
after :meth:`join` to decide whether a timeout happened -- if the thread is raises the same exception.
still alive, the :meth:`join` call timed out.
When the *timeout* argument is not present or ``None``, the operation will block .. attribute:: name
until the thread terminates.
A thread can be :meth:`join`\ ed many times. A string used for identification purposes only. It has no semantics.
Multiple threads may be given the same name. The initial name is set by
the constructor.
:meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join .. method:: getName()
the current thread as that would cause a deadlock. It is also an error to setName()
:meth:`join` a thread before it has been started and attempts to do so
raises the same exception.
Old getter/setter API for :attr:`~Thread.name`; use it directly as a
property instead.
.. attribute:: Thread.name .. attribute:: ident
A string used for identification purposes only. It has no semantics. The 'thread identifier' of this thread or ``None`` if the thread has not
Multiple threads may be given the same name. The initial name is set by the been started. This is a nonzero integer. See the
constructor. :func:`thread.get_ident()` function. Thread identifiers may be recycled
when a thread exits and another thread is created. The identifier is
available even after the thread has exited.
.. method:: is_alive()
.. method:: Thread.getName() Return whether the thread is alive.
Thread.setName()
Old getter/setter API for :attr:`~Thread.name`; use it directly as a property Roughly, a thread is alive from the moment the :meth:`start` method
instead. returns until its :meth:`run` method terminates. The module function
:func:`enumerate` returns a list of all alive threads.
.. attribute:: daemon
.. attribute:: Thread.ident A boolean value indicating whether this thread is a daemon thread (True)
or not (False). This must be set before :meth:`start` is called,
otherwise :exc:`RuntimeError` is raised. Its initial value is inherited
from the creating thread; the main thread is not a daemon thread and
therefore all threads created in the main thread default to :attr:`daemon`
= ``False``.
The 'thread identifier' of this thread or ``None`` if the thread has not been The entire Python program exits when no alive non-daemon threads are left.
started. This is a nonzero integer. See the :func:`thread.get_ident()`
function. Thread identifiers may be recycled when a thread exits and another
thread is created. The identifier is available even after the thread has
exited.
.. method:: isDaemon()
setDaemon()
.. method:: Thread.is_alive() Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
property instead.
Return whether the thread is alive.
Roughly, a thread is alive from the moment the :meth:`start` method returns
until its :meth:`run` method terminates. The module function :func:`enumerate`
returns a list of all alive threads.
.. attribute:: Thread.daemon
A boolean value indicating whether this thread is a daemon thread (True) or
not (False). This must be set before :meth:`start` is called, otherwise
:exc:`RuntimeError` is raised. Its initial value is inherited from the
creating thread; the main thread is not a daemon thread and therefore all
threads created in the main thread default to :attr:`daemon` = ``False``.
The entire Python program exits when no alive non-daemon threads are left.
.. method:: Thread.isDaemon()
Thread.setDaemon()
Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
property instead.
.. _lock-objects: .. _lock-objects:
@ -496,69 +489,66 @@ needs to wake up one consumer thread.
.. class:: Condition([lock]) .. class:: Condition([lock])
If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
:class:`RLock` object, and it is used as the underlying lock. Otherwise, a new or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
:class:`RLock` object is created and used as the underlying lock. a new :class:`RLock` object is created and used as the underlying lock.
.. method:: acquire(*args)
.. method:: Condition.acquire(*args) Acquire the underlying lock. This method calls the corresponding method on
the underlying lock; the return value is whatever that method returns.
Acquire the underlying lock. This method calls the corresponding method on the .. method:: release()
underlying lock; the return value is whatever that method returns.
Release the underlying lock. This method calls the corresponding method on
the underlying lock; there is no return value.
.. method:: Condition.release() .. method:: wait([timeout])
Release the underlying lock. This method calls the corresponding method on the Wait until notified or until a timeout occurs. If the calling thread has
underlying lock; there is no return value. not acquired the lock when this method is called, a :exc:`RuntimeError` is
raised.
This method releases the underlying lock, and then blocks until it is
awakened by a :meth:`notify` or :meth:`notify_all` call for the same
condition variable in another thread, or until the optional timeout
occurs. Once awakened or timed out, it re-acquires the lock and returns.
.. method:: Condition.wait([timeout]) When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
Wait until notified or until a timeout occurs. If the calling thread has not When the underlying lock is an :class:`RLock`, it is not released using
acquired the lock when this method is called, a :exc:`RuntimeError` is raised. its :meth:`release` method, since this may not actually unlock the lock
when it was acquired multiple times recursively. Instead, an internal
interface of the :class:`RLock` class is used, which really unlocks it
even when it has been recursively acquired several times. Another internal
interface is then used to restore the recursion level when the lock is
reacquired.
This method releases the underlying lock, and then blocks until it is awakened .. method:: notify()
by a :meth:`notify` or :meth:`notify_all` call for the same condition variable in
another thread, or until the optional timeout occurs. Once awakened or timed
out, it re-acquires the lock and returns.
When the *timeout* argument is present and not ``None``, it should be a floating Wake up a thread waiting on this condition, if any. If the calling thread
point number specifying a timeout for the operation in seconds (or fractions has not acquired the lock when this method is called, a
thereof). :exc:`RuntimeError` is raised.
When the underlying lock is an :class:`RLock`, it is not released using its This method wakes up one of the threads waiting for the condition
:meth:`release` method, since this may not actually unlock the lock when it was variable, if any are waiting; it is a no-op if no threads are waiting.
acquired multiple times recursively. Instead, an internal interface of the
:class:`RLock` class is used, which really unlocks it even when it has been
recursively acquired several times. Another internal interface is then used to
restore the recursion level when the lock is reacquired.
The current implementation wakes up exactly one thread, if any are
waiting. However, it's not safe to rely on this behavior. A future,
optimized implementation may occasionally wake up more than one thread.
.. method:: Condition.notify() Note: the awakened thread does not actually return from its :meth:`wait`
call until it can reacquire the lock. Since :meth:`notify` does not
release the lock, its caller should.
Wake up a thread waiting on this condition, if any. If the calling thread .. method:: notify_all()
has not acquired the lock when this method is called, a :exc:`RuntimeError`
is raised.
This method wakes up one of the threads waiting for the condition variable, Wake up all threads waiting on this condition. This method acts like
if any are waiting; it is a no-op if no threads are waiting. :meth:`notify`, but wakes up all waiting threads instead of one. If the
calling thread has not acquired the lock when this method is called, a
The current implementation wakes up exactly one thread, if any are waiting. :exc:`RuntimeError` is raised.
However, it's not safe to rely on this behavior. A future, optimized
implementation may occasionally wake up more than one thread.
Note: the awakened thread does not actually return from its :meth:`wait` call
until it can reacquire the lock. Since :meth:`notify` does not release the
lock, its caller should.
.. method:: Condition.notify_all()
Wake up all threads waiting on this condition. This method acts like
:meth:`notify`, but wakes up all waiting threads instead of one. If the calling
thread has not acquired the lock when this method is called, a
:exc:`RuntimeError` is raised.
.. _semaphore-objects: .. _semaphore-objects:
@ -582,33 +572,31 @@ waiting until some other thread calls :meth:`release`.
defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
raised. raised.
.. method:: acquire([blocking])
.. method:: Semaphore.acquire([blocking]) Acquire a semaphore.
Acquire a semaphore. When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called
:meth:`release` to make it larger than zero. This is done with proper
interlocking so that if multiple :meth:`acquire` calls are blocked,
:meth:`release` will wake exactly one of them up. The implementation may
pick one at random, so the order in which blocked threads are awakened
should not be relied on. There is no return value in this case.
When invoked without arguments: if the internal counter is larger than zero on When invoked with *blocking* set to true, do the same thing as when called
entry, decrement it by one and return immediately. If it is zero on entry, without arguments, and return true.
block, waiting until some other thread has called :meth:`release` to make it
larger than zero. This is done with proper interlocking so that if multiple
:meth:`acquire` calls are blocked, :meth:`release` will wake exactly one of them
up. The implementation may pick one at random, so the order in which blocked
threads are awakened should not be relied on. There is no return value in this
case.
When invoked with *blocking* set to true, do the same thing as when called When invoked with *blocking* set to false, do not block. If a call
without arguments, and return true. without an argument would block, return false immediately; otherwise, do
the same thing as when called without arguments, and return true.
When invoked with *blocking* set to false, do not block. If a call without an .. method:: release()
argument would block, return false immediately; otherwise, do the same thing as
when called without arguments, and return true.
Release a semaphore, incrementing the internal counter by one. When it
.. method:: Semaphore.release() was zero on entry and another thread is waiting for it to become larger
than zero again, wake up that thread.
Release a semaphore, incrementing the internal counter by one. When it was zero
on entry and another thread is waiting for it to become larger than zero again,
wake up that thread.
.. _semaphore-examples: .. _semaphore-examples:
@ -647,7 +635,7 @@ This is one of the simplest mechanisms for communication between threads: one
thread signals an event and other threads wait for it. thread signals an event and other threads wait for it.
An event object manages an internal flag that can be set to true with the An event object manages an internal flag that can be set to true with the
:meth:`set` method and reset to false with the :meth:`clear` method. The :meth:`~Event.set` method and reset to false with the :meth:`clear` method. The
:meth:`wait` method blocks until the flag is true. :meth:`wait` method blocks until the flag is true.
@ -655,40 +643,37 @@ An event object manages an internal flag that can be set to true with the
The internal flag is initially false. The internal flag is initially false.
.. method:: is_set()
.. method:: Event.is_set() Return true if and only if the internal flag is true.
Return true if and only if the internal flag is true. .. method:: set()
Set the internal flag to true. All threads waiting for it to become true
are awakened. Threads that call :meth:`wait` once the flag is true will
not block at all.
.. method:: Event.set() .. method:: clear()
Set the internal flag to true. All threads waiting for it to become true are Reset the internal flag to false. Subsequently, threads calling
awakened. Threads that call :meth:`wait` once the flag is true will not block at :meth:`wait` will block until :meth:`.set` is called to set the internal
all. flag to true again.
.. method:: wait([timeout])
.. method:: Event.clear() Block until the internal flag is true. If the internal flag is true on
entry, return immediately. Otherwise, block until another thread calls
:meth:`set` to set the flag to true, or until the optional timeout occurs.
Reset the internal flag to false. Subsequently, threads calling :meth:`wait` When the timeout argument is present and not ``None``, it should be a
will block until :meth:`set` is called to set the internal flag to true again. floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
This method returns the internal flag on exit, so it will always return
``True`` except if a timeout is given and the operation times out.
.. method:: Event.wait([timeout]) .. versionchanged:: 3.1
Previously, the method always returned ``None``.
Block until the internal flag is true. If the internal flag is true on entry,
return immediately. Otherwise, block until another thread calls :meth:`set`
to set the flag to true, or until the optional timeout occurs.
When the timeout argument is present and not ``None``, it should be a floating
point number specifying a timeout for the operation in seconds (or fractions
thereof).
This method returns the internal flag on exit, so it will always return
``True`` except if a timeout is given and the operation times out.
.. versionchanged:: 3.1
Previously, the method always returned ``None``.
.. _timer-objects: .. _timer-objects:
@ -719,11 +704,10 @@ For example::
Create a timer that will run *function* with arguments *args* and keyword Create a timer that will run *function* with arguments *args* and keyword
arguments *kwargs*, after *interval* seconds have passed. arguments *kwargs*, after *interval* seconds have passed.
.. method:: cancel()
.. method:: Timer.cancel() Stop the timer, and cancel the execution of the timer's action. This will
only work if the timer is still in its waiting stage.
Stop the timer, and cancel the execution of the timer's action. This will only
work if the timer is still in its waiting stage.
.. _with-locks: .. _with-locks:

View file

@ -511,7 +511,7 @@ defined in the :mod:`tkinter`.
There are many useful subclasses of Variable already defined: There are many useful subclasses of Variable already defined:
:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and :class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
:class:`BooleanVar`. To read the current value of such a variable, call the :class:`BooleanVar`. To read the current value of such a variable, call the
:meth:`get` method on it, and to change its value you call the :meth:`set` :meth:`get` method on it, and to change its value you call the :meth:`!set`
method. If you follow this protocol, the widget will always track the value of method. If you follow this protocol, the widget will always track the value of
the variable, with no further intervention on your part. the variable, with no further intervention on your part.
@ -652,7 +652,7 @@ relief
``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``. ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
scrollcommand scrollcommand
This is almost always the :meth:`set` method of some scrollbar widget, but can This is almost always the :meth:`!set` method of some scrollbar widget, but can
be any widget method that takes a single argument. Refer to the file be any widget method that takes a single argument. Refer to the file
:file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
distribution for an example. distribution for an example.

View file

@ -25,4 +25,3 @@ documented beyond this mention. There's little need to document these.
:mod:`posixpath` :mod:`posixpath`
--- Implementation of :mod:`os.path` on POSIX. --- Implementation of :mod:`os.path` on POSIX.

View file

@ -249,9 +249,9 @@ The :mod:`urllib.parse` module defines the following functions:
.. function:: quote_plus(string[, safe[, encoding[, errors]]]) .. function:: quote_plus(string[, safe[, encoding[, errors]]])
Like :func:`quote`, but also replace spaces by plus signs, as required for Like :func:`quote`, but also replace spaces by plus signs, as required for
quoting HTML form values. Plus signs in the original string are escaped quoting HTML form values when building up a query string to go into a URL.
unless they are included in *safe*. It also does not have *safe* default to Plus signs in the original string are escaped unless they are included in
``'/'``. *safe*. It also does not have *safe* default to ``'/'``.
Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``. Example: ``quote_plus('/El Niño/')`` yields ``'%2FEl+Ni%C3%B1o%2F'``.

View file

@ -206,7 +206,7 @@ check::
fxn() fxn()
# Verify some things # Verify some things
assert len(w) == 1 assert len(w) == 1
assert isinstance(w[-1].category, DeprecationWarning) assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message) assert "deprecated" in str(w[-1].message)
One can also cause all warnings to be exceptions by using ``error`` instead of One can also cause all warnings to be exceptions by using ``error`` instead of

View file

@ -33,7 +33,7 @@ The :mod:`wave` module defines the following function and exception:
.. function:: openfp(file, mode) .. function:: openfp(file, mode)
A synonym for :func:`open`, maintained for backwards compatibility. A synonym for :func:`.open`, maintained for backwards compatibility.
.. exception:: Error .. exception:: Error
@ -47,7 +47,7 @@ The :mod:`wave` module defines the following function and exception:
Wave_read Objects Wave_read Objects
----------------- -----------------
Wave_read objects, as returned by :func:`open`, have the following methods: Wave_read objects, as returned by :func:`.open`, have the following methods:
.. method:: Wave_read.close() .. method:: Wave_read.close()
@ -134,7 +134,7 @@ them, and is otherwise implementation dependent.
Wave_write Objects Wave_write Objects
------------------ ------------------
Wave_write objects, as returned by :func:`open`, have the following methods: Wave_write objects, as returned by :func:`.open`, have the following methods:
.. method:: Wave_write.close() .. method:: Wave_write.close()

View file

@ -62,7 +62,7 @@ instances, functions written in Python (but not in C), instance methods, sets,
frozensets, file objects, :term:`generator`\s, type objects, sockets, arrays, frozensets, file objects, :term:`generator`\s, type objects, sockets, arrays,
deques, and regular expression pattern objects. deques, and regular expression pattern objects.
Several builtin types such as :class:`list` and :class:`dict` do not directly Several built-in types such as :class:`list` and :class:`dict` do not directly
support weak references but can add support through subclassing:: support weak references but can add support through subclassing::
class Dict(dict): class Dict(dict):

View file

@ -10,7 +10,7 @@
The :mod:`webbrowser` module provides a high-level interface to allow displaying The :mod:`webbrowser` module provides a high-level interface to allow displaying
Web-based documents to users. Under most circumstances, simply calling the Web-based documents to users. Under most circumstances, simply calling the
:func:`open` function from this module will do the right thing. :func:`.open` function from this module will do the right thing.
Under Unix, graphical browsers are preferred under X11, but text-mode browsers Under Unix, graphical browsers are preferred under X11, but text-mode browsers
will be used if graphical browsers are not available or an X11 display isn't will be used if graphical browsers are not available or an X11 display isn't
@ -46,14 +46,14 @@ The following exception is defined:
The following functions are defined: The following functions are defined:
.. function:: open(url[, new=0[, autoraise=1]]) .. function:: open(url[, new=0[, autoraise=True]])
Display *url* using the default browser. If *new* is 0, the *url* is opened in Display *url* using the default browser. If *new* is 0, the *url* is opened
the same browser window if possible. If *new* is 1, a new browser window is in the same browser window if possible. If *new* is 1, a new browser window
opened if possible. If *new* is 2, a new browser page ("tab") is opened if is opened if possible. If *new* is 2, a new browser page ("tab") is opened
possible. If *autoraise* is true, the window is raised if possible (note that if possible. If *autoraise* is ``True``, the window is raised if possible
under many window managers this will occur regardless of the setting of this (note that under many window managers this will occur regardless of the
variable). setting of this variable).
Note that on some platforms, trying to open a filename using this function, Note that on some platforms, trying to open a filename using this function,
may work and start the operating system's associated program. However, this may work and start the operating system's associated program. However, this
@ -175,7 +175,7 @@ Browser controllers provide these methods which parallel three of the
module-level convenience functions: module-level convenience functions:
.. method:: controller.open(url[, new[, autoraise=1]]) .. method:: controller.open(url[, new[, autoraise=True]])
Display *url* using the browser handled by this controller. If *new* is 1, a new Display *url* using the browser handled by this controller. If *new* is 1, a new
browser window is opened if possible. If *new* is 2, a new browser page ("tab") browser window is opened if possible. If *new* is 2, a new browser page ("tab")

View file

@ -399,7 +399,7 @@ detached).
The object also support comparison semantics, so handle objects will compare The object also support comparison semantics, so handle objects will compare
true if they both reference the same underlying Windows handle value. true if they both reference the same underlying Windows handle value.
Handle objects can be converted to an integer (e.g., using the builtin Handle objects can be converted to an integer (e.g., using the built-in
:func:`int` function), in which case the underlying Windows handle value is :func:`int` function), in which case the underlying Windows handle value is
returned. You can also use the :meth:`Detach` method to return the integer returned. You can also use the :meth:`Detach` method to return the integer
handle, and also disconnect the Windows handle from the handle object. handle, and also disconnect the Windows handle from the handle object.

View file

@ -262,9 +262,9 @@ The following methods work on the element's children (subelements).
.. method:: Element.getiterator([tag=None]) .. method:: Element.getiterator([tag=None])
Creates a tree iterator with the current element as the root. The iterator Creates a tree iterator with the current element as the root. The iterator
iterates over this element and all elements below it that match the given tag. iterates over this element and all elements below it, in document (depth first)
If tag is ``None`` or ``'*'`` then all elements are iterated over. Returns an order. If *tag* is not ``None`` or ``'*'``, only elements whose tag equals
iterable that provides element objects in document (depth first) order. *tag* are returned from the iterator.
.. method:: Element.insert(index, element) .. method:: Element.insert(index, element)

View file

@ -87,7 +87,7 @@ between conformable Python objects and XML on the wire.
:exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer. :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
:exc:`Error`. Note that the xmlrpc client module currently does not marshal :exc:`Error`. Note that the xmlrpc client module currently does not marshal
instances of subclasses of builtin types. instances of subclasses of built-in types.
When passing strings, characters special to XML such as ``<``, ``>``, and ``&`` When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
will be automatically escaped. However, it's the caller's responsibility to will be automatically escaped. However, it's the caller's responsibility to

View file

@ -10,7 +10,7 @@
This module adds the ability to import Python modules (:file:`\*.py`, This module adds the ability to import Python modules (:file:`\*.py`,
:file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not :file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not
needed to use the :mod:`zipimport` module explicitly; it is automatically used needed to use the :mod:`zipimport` module explicitly; it is automatically used
by the builtin :keyword:`import` mechanism for ``sys.path`` items that are paths by the built-in :keyword:`import` mechanism for ``sys.path`` items that are paths
to ZIP archives. to ZIP archives.
Typically, ``sys.path`` is a list of directory names as strings. This module Typically, ``sys.path`` is a list of directory names as strings. This module

View file

@ -1304,7 +1304,7 @@ access (use of, assignment to, or deletion of ``x.name``) for class instances.
.. note:: .. note::
This method may still be bypassed when looking up special methods as the This method may still be bypassed when looking up special methods as the
result of implicit invocation via language syntax or builtin functions. result of implicit invocation via language syntax or built-in functions.
See :ref:`special-lookup`. See :ref:`special-lookup`.
@ -1696,12 +1696,12 @@ through the container; for mappings, :meth:`__iter__` should be the same as
.. method:: object.__reversed__(self) .. method:: object.__reversed__(self)
Called (if present) by the :func:`reversed` builtin to implement Called (if present) by the :func:`reversed` built-in to implement
reverse iteration. It should return a new iterator object that iterates reverse iteration. It should return a new iterator object that iterates
over all the objects in the container in reverse order. over all the objects in the container in reverse order.
If the :meth:`__reversed__` method is not provided, the :func:`reversed` If the :meth:`__reversed__` method is not provided, the :func:`reversed`
builtin will fall back to using the sequence protocol (:meth:`__len__` and built-in will fall back to using the sequence protocol (:meth:`__len__` and
:meth:`__getitem__`). Objects that support the sequence protocol should :meth:`__getitem__`). Objects that support the sequence protocol should
only provide :meth:`__reversed__` if they can provide an implementation only provide :meth:`__reversed__` if they can provide an implementation
that is more efficient than the one provided by :func:`reversed`. that is more efficient than the one provided by :func:`reversed`.

View file

@ -112,8 +112,8 @@ If the :keyword:`global` statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the top-level specified in the statement refer to the binding of that name in the top-level
namespace. Names are resolved in the top-level namespace by searching the namespace. Names are resolved in the top-level namespace by searching the
global namespace, i.e. the namespace of the module containing the code block, global namespace, i.e. the namespace of the module containing the code block,
and the builtin namespace, the namespace of the module :mod:`builtins`. The and the builtins namespace, the namespace of the module :mod:`builtins`. The
global namespace is searched first. If the name is not found there, the builtin global namespace is searched first. If the name is not found there, the builtins
namespace is searched. The global statement must precede all uses of the name. namespace is searched. The global statement must precede all uses of the name.
.. XXX document "nonlocal" semantics here .. XXX document "nonlocal" semantics here

View file

@ -641,7 +641,7 @@ the call.
.. note:: .. note::
An implementation may provide builtin functions whose positional parameters do An implementation may provide built-in functions whose positional parameters do
not have names, even if they are 'named' for the purpose of documentation, and not have names, even if they are 'named' for the purpose of documentation, and
which therefore cannot be supplied by keyword. In CPython, this is the case for which therefore cannot be supplied by keyword. In CPython, this is the case for
functions implemented in C that use :cfunc:`PyArg_ParseTuple` to parse their functions implemented in C that use :cfunc:`PyArg_ParseTuple` to parse their
@ -996,7 +996,7 @@ operators *always* consider objects of different types to be unequal, while the
``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when ``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
comparing objects of different types that do not implement these operators for comparing objects of different types that do not implement these operators for
the given pair of types. You can control comparison behavior of objects of the given pair of types. You can control comparison behavior of objects of
non-builtin types by defining rich comparison methods like :meth:`__gt__`, non-built-in types by defining rich comparison methods like :meth:`__gt__`,
described in section :ref:`customization`. described in section :ref:`customization`.
Comparison of objects of the same type depends on the type: Comparison of objects of the same type depends on the type:
@ -1037,7 +1037,7 @@ Comparison of objects of the same type depends on the type:
which depend on total ordering. For example, :func:`min`, :func:`max`, and which depend on total ordering. For example, :func:`min`, :func:`max`, and
:func:`sorted` produce undefined results given a list of sets as inputs. :func:`sorted` produce undefined results given a list of sets as inputs.
* Most other objects of builtin types compare unequal unless they are the same * Most other objects of built-in types compare unequal unless they are the same
object; the choice whether one object is considered smaller or larger than object; the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one execution of a another one is made arbitrarily but consistently within one execution of a
program. program.

View file

@ -881,7 +881,7 @@ Note that there is nothing special about the statement::
That is not a future statement; it's an ordinary import statement with no That is not a future statement; it's an ordinary import statement with no
special semantics or syntax restrictions. special semantics or syntax restrictions.
Code compiled by calls to the builtin functions :func:`exec` and :func:`compile` Code compiled by calls to the built-in functions :func:`exec` and :func:`compile`
that occur in a module :mod:`M` containing a future statement will, by default, that occur in a module :mod:`M` containing a future statement will, by default,
use the new syntax or semantics associated with the future statement. This can use the new syntax or semantics associated with the future statement. This can
be controlled by optional arguments to :func:`compile` --- see the documentation be controlled by optional arguments to :func:`compile` --- see the documentation

View file

@ -12,44 +12,41 @@ user not to "break into the definition." The most important features of classes
are retained with full power, however: the class inheritance mechanism allows are retained with full power, however: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its base multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same class or classes, and a method can call the method of a base class with the same
name. Objects can contain an arbitrary amount of private data. name. Objects can contain an arbitrary amount of data.
In C++ terminology, normally class members (including the data members) are In C++ terminology, normally class members (including the data members) are
*public* (except see below :ref:`tut-private`), *public* (except see below :ref:`tut-private`),
and all member functions are *virtual*. There are no special constructors or and all member functions are *virtual*. As in Modula-3, there are no shorthands
destructors. As in Modula-3, there are no shorthands for referencing the for referencing the object's members from its methods: the method function is
object's members from its methods: the method function is declared with an declared with an explicit first argument representing the object, which is
explicit first argument representing the object, which is provided implicitly by provided implicitly by the call. As in Smalltalk, classes themselves are
the call. As in Smalltalk, classes themselves are objects, albeit in the wider objects. This provides semantics for importing and renaming. Unlike C++ and
sense of the word: in Python, all data types are objects. This provides Modula-3, built-in types can be used as base classes for extension by the user.
semantics for importing and renaming. Unlike C++ and Modula-3, built-in types Also, like in C++, most built-in operators with special syntax (arithmetic
can be used as base classes for extension by the user. Also, like in C++ but
unlike in Modula-3, most built-in operators with special syntax (arithmetic
operators, subscripting etc.) can be redefined for class instances. operators, subscripting etc.) can be redefined for class instances.
(Lacking universally accepted terminology to talk about classes, I will make
.. _tut-terminology: occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since
A Word About Terminology
========================
Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms. (I would use Modula-3 terms, since
its object-oriented semantics are closer to those of Python than C++, but I its object-oriented semantics are closer to those of Python than C++, but I
expect that few readers have heard of it.) expect that few readers have heard of it.)
.. _tut-object:
A Word About Names and Objects
==============================
Objects have individuality, and multiple names (in multiple scopes) can be bound Objects have individuality, and multiple names (in multiple scopes) can be bound
to the same object. This is known as aliasing in other languages. This is to the same object. This is known as aliasing in other languages. This is
usually not appreciated on a first glance at Python, and can be safely ignored usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples). However, when dealing with immutable basic types (numbers, strings, tuples). However,
aliasing has an (intended!) effect on the semantics of Python code involving aliasing has a possibly surprising effect on the semantics of Python code
mutable objects such as lists, dictionaries, and most types representing involving mutable objects such as lists, dictionaries, and most other types.
entities outside the program (files, windows, etc.). This is usually used to This is usually used to the benefit of the program, since aliases behave like
the benefit of the program, since aliases behave like pointers in some respects. pointers in some respects. For example, passing an object is cheap since only a
For example, passing an object is cheap since only a pointer is passed by the pointer is passed by the implementation; and if a function modifies an object
implementation; and if a function modifies an object passed as an argument, the passed as an argument, the caller will see the change --- this eliminates the
caller will see the change --- this eliminates the need for two different need for two different argument passing mechanisms as in Pascal.
argument passing mechanisms as in Pascal.
.. _tut-scopes: .. _tut-scopes:
@ -73,7 +70,7 @@ built-in exception names); the global names in a module; and the local names in
a function invocation. In a sense the set of attributes of an object also form a function invocation. In a sense the set of attributes of an object also form
a namespace. The important thing to know about namespaces is that there is a namespace. The important thing to know about namespaces is that there is
absolutely no relation between names in different namespaces; for instance, two absolutely no relation between names in different namespaces; for instance, two
different modules may both define a function "maximize" without confusion --- different modules may both define a function ``maximize`` without confusion ---
users of the modules must prefix it with the module name. users of the modules must prefix it with the module name.
By the way, I use the word *attribute* for any name following a dot --- for By the way, I use the word *attribute* for any name following a dot --- for
@ -112,11 +109,13 @@ name attempts to find the name in the namespace.
Although scopes are determined statically, they are used dynamically. At any Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces time during execution, there are at least three nested scopes whose namespaces
are directly accessible: the innermost scope, which is searched first, contains are directly accessible:
the local names; the namespaces of any enclosing functions, which are searched
starting with the nearest enclosing scope; the middle scope, searched next, * the innermost scope, which is searched first, contains the local names
contains the current module's global names; and the outermost scope (searched * the scopes of any enclosing functions, which are searched starting with the
last) is the namespace containing built-in names. nearest enclosing scope, contains non-local, but also non-global names
* the next-to-last scope contains the current module's global names
* the outermost scope (searched last) is the namespace containing built-in names
If a name is declared global, then all references and assignments go directly to If a name is declared global, then all references and assignments go directly to
the middle scope containing the module's global names. To rebind variables the middle scope containing the module's global names. To rebind variables
@ -138,15 +137,15 @@ language definition is evolving towards static name resolution, at "compile"
time, so don't rely on dynamic name resolution! (In fact, local variables are time, so don't rely on dynamic name resolution! (In fact, local variables are
already determined statically.) already determined statically.)
A special quirk of Python is that -- if no :keyword:`global` or A special quirk of Python is that -- if no :keyword:`global` statement is in
:keyword:`nonlocal` statement is in effect -- assignments to names always go effect -- assignments to names always go into the innermost scope. Assignments
into the innermost scope. Assignments do not copy data --- they just bind names do not copy data --- they just bind names to objects. The same is true for
to objects. The same is true for deletions: the statement ``del x`` removes the deletions: the statement ``del x`` removes the binding of ``x`` from the
binding of ``x`` from the namespace referenced by the local scope. In fact, all namespace referenced by the local scope. In fact, all operations that introduce
operations that introduce new names use the local scope: in particular, import new names use the local scope: in particular, :keyword:`import` statements and
statements and function definitions bind the module or function name in the function definitions bind the module or function name in the local scope. (The
local scope. (The :keyword:`global` statement can be used to indicate that :keyword:`global` statement can be used to indicate that particular variables
particular variables live in the global scope.) live in the global scope.)
The :keyword:`global` statement can be used to indicate that particular The :keyword:`global` statement can be used to indicate that particular
variables live in the global scope and should be rebound there; the variables live in the global scope and should be rebound there; the
@ -424,9 +423,9 @@ glancing through a method.
Often, the first argument of a method is called ``self``. This is nothing more Often, the first argument of a method is called ``self``. This is nothing more
than a convention: the name ``self`` has absolutely no special meaning to than a convention: the name ``self`` has absolutely no special meaning to
Python. (Note, however, that by not following the convention your code may be Python. Note, however, that by not following the convention your code may be
less readable to other Python programmers, and it is also conceivable that a less readable to other Python programmers, and it is also conceivable that a
*class browser* program might be written that relies upon such a convention.) *class browser* program might be written that relies upon such a convention.
Any function object that is a class attribute defines a method for instances of Any function object that is a class attribute defines a method for instances of
that class. It is not necessary that the function definition is textually that class. It is not necessary that the function definition is textually
@ -462,13 +461,13 @@ argument::
Methods may reference global names in the same way as ordinary functions. The Methods may reference global names in the same way as ordinary functions. The
global scope associated with a method is the module containing the class global scope associated with a method is the module containing the class
definition. (The class itself is never used as a global scope!) While one definition. (The class itself is never used as a global scope.) While one
rarely encounters a good reason for using global data in a method, there are rarely encounters a good reason for using global data in a method, there are
many legitimate uses of the global scope: for one thing, functions and modules many legitimate uses of the global scope: for one thing, functions and modules
imported into the global scope can be used by methods, as well as functions and imported into the global scope can be used by methods, as well as functions and
classes defined in it. Usually, the class containing the method is itself classes defined in it. Usually, the class containing the method is itself
defined in this global scope, and in the next section we'll find some good defined in this global scope, and in the next section we'll find some good
reasons why a method would want to reference its own class! reasons why a method would want to reference its own class.
Each value is an object, and therefore has a *class* (also called its *type*). Each value is an object, and therefore has a *class* (also called its *type*).
It is stored as ``object.__class__``. It is stored as ``object.__class__``.
@ -519,12 +518,12 @@ An overriding method in a derived class may in fact want to extend rather than
simply replace the base class method of the same name. There is a simple way to simply replace the base class method of the same name. There is a simple way to
call the base class method directly: just call ``BaseClassName.methodname(self, call the base class method directly: just call ``BaseClassName.methodname(self,
arguments)``. This is occasionally useful to clients as well. (Note that this arguments)``. This is occasionally useful to clients as well. (Note that this
only works if the base class is defined or imported directly in the global only works if the base class is accessible as ``BaseClassName`` in the global
scope.) scope.)
Python has two built-in functions that work with inheritance: Python has two built-in functions that work with inheritance:
* Use :func:`isinstance` to check an object's type: ``isinstance(obj, int)`` * Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)``
will be ``True`` only if ``obj.__class__`` is :class:`int` or some class will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
derived from :class:`int`. derived from :class:`int`.
@ -582,28 +581,30 @@ http://www.python.org/download/releases/2.3/mro/.
Private Variables Private Variables
================= =================
There is limited support for class-private identifiers. Any identifier of the "Private" instance variables that cannot be accessed except from inside an
form ``__spam`` (at least two leading underscores, at most one trailing object, don't exist in Python. However, there is a convention that is followed
underscore) is textually replaced with ``_classname__spam``, where ``classname`` by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
is the current class name with leading underscore(s) stripped. This mangling is be treated as a non-public part of the API (whether it is a function, a method
done without regard to the syntactic position of the identifier, so it can be or a data member). It should be considered an implementation detail and subject
used to define class-private instance and class variables, methods, variables to change without notice.
stored in globals, and even variables stored in instances. private to this class
on instances of *other* classes. Truncation may occur when the mangled name
would be longer than 255 characters. Outside classes, or when the class name
consists of only underscores, no mangling occurs.
Name mangling is intended to give classes an easy way to define "private" Since there is a valid use-case for class-private members (namely to avoid name
instance variables and methods, without having to worry about instance variables clashes of names with names defined by subclasses), there is limited support for
defined by derived classes, or mucking with instance variables by code outside such a mechanism, called :dfn:`name mangling`. Any identifier of the form
the class. Note that the mangling rules are designed mostly to avoid accidents; ``__spam`` (at least two leading underscores, at most one trailing underscore)
it still is possible for a determined soul to access or modify a variable that is textually replaced with ``_classname__spam``, where ``classname`` is the
is considered private. This can even be useful in special circumstances, such current class name with leading underscore(s) stripped. This mangling is done
as in the debugger, and that's one reason why this loophole is not closed. without regard to the syntactic position of the identifier, so it can be used to
(Buglet: derivation of a class with the same name as the base class makes use of define class-private instance and class variables, methods, variables stored in
private variables of the base class possible.) globals, and even variables stored in instances. Truncation may occur when the
mangled name would be longer than 255 characters. Outside classes, or when the
class name consists of only underscores, no mangling occurs.
Notice that code passed to ``exec()`` or ``eval()`` does not Note that the mangling rules are designed mostly to avoid accidents; it still is
possible to access or modify a variable that is considered private. This can
even be useful in special circumstances, such as in the debugger.
Notice that code passed to ``exec()``, ``eval()`` or ``execfile()`` does not
consider the classname of the invoking class to be the current class; this is consider the classname of the invoking class to be the current class; this is
similar to the effect of the ``global`` statement, the effect of which is similar to the effect of the ``global`` statement, the effect of which is
likewise restricted to code that is byte-compiled together. The same likewise restricted to code that is byte-compiled together. The same
@ -654,7 +655,7 @@ Exceptions Are Classes Too
User-defined exceptions are identified by classes as well. Using this mechanism User-defined exceptions are identified by classes as well. Using this mechanism
it is possible to create extensible hierarchies of exceptions. it is possible to create extensible hierarchies of exceptions.
There are two valid (semantic) forms for the raise statement:: There are two new valid (semantic) forms for the :keyword:`raise` statement::
raise Class raise Class
@ -665,10 +666,10 @@ class derived from it. The first form is a shorthand for::
raise Class() raise Class()
A class in an except clause is compatible with an exception if it is the same A class in an :keyword:`except` clause is compatible with an exception if it is
class or a base class thereof (but not the other way around --- an except clause the same class or a base class thereof (but not the other way around --- an
listing a derived class is not compatible with a base class). For example, the except clause listing a derived class is not compatible with a base class). For
following code will print B, C, D in that order:: example, the following code will print B, C, D in that order::
class B(Exception): class B(Exception):
pass pass

View file

@ -130,16 +130,17 @@ Basic usage of the :meth:`str.format` method looks like this::
We are the knights who say "Ni!" We are the knights who say "Ni!"
The brackets and characters within them (called format fields) are replaced with The brackets and characters within them (called format fields) are replaced with
the objects passed into the format method. The number in the brackets refers to the objects passed into the :meth:`~str.format` method. The number in the
the position of the object passed into the format method. :: brackets refers to the position of the object passed into the
:meth:`~str.format` method. ::
>>> print('{0} and {1}'.format('spam', 'eggs')) >>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs')) >>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam eggs and spam
If keyword arguments are used in the format method, their values are referred to If keyword arguments are used in the :meth:`~str.format` method, their values
by using the name of the argument. :: are referred to by using the name of the argument. ::
>>> print('This {food} is {adjective}.'.format( >>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible')) ... food='spam', adjective='absolutely horrible'))
@ -160,7 +161,7 @@ truncates the Pi to three places after the decimal.
The value of PI is approximately 3.142. The value of PI is approximately 3.142.
Passing an integer after the ``':'`` will cause that field to be a minimum Passing an integer after the ``':'`` will cause that field to be a minimum
number of characters wide. This is useful for making tables pretty.:: number of characters wide. This is useful for making tables pretty. ::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items(): >>> for name, phone in table.items():
@ -181,7 +182,7 @@ square brackets ``'[]'`` to access the keys ::
Jack: 4098; Sjoerd: 4127; Dcab: 8637678 Jack: 4098; Sjoerd: 4127; Dcab: 8637678
This could also be done by passing the table as keyword arguments with the '**' This could also be done by passing the table as keyword arguments with the '**'
notation.:: notation. ::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
@ -374,9 +375,9 @@ shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
>>> f.closed >>> f.closed
True True
File objects have some additional methods, such as :meth:`isatty` and File objects have some additional methods, such as :meth:`~file.isatty` and
:meth:`truncate` which are less frequently used; consult the Library Reference :meth:`~file.truncate` which are less frequently used; consult the Library
for a complete guide to file objects. Reference for a complete guide to file objects.
.. _tut-pickle: .. _tut-pickle:

View file

@ -6,8 +6,8 @@ Interactive Input Editing and History Substitution
Some versions of the Python interpreter support editing of the current input Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell. This is implemented using the *GNU Readline* library, which the GNU Bash shell. This is implemented using the `GNU Readline`_ library,
supports Emacs-style and vi-style editing. This library has its own which supports Emacs-style and vi-style editing. This library has its own
documentation which I won't duplicate here; however, the basics are easily documentation which I won't duplicate here; however, the basics are easily
explained. The interactive editing and history described here are optionally explained. The interactive editing and history described here are optionally
available in the Unix and Cygwin versions of the interpreter. available in the Unix and Cygwin versions of the interpreter.
@ -148,8 +148,8 @@ interpreter. ::
.. _tut-commentary: .. _tut-commentary:
Commentary Alternatives to the Interactive Interpreter
========== ===========================================
This facility is an enormous step forward compared to earlier versions of the This facility is an enormous step forward compared to earlier versions of the
interpreter; however, some wishes are left: It would be nice if the proper interpreter; however, some wishes are left: It would be nice if the proper
@ -158,8 +158,12 @@ token is required next). The completion mechanism might use the interpreter's
symbol table. A command to check (or even suggest) matching parentheses, symbol table. A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful. quotes, etc., would also be useful.
.. % One alternative enhanced interactive interpreter that has been around for quite
Do we mention IPython? DUBOIS some time is `IPython`_, which features tab completion, object exploration and
advanced history management. It can also be thoroughly customized and embedded
into other applications. Another similar enhanced interactive environment is
`bpython`_.
.. rubric:: Footnotes .. rubric:: Footnotes
@ -167,3 +171,7 @@ quotes, etc., would also be useful.
:envvar:`PYTHONSTARTUP` environment variable when you start an interactive :envvar:`PYTHONSTARTUP` environment variable when you start an interactive
interpreter. interpreter.
.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
.. _IPython: http://ipython.scipy.org/
.. _bpython: http://www.bpython-interpreter.org/

View file

@ -448,14 +448,14 @@ one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all. Unfortunately, submodules are present in the package, and imports them all. Unfortunately,
this operation does not work very well on Windows platforms, where the this operation does not work very well on Windows platforms, where the
filesystem does not always have accurate information about the case of a filesystem does not always have accurate information about the case of a
filename! On these platforms, there is no guaranteed way to know whether a file filename. On these platforms, there is no guaranteed way to know whether a file
:file:`ECHO.PY` should be imported as a module :mod:`echo`, :mod:`Echo` or :file:`ECHO.PY` should be imported as a module :mod:`echo`, :mod:`Echo` or
:mod:`ECHO`. (For example, Windows 95 has the annoying practice of showing all :mod:`ECHO`. (For example, Windows 95 has the annoying practice of showing all
file names with a capitalized first letter.) The DOS 8+3 filename restriction file names with a capitalized first letter.) The DOS 8+3 filename restriction
adds another interesting problem for long module names. adds another interesting problem for long module names.
The only solution is for the package author to provide an explicit index of the The only solution is for the package author to provide an explicit index of the
package. The import statement uses the following convention: if a package's package. The :keyword:`import` statement uses the following convention: if a package's
:file:`__init__.py` code defines a list named ``__all__``, it is taken to be the :file:`__init__.py` code defines a list named ``__all__``, it is taken to be the
list of module names that should be imported when ``from package import *`` is list of module names that should be imported when ``from package import *`` is
encountered. It is up to the package author to keep this list up-to-date when a encountered. It is up to the package author to keep this list up-to-date when a
@ -476,16 +476,16 @@ been imported (possibly running any initialization code in :file:`__init__.py`)
and then imports whatever names are defined in the package. This includes any and then imports whatever names are defined in the package. This includes any
names defined (and submodules explicitly loaded) by :file:`__init__.py`. It names defined (and submodules explicitly loaded) by :file:`__init__.py`. It
also includes any submodules of the package that were explicitly loaded by also includes any submodules of the package that were explicitly loaded by
previous import statements. Consider this code:: previous :keyword:`import` statements. Consider this code::
import sound.effects.echo import sound.effects.echo
import sound.effects.surround import sound.effects.surround
from sound.effects import * from sound.effects import *
In this example, the echo and surround modules are imported in the current In this example, the :mod:`echo` and :mod:`surround` modules are imported in the
namespace because they are defined in the :mod:`sound.effects` package when the current namespace because they are defined in the :mod:`sound.effects` package
``from...import`` statement is executed. (This also works when ``__all__`` is when the ``from...import`` statement is executed. (This also works when
defined.) ``__all__`` is defined.)
Note that in general the practice of importing ``*`` from a module or package is Note that in general the practice of importing ``*`` from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to frowned upon, since it often causes poorly readable code. However, it is okay to
@ -537,5 +537,6 @@ modules found in a package.
.. rubric:: Footnotes .. rubric:: Footnotes
.. [#] In fact function definitions are also 'statements' that are 'executed'; the .. [#] In fact function definitions are also 'statements' that are 'executed'; the
execution enters the function name in the module's global symbol table. execution of a module-level function enters the function name in the module's
global symbol table.

View file

@ -347,12 +347,15 @@ Decimal Floating Point Arithmetic
The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal
floating point arithmetic. Compared to the built-in :class:`float` floating point arithmetic. Compared to the built-in :class:`float`
implementation of binary floating point, the new class is especially helpful for implementation of binary floating point, the class is especially helpful for
financial applications and other uses which require exact decimal
representation, control over precision, control over rounding to meet legal or * financial applications and other uses which require exact decimal
regulatory requirements, tracking of significant decimal places, or for representation,
applications where the user expects the results to match calculations done by * control over precision,
hand. * control over rounding to meet legal or regulatory requirements,
* tracking of significant decimal places, or
* applications where the user expects the results to match calculations done by
hand.
For example, calculating a 5% tax on a 70 cent phone charge gives different For example, calculating a 5% tax on a 70 cent phone charge gives different
results in decimal floating point and binary floating point. The difference results in decimal floating point and binary floating point. The difference

View file

@ -86,7 +86,7 @@ source.
.. note:: .. note::
This option cannot be used with builtin modules and extension modules This option cannot be used with built-in modules and extension modules
written in C, since they do not have Python module files. However, it written in C, since they do not have Python module files. However, it
can still be used for precompiled modules, even if the original source can still be used for precompiled modules, even if the original source
file is not available. file is not available.

View file

@ -1173,7 +1173,7 @@ Some of the more notable changes are:
can uncomment them. Gestalt and Internet Config modules are enabled by can uncomment them. Gestalt and Internet Config modules are enabled by
default. default.
* Keyword arguments passed to builtin functions that don't take them now cause a * Keyword arguments passed to built-in functions that don't take them now cause a
:exc:`TypeError` exception to be raised, with the message "*function* takes no :exc:`TypeError` exception to be raised, with the message "*function* takes no
keyword arguments". keyword arguments".

View file

@ -2823,7 +2823,7 @@ JSON (Javascript Object Notation). JSON is a lightweight interchange format
often used in web applications. For more information about JSON, see often used in web applications. For more information about JSON, see
http://www.json.org. http://www.json.org.
:mod:`json` comes with support for decoding and encoding most builtin Python :mod:`json` comes with support for decoding and encoding most built-in Python
types. The following example encodes and decodes a dictionary:: types. The following example encodes and decodes a dictionary::
>>> import json >>> import json

View file

@ -29,7 +29,7 @@ end
# print the local variables of the current frame # print the local variables of the current frame
define pylocals define pylocals
set $_i = 0 set $_i = 0
while $_i < f->f_nlocals while $_i < f->f_code->co_nlocals
if f->f_localsplus + $_i != 0 if f->f_localsplus + $_i != 0
set $_names = co->co_varnames set $_names = co->co_varnames
set $_name = _PyUnicode_AsString(PyTuple_GetItem($_names, $_i)) set $_name = _PyUnicode_AsString(PyTuple_GetItem($_names, $_i))

View file

@ -1958,7 +1958,6 @@ is a single character. The following type codes are defined:\n\
'H' unsigned integer 2 \n\ 'H' unsigned integer 2 \n\
'i' signed integer 2 \n\ 'i' signed integer 2 \n\
'I' unsigned integer 2 \n\ 'I' unsigned integer 2 \n\
'w' unicode character 4 \n\
'l' signed integer 4 \n\ 'l' signed integer 4 \n\
'L' unsigned integer 4 \n\ 'L' unsigned integer 4 \n\
'f' floating point 4 \n\ 'f' floating point 4 \n\

View file

@ -331,7 +331,7 @@ PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
{ {
if (!PyObject_CheckBuffer(obj)) { if (!PyObject_CheckBuffer(obj)) {
PyErr_Format(PyExc_TypeError, PyErr_Format(PyExc_TypeError,
"'%100s' does not have the buffer interface", "'%100s' does not support the buffer interface",
Py_TYPE(obj)->tp_name); Py_TYPE(obj)->tp_name);
return -1; return -1;
} }

View file

@ -179,7 +179,7 @@ validate_and_copy_tuple(PyObject *tup)
} }
PyDoc_STRVAR(code_doc, PyDoc_STRVAR(code_doc,
"code(argcount, kwonlyargcount nlocals, stacksize, flags, codestring,\n\ "code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,\n\
constants, names, varnames, filename, name, firstlineno,\n\ constants, names, varnames, filename, name, firstlineno,\n\
lnotab[, freevars[, cellvars]])\n\ lnotab[, freevars[, cellvars]])\n\
\n\ \n\

View file

@ -255,7 +255,7 @@ PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char fort)
if (!PyObject_CheckBuffer(obj)) { if (!PyObject_CheckBuffer(obj)) {
PyErr_SetString(PyExc_TypeError, PyErr_SetString(PyExc_TypeError,
"object does not have the buffer interface"); "object does not support the buffer interface");
return NULL; return NULL;
} }