In both cases, *\*buffer_length* is set to the length of the encoded data
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
them. Instead, the implementation assumes that the string object uses the
encoding passed in as parameter.
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
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.
Some exporters may not be able to share memory in every possible way and
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`.
-.. cfunction:: double PyFloat_GetMin(void)
+.. cfunction:: double PyFloat_GetMin()
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
be freed.
*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
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
to the importer object.
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.
This is the typical calling convention, where the methods have the type
:ctype:`PyCFunction`. The function expects two :ctype:`PyObject\*` values.
- The first one is the *self* object for methods; for module functions, it
- has the value given to :cfunc:`Py_InitModule4` (or *NULL* if
- :cfunc:`Py_InitModule` was used). The second parameter (often called
- *args*) is a tuple object representing all arguments. This parameter is
- typically processed using :cfunc:`PyArg_ParseTuple` or
- :cfunc:`PyArg_UnpackTuple`.
+ The first one is the *self* object for methods; for module functions, it is
+ the module object. The second parameter (often called *args*) is a tuple
+ object representing all arguments. This parameter is typically processed
+ using :cfunc:`PyArg_ParseTuple` or :cfunc:`PyArg_UnpackTuple`.
.. data:: METH_KEYWORDS
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
- :ctype:`PyCFunction`. When used with object methods, the first parameter is
- typically named ``self`` and will hold a reference to the object instance.
- In all cases the second parameter will be *NULL*.
+ :ctype:`PyCFunction`. The first parameter is typically named *self* and will
+ hold a reference to the module or object instance. In all cases the second
+ parameter will be *NULL*.
.. data:: METH_O
case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
on error.
-.. cfunction:: void PySys_ResetWarnOptions(void)
+.. cfunction:: void PySys_ResetWarnOptions()
Reset :data:`sys.warnoptions` to an empty list.
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.
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.
:ctype:`PyUnicodeObject` (not checked).
-.. cfunction:: int PyUnicode_ClearFreeList(void)
+.. cfunction:: int PyUnicode_ClearFreeList()
Clear the free list. Return the total number of freed items.
+
Unicode provides many different character properties. The most often needed ones
are available through these macros which are mapped to C functions depending on
the Python configuration.
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.
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
-builtin unicode() Unicode object constructor.
+built-in :func:`unicode` Unicode object constructor.
Setting encoding to *NULL* causes the default encoding to be used
which is ASCII. The file system calls should 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
-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
generic ones are documented for simplicity.
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
- 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
the codec.
+------------------+--------------------------------+---------+
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
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.
.. method:: TextFile.open(filename)
- Open a new file *filename*. This overrides any *file* or *filename* constructor
- arguments.
+ Open a new file *filename*. This overrides any *file* or *filename*
+ constructor arguments.
.. method:: TextFile.close()
function. The C function always has two arguments, conventionally named *self*
and *args*.
-The *self* argument is only used when the C function implements a built-in
-method, not a function. In the example, *self* will always be a *NULL* pointer,
-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 *self* argument points to the module object for module-level functions;
+for a method it would point to the object instance.
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
these :class:`PyTypeObject` structures between extension modules.
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
increases an internal counter. ::
abstract base class
Abstract Base Classes (abbreviated ABCs) complement :term:`duck-typing` by
- providing a way to define interfaces when other techniques like :func:`hasattr`
- would be clumsy. Python comes with many builtin ABCs for data structures
- (in the :mod:`collections` module), numbers (in the :mod:`numbers`
- module), and streams (in the :mod:`io` module). You can create your own
- ABC with the :mod:`abc` module.
+ providing a way to define interfaces when other techniques like
+ :func:`hasattr` would be clumsy. Python comes with many built-in ABCs for
+ data structures (in the :mod:`collections` module), numbers (in the
+ :mod:`numbers` module), and streams (in the :mod:`io` module). You can
+ create your own ABC with the :mod:`abc` module.
argument
A value passed to a function or method, assigned to a named local
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
``-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
``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
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
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
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``
namespace
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
modularity by preventing naming conflicts. For instance, the functions
:func:`builtins.open` and :func:`os.open` are distinguished by their
More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and
: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
sequence with comparable semantics, for example, yet many people write their own
:func:`max`/:func:`min`. Another highly useful function is
Handling Exceptions
===================
-*urlopen* raises :exc:`URLError` when it cannot handle a response (though as usual
-with Python APIs, builtin exceptions such as
-:exc:`ValueError`, :exc:`TypeError` etc. may also
-be raised).
+*urlopen* raises :exc:`URLError` when it cannot handle a response (though as
+usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
+:exc:`TypeError` etc. may also be raised).
:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
HTTP URLs.
row = cur.fetchone()
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
con.text_factory = sqlite3.OptimizedUnicode
cur.execute("select ?", (AUSTRIA,))
The :option:`-v` option enables output of more information on the translation
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:
.. 2to3fixer:: itertools
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`.
.. 2to3fixer:: long
.. 2to3fixer:: next
- Converts the use of iterator's :meth:`next` methods to the :func:`next`
- function. It also renames :meth:`next` methods to :meth:`~object.__next__`.
+ Converts the use of iterator's :meth:`~iterator.next` methods to the
+ :func:`next` function. It also renames :meth:`next` methods to
+ :meth:`~object.__next__`.
.. 2to3fixer:: nonzero
:meth:`getOptionalRelease` and :meth:`getMandatoryRelease`.
*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`
attribute on :class:`_Feature` instances.
time how many samples you are going to write in total and use
: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:
Close the AIFF file. After calling this method, the object can no longer be
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
the following methods exist. The :meth:`get\*` methods can only be called after
the corresponding :meth:`set\*` methods have been called. Before the first
+-----------+----------------+-------------------+-----------------------+
| ``'B'`` | unsigned char | int | 1 |
+-----------+----------------+-------------------+-----------------------+
-| ``'u'`` | Py_UNICODE | Unicode character | 2 |
+| ``'u'`` | Py_UNICODE | Unicode character | 2 (see note) |
+-----------+----------------+-------------------+-----------------------+
| ``'h'`` | signed short | int | 2 |
+-----------+----------------+-------------------+-----------------------+
| ``'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
(strictly speaking, by the C implementation). The actual size can be accessed
through the :attr:`itemsize` attribute.
grammar looks like.
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
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.
u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
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
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::
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
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`
-attribute. You can then read the data at leisure from 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::
fileitem = form["userfile"]
The file upload draft standard entertains the possibility of uploading multiple
files from one field (using a recursive :mimetype:`multipart/\*` encoding).
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/\*`). In this case, it can be iterated over recursively
just like the top-level form object.
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
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
:class:`FieldStorage` and :class:`MiniFieldStorage` items.
encoding error), ``'replace'`` (replace malformed data with a suitable
replacement marker, such as ``'?'``), ``'ignore'`` (ignore malformed data and
continue without further notice), ``'xmlcharrefreplace'`` (replace with the
- appropriate XML character reference (for encoding only)) and
- ``'backslashreplace'`` (replace with backslashed escape sequences (for encoding
- only)) as well as any other error handling name defined via
+ appropriate XML character reference (for encoding only)),
+ ``'backslashreplace'`` (replace with backslashed escape sequences (for
+ encoding only)), ``'surrogateescape'`` (replae with surrogate U+DCxx, see
+ :pep:`383`) as well as any other error handling name defined via
:func:`register_error`.
In case a search function cannot find a given encoding, it should return
.. class:: defaultdict([default_factory[, ...]])
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
:class:`dict` class and is not documented here.
constructor as a dictionary. Additional defaults may be passed into the
: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
dictionary type is passed that sorts its keys, the sections will be sorted on
write-back, as will be the keys within each section.
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
- 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
with ``newline=''``. [#]_ An optional
*dialect* parameter can be given which is used to define a set of parameters
.. 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
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
.. note::
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
- mentions a character.) The builtin :func:`ord` is handy for conveying strings to
- codes.
+ character (a string of length 1). (This note is true whenever the
+ documentation mentions a character.) The built-in :func:`ord` is handy for
+ conveying strings to codes.
Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any
character previously painter at that location. By default, the character
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
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
.. 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.
.. method:: min(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.
.. method:: next_minus([context])
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
``0``. If a number is given, return ``number.__int__()``. Conversion of
a base-radix integer literal optionally preceded by '+' or '-' (with no space
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
- 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``,
- ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code. Radix 0
- means to interpret exactly as a code literal, so that the actual radix is 2,
+ ``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 base is 2,
8, 10, or 16, and so that ``int('010', 0)`` is not legal, while
``int('010')`` is, as well as ``int('010', 8)``.
.. 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
:func:`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
candidates for translation, by wrapping them in a call to the :func:`_`
print(_('This string will be translated.'))
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.
binding it to ``_``.
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
:meth:`self.gettext`), ``'ngettext'`` (bound to :meth:`self.ngettext`),
``'lgettext'`` and ``'lngettext'``.
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
-``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.
.. sectionauthor:: Benjamin Peterson <benjamin@python.org>
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
defines the basic interface to a stream. Note, however, that there is no
stream for text.
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
.. data:: DEFAULT_BUFFER_SIZE
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.
.. function:: open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
closed. If a filename is given *closefd* has no effect and must be ``True``
(the default).
- 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'``,
+ 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'``,
``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
:class:`TextIOBase` (specifically :class:`TextIOWrapper`). When used to open
a file in a binary mode with buffering, the returned class is a subclass of
most *limit* bytes will be read.
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.
.. method:: readlines(hint=-1)
.. data:: LC_NUMERIC
- Locale category for formatting numbers. The functions :func:`format`,
- :func:`atoi`, :func:`atof` and :func:`str` of the :mod:`locale` module are
+ Locale category for formatting numbers. The functions :func:`.format`,
+ :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.
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`,
-:func:`format`, :func:`str`.
+:func:`.format`, :func:`.str`.
There is no way to perform case conversions and character classifications
according to the locale. For (Unicode) text strings these are done according
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
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:: apply(func[, args[, kwds]])
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
- for performing work in parallel. Additionally, the passed
- in function is only executed in one of the workers of the pool.
+ till the result is ready. Given this blocks, :meth:`apply_async` is better
+ suited for performing work in parallel. Additionally, the passed in
+ function is only executed in one of the workers of the pool.
.. method:: apply_async(func[, args[, kwds[, callback]]])
.. 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.
This method chops the iterable into a number of chunks which it submits to
.. 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
single argument. When the result becomes ready *callback* is applied to
make make the job complete **much** faster than using the default value of
``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:
``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
result cannot be returned within *timeout* seconds.
.. class:: Complex
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`, ``+``,
``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
except ``-`` and ``!=`` are abstract.
* ``args``, the list of positional arguments leftover after parsing options
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.
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
-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.
:mod:`optparse` always creates a special object for this, conventionally called
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*
options.
guide :mod:`optparse`'s behaviour; a few have required attributes, which you
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
- 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
- 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.
If ``choices`` is supplied (a list or tuple of strings), the type defaults to
``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
first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``). If there
parser.add_option("--clobber", action="store_true", 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
:attr:`dest`. If no default value for :attr:`dest` is supplied, an empty list
the command-line. If ``nargs`` > 1, multiple arguments are consumed, and a
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.
Example::
options.verbosity += 1
-* ``callback`` [required: ``callback``; relevant: :attr:`type`, ``nargs``,
+* ``callback`` [required: ``callback``; relevant: :attr:`!type`, ``nargs``,
``callback_args``, ``callback_kwargs``]
Call the function specified by ``callback``, which is called as ::
Determines :mod:`optparse`'s behaviour when this option is seen on the command
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
available option types are documented below.
* ``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`.
* ``const``
There are several other option attributes that you can supply when you define a
callback option:
-:attr:`type`
+:attr:`!type`
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
to your callback function.
``nargs``
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.
``callback_args``
``value``
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
- the type implied by the option's type. If :attr:`type` for this option is
+ 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
``None`` (no argument expected), then ``value`` will be ``None``. If ``nargs``
> 1, ``value`` will be a tuple of values of the appropriate type.
Things get slightly more interesting when you define callback options that take
a fixed number of arguments. Specifying that a callback option takes arguments
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``
arguments.
"typed" actions
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
- 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``,
``store_const``, ``append``, and ``count``, while the default "typed" actions
.. note::
- This function is intended for low-level I/O. For normal usage, use the built-in
- function :func:`open`, which returns a "file object" with :meth:`~file.read` and
- :meth:`~file.write` methods (and many more). To wrap a file descriptor in a "file
- object", use :func:`fdopen`.
+ This function is intended for low-level I/O. For normal usage, use the
+ built-in function :func:`open`, which returns a "file object" with
+ :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
+ wrap a file descriptor in a "file object", use :func:`fdopen`.
.. function:: openpty()
.. 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
- empty string is returned. Availability: Unix, Windows.
+ empty bytes object is returned. Availability: Unix, Windows.
.. note::
.. function:: write(fd, str)
- Write the string *str* to file descriptor *fd*. Return the number of bytes
- actually written. Availability: Unix, Windows.
+ Write the bytestring in *str* to file descriptor *fd*. Return the number of
+ bytes actually written. Availability: Unix, Windows.
.. note::
.. note::
- Using :func:`access` to check if a user is authorized to e.g. open a file before
- actually doing so using :func:`open` creates a security hole, because the user
- might exploit the short time interval between checking and opening the file to
- manipulate it.
+ Using :func:`access` to check if a user is authorized to e.g. open a file
+ before actually doing so using :func:`open` creates a security hole,
+ because the user might exploit the short time interval between checking
+ and opening the file to manipulate it.
.. note::
parameters at once. This is more convenient, but may not be as flexible in all
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:
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
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
breaks them onto multiple lines if they don't fit within the allowed width.
.. attribute:: Class.lineno
The line number of the ``class`` statement within the file named by
- :attr:`file`.
+ :attr:`~Class.file`.
.. _pyclbr-function-objects:
.. attribute:: Function.lineno
The line number of the ``def`` statement within the file named by
- :attr:`file`.
+ :attr:`~Function.file`.
flags are described in :ref:`contents-of-module-re`.) This
is useful if you wish to include the flags as part of the regular
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
used first in the expression string, or after one or more whitespace characters.
result = re.match(pattern, string)
- but using :func:`compile` and saving the resulting regular expression object
- for reuse is more efficient when the expression will be used several times
- in a single program.
+ but using :func:`re.compile` and saving the resulting regular expression
+ object for reuse is more efficient when the expression will be used several
+ times in a single program.
.. 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.
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'
- The pattern may be a string or an RE object; if you need to specify regular
- 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 pattern may be a string or an RE object.
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
.. note::
- If you want to locate a match anywhere in *string*, use :meth:`search`
- instead.
+ If you want to locate a match anywhere in *string*, use
+ :meth:`~RegexObject.search` instead.
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
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
- :meth:`match` method.
+ :meth:`~RegexObject.match` method.
.. method:: RegexObject.split(string[, maxsplit=0])
.. method:: MatchObject.expand(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
- converted to the appropriate characters, and numeric backreferences (``\1``,
- ``\2``) and named backreferences (``\g<1>``, ``\g<name>``) are replaced by the
- contents of the corresponding group.
+ string *template*, as done by the :meth:`~RegexObject.sub` method. Escapes
+ such as ``\n`` are converted to the appropriate characters, and numeric
+ backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
+ ``\g<name>``) are replaced by the contents of the corresponding group.
.. method:: MatchObject.group([group1, ...])
.. attribute:: MatchObject.pos
- The value of *pos* which was passed to the :func:`search` or :func:`match`
- method of the :class:`RegexObject`. This is the index into the string at which
- the RE engine started looking for a match.
+ The value of *pos* which was passed to the :meth:`~RegexObject.search` or
+ :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
+ index into the string at which the RE engine started looking for a match.
.. attribute:: MatchObject.endpos
- The value of *endpos* which was passed to the :func:`search` or :func:`match`
- method of the :class:`RegexObject`. This is the index into the string beyond
- which the RE engine will not go.
+ The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
+ :meth:`~RegexObject.match` method of the :class:`RegexObject`. This is the
+ index into the string beyond which the RE engine will not go.
.. attribute:: MatchObject.lastindex
.. attribute:: MatchObject.re
- The regular expression object whose :meth:`match` or :meth:`search` method
- produced this :class:`MatchObject` instance.
+ The regular expression object whose :meth:`~RegexObject.match` or
+ :meth:`~RegexObject.search` method produced this :class:`MatchObject`
+ instance.
.. attribute:: MatchObject.string
- The string passed to :func:`match` or :func:`search`.
+ The string passed to :meth:`~RegexObject.match` or
+ :meth:`~RegexObject.search`.
Examples
>>> displaymatch(pair.match("354aa")) # Pair of aces.
"<Match: '354aa', groups=('a',)>"
-To find out what card the pair consists of, one could use the :func:`group`
-method of :class:`MatchObject` in the following manner:
+To find out what card the pair consists of, one could use the
+:meth:`~MatchObject.group` method of :class:`MatchObject` in the following
+manner:
.. doctest::
.. data:: aRepr
- This is an instance of :class:`Repr` which is used to provide the :func:`repr`
- function described below. Changing the attributes of this object will affect
- the size limits used by :func:`repr` and the Python debugger.
+ This is an instance of :class:`Repr` which is used to provide the
+ :func:`.repr` function described below. Changing the attributes of this
+ object will affect the size limits used by :func:`.repr` and the Python
+ debugger.
.. function:: repr(obj)
- This is the :meth:`repr` method of ``aRepr``. It returns a string similar to
- that returned by the built-in function of the same name, but with limits on
- most sizes.
+ This is the :meth:`~Repr.repr` method of ``aRepr``. It returns a string
+ similar to that returned by the built-in function of the same name, but with
+ limits on most sizes.
.. _repr-objects:
.. 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
type-specific methods should call :meth:`repr1` to perform recursive formatting,
with ``level - 1`` for the value of *level* in the recursive call.
.. attribute:: kevent.filter
- Name of the kernel filter
+ Name of the kernel filter.
+---------------------------+---------------------------------------------+
| Constant | Meaning |
| | there is data available to read |
+---------------------------+---------------------------------------------+
| :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 |
+---------------------------+---------------------------------------------+
.. attribute:: kevent.flags
- Filter action
+ Filter action.
+---------------------------+---------------------------------------------+
| Constant | Meaning |
.. 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 |
| :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 |
| :const:`KQ_NOTE_REVOKE` | access to the file was revoked |
+----------------------------+--------------------------------------------+
-
- :const:`KQ_FILTER_PROC` filter flags
+ :const:`KQ_FILTER_PROC` filter flags:
+----------------------------+--------------------------------------------+
| Constant | Meaning |
| :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 |
.. attribute:: kevent.data
- Filter specific data
+ Filter specific data.
.. attribute:: kevent.udata
- User defined value
+ User defined value.
.. 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
in the third-party :mod:`bsddb` module from `pybsddb
<http://www.jcea.es/programacion/pybsddb.htm>`_ but not in other database
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
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
interpretation as for the :class:`Shelf` class.
The :meth:`ioctl` method is a limited interface to the WSAIoctl system
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)
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.
Rows wrapped with this class can be accessed both by index (like tuples) and
Comparisons
===========
-.. index:: pair: chaining; comparisons
-
-There are eight comparison operations in Python. They all have the same
-priority (which is higher than that of the Boolean operations). Comparisons can
-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
-evaluated at all when ``x < y`` is found to be false).
-
.. index::
+ pair: chaining; comparisons
pair: operator; comparison
operator: ==
operator: <
- operator: >
operator: <=
+ operator: >
operator: >=
operator: !=
operator: is
operator: is not
+There are eight comparison operations in Python. They all have the same
+priority (which is higher than that of the Boolean operations). Comparisons can
+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
+evaluated at all when ``x < y`` is found to be false).
+
This table summarizes the comparison operations:
+------------+-------------------------+
builtin: int
builtin: float
builtin: complex
+ operator: +
+ operator: -
+ operator: *
+ operator: /
+ operator: //
+ operator: %
+ operator: **
Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the "narrower" type is
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.
Negative numbers are treated as their 2's complement value (this assumes a
| ``~x`` | the bits of *x* inverted | |
+------------+--------------------------------+----------+
-.. index::
- triple: operations on; integer; types
- pair: bit-string; operations
- pair: shifting; operations
- pair: masking; operations
-
Notes:
(1)
order of insertion. Accordingly, sets do not support indexing, slicing, or
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
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.
"Format specifications" are used within replacement fields contained within a
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
specification is to be interpreted.
.. 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
An error raised when something is impossible because of Sun AU specs or
implementation deficiency.
-The :mod:`sunau` module defines the following data items:
+The :mod:`sunau` module defines the following data items:
.. data:: AUDIO_FILE_MAGIC
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()
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)
``'c_call'``
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'``
A C function has returned. *arg* is ``None``.
The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.
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
:keyword:`with` statement, just like a normal file.
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
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
be used in a :keyword:`with` statement, just like a normal file.
-
:mod:`threading` --- Higher-level threading interface
=====================================================
:noindex:
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
- :meth:`clear` method. The :meth:`wait` method blocks until the flag is true.
+ that can be set to true with the :meth:`~Event.set` method and reset to false
+ with the :meth:`clear` method. The :meth:`wait` method blocks until the flag
+ is true.
.. class:: local
.. 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
:class:`ThreadGroup` class is implemented.
*target* is the callable object to be invoked by the :meth:`run` method.
Defaults to ``None``, meaning nothing is called.
- *name* is the thread name. By default, a unique name is constructed of the form
- "Thread-*N*" where *N* is a small decimal number.
+ *name* is the thread name. By default, a unique name is constructed of the
+ form "Thread-*N*" where *N* is a small decimal number.
*args* is the argument tuple for the target invocation. Defaults to ``()``.
*kwargs* is a dictionary of keyword arguments for the target invocation.
Defaults to ``{}``.
- If the subclass overrides the constructor, it must make sure to invoke the base
- class constructor (``Thread.__init__()``) before doing anything else to the
- thread.
-
-
-.. method:: Thread.start()
-
- 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.
+ If the subclass overrides the constructor, it must make sure to invoke the
+ base class constructor (``Thread.__init__()``) before doing anything else to
+ the thread.
- This method will raise a :exc:`RuntimeException` if called more than once on the
- same thread object.
+ .. method:: start()
+ Start the thread's activity.
-.. method:: Thread.run()
+ 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.
- Method representing the thread's activity.
+ This method will raise a :exc:`RuntimeException` if called more than once
+ on the same thread object.
- 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:: run()
+ Method representing the thread's activity.
-.. method:: Thread.join([timeout])
+ 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.
- Wait until the thread terminates. This blocks the calling thread until the
- thread whose :meth:`join` method is called terminates -- either normally or
- through an unhandled exception -- or until the optional timeout occurs.
+ .. method:: join([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). 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.
+ Wait until the thread terminates. This blocks the calling thread until the
+ 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 not present or ``None``, the operation will block
- until the thread terminates.
+ 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.
- A thread can be :meth:`join`\ ed many times.
+ When the *timeout* argument is not present or ``None``, the operation will
+ block until the thread terminates.
- :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
- the current thread as that would cause a deadlock. It is also an error to
- :meth:`join` a thread before it has been started and attempts to do so
- raises the same exception.
+ A thread can be :meth:`join`\ ed many times.
+ :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
+ the current thread as that would cause a deadlock. It is also an error to
+ :meth:`join` a thread before it has been started and attempts to do so
+ raises the same exception.
-.. attribute:: Thread.name
+ .. attribute:: name
- 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.
+ 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.
+ .. method:: getName()
+ setName()
-.. method:: Thread.getName()
- Thread.setName()
+ Old getter/setter API for :attr:`~Thread.name`; use it directly as a
+ property instead.
- Old getter/setter API for :attr:`~Thread.name`; use it directly as a property
- instead.
+ .. attribute:: ident
+ The 'thread identifier' of this thread or ``None`` if the thread has not
+ been 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.
-.. attribute:: Thread.ident
+ .. method:: is_alive()
- The 'thread identifier' of this thread or ``None`` if the thread has not been
- 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.
+ 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.
-.. method:: Thread.is_alive()
+ .. attribute:: daemon
- Return whether the thread is alive.
+ 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``.
- 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.
+ The entire Python program exits when no alive non-daemon threads are left.
+ .. method:: isDaemon()
+ setDaemon()
-.. 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.
+ Old getter/setter API for :attr:`~Thread.daemon`; use it directly as a
+ property instead.
.. _lock-objects:
.. class:: Condition([lock])
- If the *lock* argument is given and not ``None``, it must be a :class:`Lock` or
- :class:`RLock` object, and it is used as the underlying lock. Otherwise, a new
- :class:`RLock` object is created and used as the underlying lock.
-
+ If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
+ or :class:`RLock` object, and it is used as the underlying lock. Otherwise,
+ a new :class:`RLock` object is created and used as the underlying lock.
-.. method:: Condition.acquire(*args)
+ .. method:: 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 underlying lock; the return value is whatever that method returns.
+ .. method:: release()
-.. method:: Condition.release()
+ Release the underlying lock. This method calls the corresponding method on
+ the underlying lock; there is no return value.
- Release the underlying lock. This method calls the corresponding method on the
- underlying lock; there is no return value.
+ .. method:: wait([timeout])
+ Wait until notified or until a timeout occurs. If the calling thread has
+ not acquired the lock when this method is called, a :exc:`RuntimeError` is
+ raised.
-.. method:: Condition.wait([timeout])
+ 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.
- Wait until notified or until a timeout occurs. If the calling thread has not
- acquired the lock when this method is called, a :exc:`RuntimeError` is raised.
+ 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 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.
+ When the underlying lock is an :class:`RLock`, it is not released using
+ 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.
- 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).
+ .. method:: notify()
- When the underlying lock is an :class:`RLock`, it is not released using 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.
+ Wake up a thread waiting on this condition, if any. If the calling thread
+ 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, if any are waiting; it is a no-op if no threads are waiting.
-.. method:: Condition.notify()
+ 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.
- Wake up a thread waiting on this condition, if any. If the calling thread
- has not acquired the lock when this method is called, a :exc:`RuntimeError`
- is raised.
+ 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.
- This method wakes up one of the threads waiting for the condition variable,
- if any are waiting; it is a no-op if no threads are waiting.
+ .. method:: notify_all()
- 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.
-
- 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.
+ 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:
defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
raised.
+ .. method:: acquire([blocking])
-.. method:: Semaphore.acquire([blocking])
-
- 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.
+ Acquire a semaphore.
- When invoked with *blocking* set to true, do the same thing as when called
- without arguments, and return true.
+ 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 with *blocking* set to false, do not block. If a call 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 true, 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 argument would block, return false immediately; otherwise, do
+ the same thing as when called without arguments, and return true.
-.. method:: Semaphore.release()
+ .. method:: release()
- 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.
+ 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:
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
-: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.
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
- awakened. Threads that call :meth:`wait` once the flag is true will not block at
- all.
+ Reset the internal flag to false. Subsequently, threads calling
+ :meth:`wait` will block until :meth:`.set` is called to set the internal
+ 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`
- will block until :meth:`set` is called to set the internal flag to true again.
+ 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.
-.. method:: Event.wait([timeout])
-
- 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``.
+ .. versionchanged:: 3.1
+ Previously, the method always returned ``None``.
.. _timer-objects:
Create a timer that will run *function* with arguments *args* and keyword
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:
There are many useful subclasses of Variable already defined:
:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
: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
the variable, with no further intervention on your part.
``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
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
:file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
distribution for an example.
:mod:`posixpath`
--- Implementation of :mod:`os.path` on POSIX.
-
.. function:: quote_plus(string[, safe[, encoding[, errors]]])
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
- unless they are included in *safe*. It also does not have *safe* default to
- ``'/'``.
+ quoting HTML form values when building up a query string to go into a URL.
+ 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'``.
fxn()
# Verify some things
assert len(w) == 1
- assert isinstance(w[-1].category, DeprecationWarning)
+ assert issubclass(w[-1].category, DeprecationWarning)
assert "deprecated" in str(w[-1].message)
One can also cause all warnings to be exceptions by using ``error`` instead of
.. function:: openfp(file, mode)
- A synonym for :func:`open`, maintained for backwards compatibility.
+ A synonym for :func:`.open`, maintained for backwards compatibility.
.. exception:: Error
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()
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()
frozensets, file objects, :term:`generator`\s, type objects, sockets, arrays,
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::
class Dict(dict):
The :mod:`webbrowser` module provides a high-level interface to allow displaying
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
will be used if graphical browsers are not available or an X11 display isn't
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
- the same browser window if possible. If *new* is 1, a new browser window is
- opened if possible. If *new* is 2, a new browser page ("tab") is opened if
- possible. If *autoraise* is true, the window is raised if possible (note that
- under many window managers this will occur regardless of the setting of this
- variable).
+ Display *url* using the default browser. If *new* is 0, the *url* is opened
+ in the same browser window if possible. If *new* is 1, a new browser window
+ is opened if possible. If *new* is 2, a new browser page ("tab") is opened
+ if possible. If *autoraise* is ``True``, the window is raised if possible
+ (note that under many window managers this will occur regardless of the
+ setting of this variable).
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
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
browser window is opened if possible. If *new* is 2, a new browser page ("tab")
The object also support comparison semantics, so handle objects will compare
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
returned. You can also use the :meth:`Detach` method to return the integer
handle, and also disconnect the Windows handle from the handle object.
.. method:: Element.getiterator([tag=None])
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.
- If tag is ``None`` or ``'*'`` then all elements are iterated over. Returns an
- iterable that provides element objects in document (depth first) order.
+ iterates over this element and all elements below it, in document (depth first)
+ order. If *tag* is not ``None`` or ``'*'``, only elements whose tag equals
+ *tag* are returned from the iterator.
.. method:: Element.insert(index, element)
: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
: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 ``&``
will be automatically escaped. However, it's the caller's responsibility to
This module adds the ability to import Python modules (:file:`\*.py`,
: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
-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.
Typically, ``sys.path`` is a list of directory names as strings. This module
.. note::
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`.
.. 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
over all the objects in the container in reverse order.
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
only provide :meth:`__reversed__` if they can provide an implementation
that is more efficient than the one provided by :func:`reversed`.
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
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
-global namespace is searched first. If the name is not found there, the builtin
+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 builtins
namespace is searched. The global statement must precede all uses of the name.
.. XXX document "nonlocal" semantics here
.. 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
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
``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
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
-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`.
Comparison of objects of the same type depends on the type:
which depend on total ordering. For example, :func:`min`, :func:`max`, and
: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
another one is made arbitrarily but consistently within one execution of a
program.
That is not a future statement; it's an ordinary import statement with no
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,
use the new syntax or semantics associated with the future statement. This can
be controlled by optional arguments to :func:`compile` --- see the documentation
are retained with full power, however: the class inheritance mechanism allows
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
-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
*public* (except see below :ref:`tut-private`),
-and all member functions are *virtual*. There are no special constructors or
-destructors. As in Modula-3, there are no shorthands for referencing the
-object's members from its methods: the method function is declared with an
-explicit first argument representing the object, which is provided implicitly by
-the call. As in Smalltalk, classes themselves are objects, albeit in the wider
-sense of the word: in Python, all data types are objects. This provides
-semantics for importing and renaming. Unlike C++ and Modula-3, built-in types
-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
+and all member functions are *virtual*. As in Modula-3, there are no shorthands
+for referencing the object's members from its methods: the method function is
+declared with an explicit first argument representing the object, which is
+provided implicitly by the call. As in Smalltalk, classes themselves are
+objects. This provides semantics for importing and renaming. Unlike C++ and
+Modula-3, built-in types can be used as base classes for extension by the user.
+Also, like in C++, most built-in operators with special syntax (arithmetic
operators, subscripting etc.) can be redefined for class instances.
+(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
+expect that few readers have heard of it.)
-.. _tut-terminology:
-A Word About Terminology
-========================
+.. _tut-object:
-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
-expect that few readers have heard of it.)
+A Word About Names and Objects
+==============================
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
usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples). However,
-aliasing has an (intended!) effect on the semantics of Python code involving
-mutable objects such as lists, dictionaries, and most types representing
-entities outside the program (files, windows, etc.). This is usually used to
-the benefit of the program, since aliases behave like pointers in some respects.
-For example, passing an object is cheap since only a pointer is passed by the
-implementation; and if a function modifies an object passed as an argument, the
-caller will see the change --- this eliminates the need for two different
-argument passing mechanisms as in Pascal.
+aliasing has a possibly surprising effect on the semantics of Python code
+involving mutable objects such as lists, dictionaries, and most other types.
+This is usually used to the benefit of the program, since aliases behave like
+pointers in some respects. For example, passing an object is cheap since only a
+pointer is passed by the implementation; and if a function modifies an object
+passed as an argument, the caller will see the change --- this eliminates the
+need for two different argument passing mechanisms as in Pascal.
.. _tut-scopes:
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
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.
By the way, I use the word *attribute* for any name following a dot --- for
Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces
-are directly accessible: the innermost scope, which is searched first, contains
-the local names; the namespaces of any enclosing functions, which are searched
-starting with the nearest enclosing scope; the middle scope, searched next,
-contains the current module's global names; and the outermost scope (searched
-last) is the namespace containing built-in names.
+are directly accessible:
+
+* the innermost scope, which is searched first, contains the local names
+* the scopes of any enclosing functions, which are searched starting with the
+ 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
the middle scope containing the module's global names. To rebind variables
time, so don't rely on dynamic name resolution! (In fact, local variables are
already determined statically.)
-A special quirk of Python is that -- if no :keyword:`global` or
-:keyword:`nonlocal` statement is in effect -- assignments to names always go
-into the innermost scope. Assignments do not copy data --- they just bind names
-to objects. The same is true for deletions: the statement ``del x`` removes the
-binding of ``x`` from the namespace referenced by the local scope. In fact, all
-operations that introduce new names use the local scope: in particular, import
-statements and function definitions bind the module or function name in the
-local scope. (The :keyword:`global` statement can be used to indicate that
-particular variables live in the global scope.)
+A special quirk of Python is that -- if no :keyword:`global` statement is in
+effect -- assignments to names always go into the innermost scope. Assignments
+do not copy data --- they just bind names to objects. The same is true for
+deletions: the statement ``del x`` removes the binding of ``x`` from the
+namespace referenced by the local scope. In fact, all operations that introduce
+new names use the local scope: in particular, :keyword:`import` statements and
+function definitions bind the module or function name in the local scope. (The
+:keyword:`global` statement can be used to indicate that particular variables
+live in the global scope.)
The :keyword:`global` statement can be used to indicate that particular
variables live in the global scope and should be rebound there; the
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
-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
-*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
that class. It is not necessary that the function definition is textually
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
-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
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
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
-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*).
It is stored as ``object.__class__``.
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,
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.)
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
derived from :class:`int`.
Private Variables
=================
-There is limited support for class-private identifiers. Any identifier of the
-form ``__spam`` (at least two leading underscores, at most one trailing
-underscore) is textually replaced with ``_classname__spam``, where ``classname``
-is the current class name with leading underscore(s) stripped. This mangling is
-done without regard to the syntactic position of the identifier, so it can be
-used to define class-private instance and class variables, methods, variables
-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"
-instance variables and methods, without having to worry about instance variables
-defined by derived classes, or mucking with instance variables by code outside
-the class. Note that the mangling rules are designed mostly to avoid accidents;
-it still is possible for a determined soul to access or modify a variable that
-is considered private. This can even be useful in special circumstances, such
-as in the debugger, and that's one reason why this loophole is not closed.
-(Buglet: derivation of a class with the same name as the base class makes use of
-private variables of the base class possible.)
-
-Notice that code passed to ``exec()`` or ``eval()`` does not
+"Private" instance variables that cannot be accessed except from inside an
+object, don't exist in Python. However, there is a convention that is followed
+by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
+be treated as a non-public part of the API (whether it is a function, a method
+or a data member). It should be considered an implementation detail and subject
+to change without notice.
+
+Since there is a valid use-case for class-private members (namely to avoid name
+clashes of names with names defined by subclasses), there is limited support for
+such a mechanism, called :dfn:`name mangling`. Any identifier of the form
+``__spam`` (at least two leading underscores, at most one trailing underscore)
+is textually replaced with ``_classname__spam``, where ``classname`` is the
+current class name with leading underscore(s) stripped. This mangling is done
+without regard to the syntactic position of the identifier, so it can be used to
+define class-private instance and class variables, methods, variables stored in
+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.
+
+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
similar to the effect of the ``global`` statement, the effect of which is
likewise restricted to code that is byte-compiled together. The same
User-defined exceptions are identified by classes as well. Using this mechanism
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()
-A class in an except clause is compatible with an exception if it is the same
-class or a base class thereof (but not the other way around --- an except clause
-listing a derived class is not compatible with a base class). For example, the
-following code will print B, C, D in that order::
+A class in an :keyword:`except` clause is compatible with an exception if it is
+the same class or a base class thereof (but not the other way around --- an
+except clause listing a derived class is not compatible with a base class). For
+example, the following code will print B, C, D in that order::
class B(Exception):
pass
We are the knights who say "Ni!"
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 position of the object passed into the format method. ::
+the objects passed into the :meth:`~str.format` method. The number in the
+brackets refers to the position of the object passed into the
+:meth:`~str.format` method. ::
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
-If keyword arguments are used in the format method, their values are referred to
-by using the name of the argument. ::
+If keyword arguments are used in the :meth:`~str.format` method, their values
+are referred to by using the name of the argument. ::
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
The value of PI is approximately 3.142.
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}
>>> for name, phone in table.items():
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
This could also be done by passing the table as keyword arguments with the '**'
-notation.::
+notation. ::
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
>>> f.closed
True
-File objects have some additional methods, such as :meth:`isatty` and
-:meth:`truncate` which are less frequently used; consult the Library Reference
-for a complete guide to file objects.
+File objects have some additional methods, such as :meth:`~file.isatty` and
+:meth:`~file.truncate` which are less frequently used; consult the Library
+Reference for a complete guide to file objects.
.. _tut-pickle:
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
-the GNU Bash shell. This is implemented using the *GNU Readline* library, which
-supports Emacs-style and vi-style editing. This library has its own
+the GNU Bash shell. This is implemented using the `GNU Readline`_ library,
+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
explained. The interactive editing and history described here are optionally
available in the Unix and Cygwin versions of the interpreter.
.. _tut-commentary:
-Commentary
-==========
+Alternatives to the Interactive Interpreter
+===========================================
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
symbol table. A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful.
-.. %
- Do we mention IPython? DUBOIS
+One alternative enhanced interactive interpreter that has been around for quite
+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
:envvar:`PYTHONSTARTUP` environment variable when you start an interactive
interpreter.
+
+.. _GNU Readline: http://tiswww.case.edu/php/chet/readline/rltop.html
+.. _IPython: http://ipython.scipy.org/
+.. _bpython: http://www.bpython-interpreter.org/
submodules are present in the package, and imports them all. Unfortunately,
this operation does not work very well on Windows platforms, where the
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
: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
adds another interesting problem for long module names.
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
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
and then imports whatever names are defined in the package. This includes any
names defined (and submodules explicitly loaded) by :file:`__init__.py`. It
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.surround
from sound.effects import *
-In this example, the echo and surround modules are imported in the current
-namespace because they are defined in the :mod:`sound.effects` package when the
-``from...import`` statement is executed. (This also works when ``__all__`` is
-defined.)
+In this example, the :mod:`echo` and :mod:`surround` modules are imported in the
+current namespace because they are defined in the :mod:`sound.effects` package
+when the ``from...import`` statement is executed. (This also works when
+``__all__`` is defined.)
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
.. rubric:: Footnotes
.. [#] 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.
The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal
floating point arithmetic. Compared to the built-in :class:`float`
-implementation of binary floating point, the new 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
-regulatory requirements, tracking of significant decimal places, or for
-applications where the user expects the results to match calculations done by
-hand.
+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 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
results in decimal floating point and binary floating point. The difference
.. 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
can still be used for precompiled modules, even if the original source
file is not available.
can uncomment them. Gestalt and Internet Config modules are enabled by
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
keyword arguments".
often used in web applications. For more information about JSON, see
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::
>>> import json
# print the local variables of the current frame
define pylocals
set $_i = 0
- while $_i < f->f_nlocals
+ while $_i < f->f_code->co_nlocals
if f->f_localsplus + $_i != 0
set $_names = co->co_varnames
set $_name = _PyUnicode_AsString(PyTuple_GetItem($_names, $_i))
'H' unsigned integer 2 \n\
'i' signed integer 2 \n\
'I' unsigned integer 2 \n\
- 'w' unicode character 4 \n\
'l' signed integer 4 \n\
'L' unsigned integer 4 \n\
'f' floating point 4 \n\
{
if (!PyObject_CheckBuffer(obj)) {
PyErr_Format(PyExc_TypeError,
- "'%100s' does not have the buffer interface",
+ "'%100s' does not support the buffer interface",
Py_TYPE(obj)->tp_name);
return -1;
}
}
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\
lnotab[, freevars[, cellvars]])\n\
\n\
if (!PyObject_CheckBuffer(obj)) {
PyErr_SetString(PyExc_TypeError,
- "object does not have the buffer interface");
+ "object does not support the buffer interface");
return NULL;
}