Make the "standard types" docs more standard.

Add links from all constructors in "built-in functions" to
stdtypes.
This commit is contained in:
Georg Brandl
2007-08-06 16:50:04 +00:00
parent 338fa90190
commit 12ffdb0103
25 changed files with 952 additions and 967 deletions

View File

@@ -929,7 +929,7 @@ return true, otherwise they return false and raise an appropriate exception.
set and *NULL* returned.
.. _string-formatting:
.. _string-conversion:
String conversion and formatting
================================

View File

@@ -334,7 +334,7 @@ Reader objects (:class:`DictReader` instances and objects returned by the
:func:`reader` function) have the following public methods:
.. method:: csv reader.next()
.. method:: csvreader.next()
Return the next row of the reader's iterable object as a list, parsed according
to the current dialect.
@@ -342,12 +342,12 @@ Reader objects (:class:`DictReader` instances and objects returned by the
Reader objects have the following public attributes:
.. attribute:: csv reader.dialect
.. attribute:: csvreader.dialect
A read-only description of the dialect in use by the parser.
.. attribute:: csv reader.line_num
.. attribute:: csvreader.line_num
The number of lines read from the source iterator. This is not the same as the
number of records returned, as records can span multiple lines.
@@ -367,13 +367,13 @@ out surrounded by parens. This may cause some problems for other programs which
read CSV files (assuming they support complex numbers at all).
.. method:: csv writer.writerow(row)
.. method:: csvwriter.writerow(row)
Write the *row* parameter to the writer's file object, formatted according to
the current dialect.
.. method:: csv writer.writerows(rows)
.. method:: csvwriter.writerows(rows)
Write all the *rows* parameters (a list of *row* objects as described above) to
the writer's file object, formatted according to the current dialect.
@@ -381,7 +381,7 @@ read CSV files (assuming they support complex numbers at all).
Writer objects have the following public attribute:
.. attribute:: csv writer.dialect
.. attribute:: csvwriter.dialect
A read-only description of the dialect in use by the writer.

View File

@@ -232,6 +232,7 @@ available. They are listed here in alphabetical order.
the function serves as a numeric conversion function like :func:`int`,
:func:`long` and :func:`float`. If both arguments are omitted, returns ``0j``.
The complex type is described in :ref:`typesnumeric`.
.. function:: delattr(object, name)
@@ -242,42 +243,10 @@ available. They are listed here in alphabetical order.
.. function:: dict([arg])
:noindex:
Return a new dictionary initialized from an optional positional argument or from
a set of keyword arguments. If no arguments are given, return a new empty
dictionary. If the positional argument *arg* is a mapping object, return a
dictionary mapping the same keys to the same values as does the mapping object.
Otherwise the positional argument must be a sequence, a container that supports
iteration, or an iterator object. The elements of the argument must each also
be of one of those kinds, and each must in turn contain exactly two objects.
The first is used as a key in the new dictionary, and the second as the key's
value. If a given key is seen more than once, the last value associated with it
is retained in the new dictionary.
If keyword arguments are given, the keywords themselves with their associated
values are added as items to the dictionary. If a key is specified both in the
positional argument and as a keyword argument, the value associated with the
keyword is retained in the dictionary. For example, these all return a
dictionary equal to ``{"one": 2, "two": 3}``:
* ``dict({'one': 2, 'two': 3})``
* ``dict({'one': 2, 'two': 3}.items())``
* ``dict({'one': 2, 'two': 3}.iteritems())``
* ``dict(zip(('one', 'two'), (2, 3)))``
* ``dict([['two', 3], ['one', 2]])``
* ``dict(one=2, two=3)``
* ``dict([(['one', 'two'][i-2], i) for i in (2, 3)])``
.. versionadded:: 2.2
.. versionchanged:: 2.3
Support for building a dictionary from keyword arguments added.
Create a new dictionary. The dictionary type is described in
:ref:`typesmapping`.
.. function:: dir([object])
@@ -477,6 +446,7 @@ available. They are listed here in alphabetical order.
these values to be returned depends entirely on the C library and is known to
vary.
The float type is described in :ref:`typesnumeric`.
.. function:: frozenset([iterable])
@@ -487,6 +457,8 @@ available. They are listed here in alphabetical order.
:class:`frozenset` objects. If *iterable* is not specified, returns a new empty
set, ``frozenset([])``.
The frozenset type is described in :ref:`types-set`.
.. versionadded:: 2.4
@@ -583,6 +555,8 @@ available. They are listed here in alphabetical order.
the integer range a long object will be returned instead. If no arguments are
given, returns ``0``.
The integer type is described in :ref:`typesnumeric`.
.. function:: isinstance(object, classinfo)
@@ -642,6 +616,8 @@ available. They are listed here in alphabetical order.
returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If
no argument is given, returns a new empty list, ``[]``.
:class:`list` is a mutable sequence type, as documented in :ref:`typesseq`.
.. function:: locals()
@@ -667,6 +643,7 @@ available. They are listed here in alphabetical order.
with the same value is returned. Conversion of floating point numbers to
integers truncates (towards zero). If no arguments are given, returns ``0L``.
The long type is described in :ref:`typesnumeric`.
.. function:: map(function, iterable, ...)
@@ -1011,6 +988,8 @@ available. They are listed here in alphabetical order.
:class:`frozenset` objects. If *iterable* is not specified, returns a new empty
set, ``set([])``.
The set type is described in :ref:`types-set`.
.. versionadded:: 2.4
@@ -1101,13 +1080,12 @@ available. They are listed here in alphabetical order.
acceptable to :func:`eval`; its goal is to return a printable string. If no
argument is given, returns the empty string, ``''``.
For more information on strings see :ref:`typesseq` which describes
sequence functionality (strings are sequences), and also the
string-specific methods described in the :ref:`string-methods`
section. To output formatted strings use template strings or the
``%`` operator described in the :ref:`typesseq-strings` section. In
addition see the :ref:`stringservices` section. See also
:func:`unicode`.
For more information on strings see :ref:`typesseq` which describes sequence
functionality (strings are sequences), and also the string-specific methods
described in the :ref:`string-methods` section. To output formatted strings
use template strings or the ``%`` operator described in the
:ref:`string-formatting` section. In addition see the :ref:`stringservices`
section. See also :func:`unicode`.
.. function:: sum(iterable[, start])
@@ -1152,6 +1130,7 @@ available. They are listed here in alphabetical order.
3])`` returns ``(1, 2, 3)``. If no argument is given, returns a new empty
tuple, ``()``.
:class:`tuple` is a mutable sequence type, as documented in :ref:`typesseq`.
.. function:: type(object)
@@ -1222,11 +1201,10 @@ available. They are listed here in alphabetical order.
For more information on Unicode strings see :ref:`typesseq` which describes
sequence functionality (Unicode strings are sequences), and also the
string-specific methods described in the :ref:`string-methods`
section. To output formatted strings use template strings or the
``%`` operator described in the :ref:`typesseq-strings` section. In
addition see the :ref:`stringservices` section. See also
:func:`str`.
string-specific methods described in the :ref:`string-methods` section. To
output formatted strings use template strings or the ``%`` operator described
in the :ref:`string-formatting` section. In addition see the
:ref:`stringservices` section. See also :func:`str`.
.. versionadded:: 2.0

View File

@@ -612,7 +612,7 @@ format of the messages was also changed, and output went to the specified file
rather than the console.
Formatting uses standard Python string formatting - see section
:ref:`typesseq-strings`. The format string takes the following common
:ref:`string-formatting`. The format string takes the following common
specifiers. For a complete list of specifiers, consult the :class:`Formatter`
documentation.
@@ -1483,7 +1483,7 @@ A Formatter can be initialized with a format string which makes use of knowledge
of the :class:`LogRecord` attributes - such as the default value mentioned above
making use of the fact that the user's message and arguments are pre-formatted
into a :class:`LogRecord`'s *message* attribute. This format string contains
standard python %-style mapping keys. See section :ref:`typesseq-strings`
standard python %-style mapping keys. See section :ref:`string-formatting`
for more information on string formatting.
Currently, the useful mapping keys in a :class:`LogRecord` are:

View File

@@ -124,19 +124,19 @@ The audio device objects returned by :func:`open` define the following methods
and (read-only) attributes:
.. method:: audio device.close()
.. method:: oss_audio_device.close()
Explicitly close the audio device. When you are done writing to or reading from
an audio device, you should explicitly close it. A closed device cannot be used
again.
.. method:: audio device.fileno()
.. method:: oss_audio_device.fileno()
Return the file descriptor associated with the device.
.. method:: audio device.read(size)
.. method:: oss_audio_device.read(size)
Read *size* bytes from the audio input and return them as a Python string.
Unlike most Unix device drivers, OSS audio devices in blocking mode (the
@@ -144,7 +144,7 @@ and (read-only) attributes:
available.
.. method:: audio device.write(data)
.. method:: oss_audio_device.write(data)
Write the Python string *data* to the audio device and return the number of
bytes written. If the audio device is in blocking mode (the default), the
@@ -153,7 +153,7 @@ and (read-only) attributes:
---see :meth:`writeall`.
.. method:: audio device.writeall(data)
.. method:: oss_audio_device.writeall(data)
Write the entire Python string *data* to the audio device: waits until the audio
device is able to accept data, writes as much data as it will accept, and
@@ -169,13 +169,13 @@ be useful when consulting the OSS documentation). If the underlying
:func:`ioctl` fails, they all raise :exc:`IOError`.
.. method:: audio device.nonblock()
.. method:: oss_audio_device.nonblock()
Put the device into non-blocking mode. Once in non-blocking mode, there is no
way to return it to blocking mode.
.. method:: audio device.getfmts()
.. method:: oss_audio_device.getfmts()
Return a bitmask of the audio output formats supported by the soundcard. Some
of the formats supported by OSS are:
@@ -212,7 +212,7 @@ be useful when consulting the OSS documentation). If the underlying
:const:`AFMT_S16_LE`.
.. method:: audio device.setfmt(format)
.. method:: oss_audio_device.setfmt(format)
Try to set the current audio format to *format*---see :meth:`getfmts` for a
list. Returns the audio format that the device was set to, which may not be the
@@ -220,7 +220,7 @@ be useful when consulting the OSS documentation). If the underlying
by passing an "audio format" of :const:`AFMT_QUERY`.
.. method:: audio device.channels(nchannels)
.. method:: oss_audio_device.channels(nchannels)
Set the number of output channels to *nchannels*. A value of 1 indicates
monophonic sound, 2 stereophonic. Some devices may have more than 2 channels,
@@ -228,7 +228,7 @@ be useful when consulting the OSS documentation). If the underlying
the device was set to.
.. method:: audio device.speed(samplerate)
.. method:: oss_audio_device.speed(samplerate)
Try to set the audio sampling rate to *samplerate* samples per second. Returns
the rate actually set. Most sound devices don't support arbitrary sampling
@@ -250,21 +250,21 @@ be useful when consulting the OSS documentation). If the underlying
+-------+-------------------------------------------+
.. method:: audio device.sync()
.. method:: oss_audio_device.sync()
Wait until the sound device has played every byte in its buffer. (This happens
implicitly when the device is closed.) The OSS documentation recommends closing
and re-opening the device rather than using :meth:`sync`.
.. method:: audio device.reset()
.. method:: oss_audio_device.reset()
Immediately stop playing or recording and return the device to a state where it
can accept commands. The OSS documentation recommends closing and re-opening
the device after calling :meth:`reset`.
.. method:: audio device.post()
.. method:: oss_audio_device.post()
Tell the driver that there is likely to be a pause in the output, making it
possible for the device to handle the pause more intelligently. You might use
@@ -275,7 +275,7 @@ The following convenience methods combine several ioctls, or one ioctl and some
simple calculations.
.. method:: audio device.setparameters(format, nchannels, samplerate [, strict=False])
.. method:: oss_audio_device.setparameters(format, nchannels, samplerate [, strict=False])
Set the key audio sampling parameters---sample format, number of channels, and
sampling rate---in one method call. *format*, *nchannels*, and *samplerate*
@@ -298,17 +298,17 @@ simple calculations.
rate = dsp.rate(channels)
.. method:: audio device.bufsize()
.. method:: oss_audio_device.bufsize()
Returns the size of the hardware buffer, in samples.
.. method:: audio device.obufcount()
.. method:: oss_audio_device.obufcount()
Returns the number of samples that are in the hardware buffer yet to be played.
.. method:: audio device.obuffree()
.. method:: oss_audio_device.obuffree()
Returns the number of samples that could be queued into the hardware buffer to
be played without blocking.
@@ -316,17 +316,17 @@ simple calculations.
Audio device objects also support several read-only attributes:
.. attribute:: audio device.closed
.. attribute:: oss_audio_device.closed
Boolean indicating whether the device has been closed.
.. attribute:: audio device.name
.. attribute:: oss_audio_device.name
String containing the name of the device file.
.. attribute:: audio device.mode
.. attribute:: oss_audio_device.mode
The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
@@ -339,20 +339,20 @@ Mixer Device Objects
The mixer object provides two file-like methods:
.. method:: mixer device.close()
.. method:: oss_mixer_device.close()
This method closes the open mixer device file. Any further attempts to use the
mixer after this file is closed will raise an :exc:`IOError`.
.. method:: mixer device.fileno()
.. method:: oss_mixer_device.fileno()
Returns the file handle number of the open mixer device file.
The remaining methods are specific to audio mixing:
.. method:: mixer device.controls()
.. method:: oss_mixer_device.controls()
This method returns a bitmask specifying the available mixer controls ("Control"
being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
@@ -372,7 +372,7 @@ The remaining methods are specific to audio mixing:
Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.
.. method:: mixer device.stereocontrols()
.. method:: oss_mixer_device.stereocontrols()
Returns a bitmask indicating stereo mixer controls. If a bit is set, the
corresponding control is stereo; if it is unset, the control is either
@@ -383,13 +383,13 @@ The remaining methods are specific to audio mixing:
data from a bitmask.
.. method:: mixer device.reccontrols()
.. method:: oss_mixer_device.reccontrols()
Returns a bitmask specifying the mixer controls that may be used to record. See
the code example for :meth:`controls` for an example of reading from a bitmask.
.. method:: mixer device.get(control)
.. method:: oss_mixer_device.get(control)
Returns the volume of a given mixer control. The returned volume is a 2-tuple
``(left_volume,right_volume)``. Volumes are specified as numbers from 0
@@ -400,7 +400,7 @@ The remaining methods are specific to audio mixing:
:exc:`IOError` if an unsupported control is specified.
.. method:: mixer device.set(control, (left, right))
.. method:: oss_mixer_device.set(control, (left, right))
Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
``right`` must be ints and between 0 (silent) and 100 (full volume). On
@@ -412,13 +412,13 @@ The remaining methods are specific to audio mixing:
specified volumes were out-of-range.
.. method:: mixer device.get_recsrc()
.. method:: oss_mixer_device.get_recsrc()
This method returns a bitmask indicating which control(s) are currently being
used as a recording source.
.. method:: mixer device.set_recsrc(bitmask)
.. method:: oss_mixer_device.set_recsrc(bitmask)
Call this function to specify a recording source. Returns a bitmask indicating
the new recording source (or sources) if successful; raises :exc:`IOError` if an

View File

@@ -47,17 +47,17 @@ The class descriptor objects used as values in the dictionary returned by
:func:`readmodule` and :func:`readmodule_ex` provide the following data members:
.. attribute:: class descriptor.module
.. attribute:: class_descriptor.module
The name of the module defining the class described by the class descriptor.
.. attribute:: class descriptor.name
.. attribute:: class_descriptor.name
The name of the class.
.. attribute:: class descriptor.super
.. attribute:: class_descriptor.super
A list of class descriptors which describe the immediate base classes of the
class being described. Classes which are named as superclasses but which are
@@ -65,17 +65,17 @@ The class descriptor objects used as values in the dictionary returned by
name instead of class descriptors.
.. attribute:: class descriptor.methods
.. attribute:: class_descriptor.methods
A dictionary mapping method names to line numbers.
.. attribute:: class descriptor.file
.. attribute:: class_descriptor.file
Name of the file containing the ``class`` statement defining the class.
.. attribute:: class descriptor.lineno
.. attribute:: class_descriptor.lineno
The line number of the ``class`` statement within the file named by
:attr:`file`.
@@ -90,23 +90,23 @@ The function descriptor objects used as values in the dictionary returned by
:func:`readmodule_ex` provide the following data members:
.. attribute:: function descriptor.module
.. attribute:: function_descriptor.module
The name of the module defining the function described by the function
descriptor.
.. attribute:: function descriptor.name
.. attribute:: function_descriptor.name
The name of the function.
.. attribute:: function descriptor.file
.. attribute:: function_descriptor.file
Name of the file containing the ``def`` statement defining the function.
.. attribute:: function descriptor.lineno
.. attribute:: function_descriptor.lineno
The line number of the ``def`` statement within the file named by :attr:`file`.

View File

@@ -1,3 +1,5 @@
.. XXX: reference/datamodel and this have quite a few overlaps!
.. _bltin-types:
@@ -497,6 +499,8 @@ and xrange objects.
object: Unicode
object: tuple
object: list
object: buffer
object: xrange
String literals are written in single or double quotes: ``'xyzzy'``,
``"frobozz"``. See :ref:`strings` for more about string literals. Unicode
@@ -508,18 +512,10 @@ parentheses, but an empty tuple must have the enclosing parentheses, such as
``a, b, c`` or ``()``. A single item tuple must have a trailing comma, such as
``(d,)``.
.. index::
builtin: buffer
object: buffer
Buffer objects are not directly supported by Python syntax, but can be created
by calling the builtin function :func:`buffer`. They don't support
concatenation or repetition.
.. index::
builtin: xrange
object: xrange
Xrange objects are similar to buffers in that there is no specific syntax to
create them, but they are created using the :func:`xrange` function. They don't
support slicing, concatenation or repetition, and using ``in``, ``not in``,
@@ -657,12 +653,11 @@ String Methods
.. index:: pair: string; methods
Below are listed the string methods which both 8-bit strings and Unicode
objects support. In addition, Python's strings support the
sequence type methods described in the
:ref:`typesseq` section (above). To output formatted strings use
template strings or the ``%`` operator described in the
:ref:`typesseq-strings` section (below). Also, see the :mod:`re` module for
Below are listed the string methods which both 8-bit strings and Unicode objects
support. In addition, Python's strings support the sequence type methods
described in the :ref:`typesseq` section (above). To output formatted strings
use template strings or the ``%`` operator described in the
:ref:`string-formatting` section (below). Also, see the :mod:`re` module for
string functions based on regular expressions.
.. method:: str.capitalize()
@@ -1038,7 +1033,7 @@ string functions based on regular expressions.
.. versionadded:: 2.2.2
.. _typesseq-strings:
.. _string-formatting:
String Formatting Operations
----------------------------
@@ -1105,86 +1100,72 @@ sequential parameter list).
The conversion flag characters are:
+---------+-----------------------------------------------+
| Flag | Meaning |
+=========+===============================================+
| ``'#'`` | The value conversion will use the "alternate |
| | form" (where defined below). |
+---------+-----------------------------------------------+
| ``'0'`` | The conversion will be zero padded for |
| | numeric values. |
+---------+-----------------------------------------------+
| ``'-'`` | The converted value is left adjusted |
| | (overrides the ``'0'`` conversion if both are |
| | given). |
+---------+-----------------------------------------------+
| ``' '`` | (a space) A blank should be left before a |
| | positive number (or empty string) produced by |
| | a signed conversion. |
+---------+-----------------------------------------------+
| ``'+'`` | A sign character (``'+'`` or ``'-'``) will |
| | precede the conversion (overrides a "space" |
| | flag). |
+---------+-----------------------------------------------+
+---------+---------------------------------------------------------------------+
| Flag | Meaning |
+=========+=====================================================================+
| ``'#'`` | The value conversion will use the "alternate form" (where defined |
| | below). |
+---------+---------------------------------------------------------------------+
| ``'0'`` | The conversion will be zero padded for numeric values. |
+---------+---------------------------------------------------------------------+
| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
| | conversion if both are given). |
+---------+---------------------------------------------------------------------+
| ``' '`` | (a space) A blank should be left before a positive number (or empty |
| | string) produced by a signed conversion. |
+---------+---------------------------------------------------------------------+
| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
| | (overrides a "space" flag). |
+---------+---------------------------------------------------------------------+
A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
is not necessary for Python.
The conversion types are:
+------------+---------------------------------+-------+
| Conversion | Meaning | Notes |
+============+=================================+=======+
| ``'d'`` | Signed integer decimal. | |
+------------+---------------------------------+-------+
| ``'i'`` | Signed integer decimal. | |
+------------+---------------------------------+-------+
| ``'o'`` | Unsigned octal. | \(1) |
+------------+---------------------------------+-------+
| ``'u'`` | Unsigned decimal. | |
+------------+---------------------------------+-------+
| ``'x'`` | Unsigned hexadecimal | \(2) |
| | (lowercase). | |
+------------+---------------------------------+-------+
| ``'X'`` | Unsigned hexadecimal | \(2) |
| | (uppercase). | |
+------------+---------------------------------+-------+
| ``'e'`` | Floating point exponential | \(3) |
| | format (lowercase). | |
+------------+---------------------------------+-------+
| ``'E'`` | Floating point exponential | \(3) |
| | format (uppercase). | |
+------------+---------------------------------+-------+
| ``'f'`` | Floating point decimal format. | \(3) |
+------------+---------------------------------+-------+
| ``'F'`` | Floating point decimal format. | \(3) |
+------------+---------------------------------+-------+
| ``'g'`` | Floating point format. Uses | \(4) |
| | exponential format if exponent | |
| | is greater than -4 or less than | |
| | precision, decimal format | |
| | otherwise. | |
+------------+---------------------------------+-------+
| ``'G'`` | Floating point format. Uses | \(4) |
| | exponential format if exponent | |
| | is greater than -4 or less than | |
| | precision, decimal format | |
| | otherwise. | |
+------------+---------------------------------+-------+
| ``'c'`` | Single character (accepts | |
| | integer or single character | |
| | string). | |
+------------+---------------------------------+-------+
| ``'r'`` | String (converts any python | \(5) |
| | object using :func:`repr`). | |
+------------+---------------------------------+-------+
| ``'s'`` | String (converts any python | \(6) |
| | object using :func:`str`). | |
+------------+---------------------------------+-------+
| ``'%'`` | No argument is converted, | |
| | results in a ``'%'`` character | |
| | in the result. | |
+------------+---------------------------------+-------+
+------------+-----------------------------------------------------+-------+
| Conversion | Meaning | Notes |
+============+=====================================================+=======+
| ``'d'`` | Signed integer decimal. | |
+------------+-----------------------------------------------------+-------+
| ``'i'`` | Signed integer decimal. | |
+------------+-----------------------------------------------------+-------+
| ``'o'`` | Unsigned octal. | \(1) |
+------------+-----------------------------------------------------+-------+
| ``'u'`` | Unsigned decimal. | |
+------------+-----------------------------------------------------+-------+
| ``'x'`` | Unsigned hexadecimal (lowercase). | \(2) |
+------------+-----------------------------------------------------+-------+
| ``'X'`` | Unsigned hexadecimal (uppercase). | \(2) |
+------------+-----------------------------------------------------+-------+
| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'f'`` | Floating point decimal format. | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'F'`` | Floating point decimal format. | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'g'`` | Floating point format. Uses exponential format if | \(4) |
| | exponent is greater than -4 or less than precision, | |
| | decimal format otherwise. | |
+------------+-----------------------------------------------------+-------+
| ``'G'`` | Floating point format. Uses exponential format if | \(4) |
| | exponent is greater than -4 or less than precision, | |
| | decimal format otherwise. | |
+------------+-----------------------------------------------------+-------+
| ``'c'`` | Single character (accepts integer or single | |
| | character string). | |
+------------+-----------------------------------------------------+-------+
| ``'r'`` | String (converts any python object using | \(5) |
| | :func:`repr`). | |
+------------+-----------------------------------------------------+-------+
| ``'s'`` | String (converts any python object using | \(6) |
| | :func:`str`). | |
+------------+-----------------------------------------------------+-------+
| ``'%'`` | No argument is converted, results in a ``'%'`` | |
| | character in the result. | |
+------------+-----------------------------------------------------+-------+
Notes:
@@ -1444,37 +1425,52 @@ element of another set.
Instances of :class:`set` and :class:`frozenset` provide the following
operations:
+-------------------------------+------------+---------------------------------+
| Operation | Equivalent | Result |
+===============================+============+=================================+
| ``len(s)`` | | cardinality of set *s* |
+-------------------------------+------------+---------------------------------+
| ``x in s`` | | test *x* for membership in *s* |
+-------------------------------+------------+---------------------------------+
| ``x not in s`` | | test *x* for non-membership in |
| | | *s* |
+-------------------------------+------------+---------------------------------+
| ``s.issubset(t)`` | ``s <= t`` | test whether every element in |
| | | *s* is in *t* |
+-------------------------------+------------+---------------------------------+
| ``s.issuperset(t)`` | ``s >= t`` | test whether every element in |
| | | *t* is in *s* |
+-------------------------------+------------+---------------------------------+
| ``s.union(t)`` | *s* \| *t* | new set with elements from both |
| | | *s* and *t* |
+-------------------------------+------------+---------------------------------+
| ``s.intersection(t)`` | *s* & *t* | new set with elements common to |
| | | *s* and *t* |
+-------------------------------+------------+---------------------------------+
| ``s.difference(t)`` | *s* - *t* | new set with elements in *s* |
| | | but not in *t* |
+-------------------------------+------------+---------------------------------+
| ``s.symmetric_difference(t)`` | *s* ^ *t* | new set with elements in either |
| | | *s* or *t* but not both |
+-------------------------------+------------+---------------------------------+
| ``s.copy()`` | | new set with a shallow copy of |
| | | *s* |
+-------------------------------+------------+---------------------------------+
.. describe:: len(s)
Return the cardinality of set *s*.
.. describe:: x in s
Test *x* for membership in *s*.
.. describe:: x not in s
Test *x* for non-membership in *s*.
.. method:: set.issubset(other)
set <= other
Test whether every element in the set is in *other*.
.. method:: set.issuperset(other)
set >= other
Test whether every element in *other* is in the set.
.. method:: set.union(other)
set | other
Return a new set with elements from both sets.
.. method:: set.intersection(other)
set & other
Return a new set with elements common to both sets.
.. method:: set.difference(other)
set - other
Return a new set with elements in the set that are not in *other*.
.. method:: set.symmetric_difference(other)
set ^ other
Return a new set with elements in either the set or *other* but not both.
.. method:: set.copy()
Return a new set with a shallow copy of *s*.
Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
:meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
@@ -1512,46 +1508,56 @@ returns an instance of :class:`frozenset`.
The following table lists operations available for :class:`set` that do not
apply to immutable instances of :class:`frozenset`:
+--------------------------------------+-------------+---------------------------------+
| Operation | Equivalent | Result |
+======================================+=============+=================================+
| ``s.update(t)`` | *s* \|= *t* | update set *s*, adding elements |
| | | from *t* |
+--------------------------------------+-------------+---------------------------------+
| ``s.intersection_update(t)`` | *s* &= *t* | update set *s*, keeping only |
| | | elements found in both *s* and |
| | | *t* |
+--------------------------------------+-------------+---------------------------------+
| ``s.difference_update(t)`` | *s* -= *t* | update set *s*, removing |
| | | elements found in *t* |
+--------------------------------------+-------------+---------------------------------+
| ``s.symmetric_difference_update(t)`` | *s* ^= *t* | update set *s*, keeping only |
| | | elements found in either *s* or |
| | | *t* but not in both |
+--------------------------------------+-------------+---------------------------------+
| ``s.add(x)`` | | add element *x* to set *s* |
+--------------------------------------+-------------+---------------------------------+
| ``s.remove(x)`` | | remove *x* from set *s*; raises |
| | | :exc:`KeyError` if not present |
+--------------------------------------+-------------+---------------------------------+
| ``s.discard(x)`` | | removes *x* from set *s* if |
| | | present |
+--------------------------------------+-------------+---------------------------------+
| ``s.pop()`` | | remove and return an arbitrary |
| | | element from *s*; raises |
| | | :exc:`KeyError` if empty |
+--------------------------------------+-------------+---------------------------------+
| ``s.clear()`` | | remove all elements from set |
| | | *s* |
+--------------------------------------+-------------+---------------------------------+
.. method:: set.update(other)
set |= other
Update the set, adding elements from *other*.
.. method:: set.intersection_update(other)
set &= other
Update the set, keeping only elements found in it and *other*.
.. method:: set.difference_update(other)
set -= other
Update the set, removing elements found in *other*.
.. method:: set.symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in both.
.. method:: set.add(el)
Add element *el* to the set.
.. method:: set.remove(el)
Remove element *el* from the set. Raises :exc:`KeyError` if *el* is not
contained in the set.
.. method:: set.discard(el)
Remove element *el* from the set if it is present.
.. method:: set.pop()
Remove and return an arbitrary element from the set. Raises :exc:`KeyError`
if the set is empty.
.. method:: set.clear()
Remove all elements from the set.
Note, the non-operator versions of the :meth:`update`,
:meth:`intersection_update`, :meth:`difference_update`, and
:meth:`symmetric_difference_update` methods will accept any iterable as an
argument.
The design of the set types was based on lessons learned from the :mod:`sets`
module.
The design of the set types was based on lessons learned from the Python
implementation found in the :mod:`sets` module.
.. seealso::
@@ -1568,173 +1574,216 @@ Mapping Types --- :class:`dict`
.. index::
object: mapping
object: dictionary
triple: operations on; mapping; types
triple: operations on; dictionary; type
statement: del
builtin: len
A :dfn:`mapping` object maps immutable values to arbitrary objects. Mappings
A :dfn:`mapping` object maps immutable values to arbitrary objects. Mappings
are mutable objects. There is currently only one standard mapping type, the
:dfn:`dictionary`. A dictionary's keys are almost arbitrary values. Only
:dfn:`dictionary`. A dictionary's keys are *almost* arbitrary values. Only
values containing lists, dictionaries or other mutable types (that are compared
by value rather than by object identity) may not be used as keys. Numeric types
used for keys obey the normal rules for numeric comparison: if two numbers
compare equal (such as ``1`` and ``1.0``) then they can be used interchangeably
to index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of ``key: value``
Dictionaries can be created by placing a comma-separated list of ``key: value``
pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
'jack', 4127: 'sjoerd'}``.
'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
.. index::
triple: operations on; mapping; types
triple: operations on; dictionary; type
statement: del
builtin: len
single: clear() (dictionary method)
single: copy() (dictionary method)
single: has_key() (dictionary method)
single: fromkeys() (dictionary method)
single: items() (dictionary method)
single: keys() (dictionary method)
single: update() (dictionary method)
single: values() (dictionary method)
single: get() (dictionary method)
single: setdefault() (dictionary method)
single: pop() (dictionary method)
single: popitem() (dictionary method)
single: iteritems() (dictionary method)
single: iterkeys() (dictionary method)
single: itervalues() (dictionary method)
.. class:: dict([arg])
The following operations are defined on mappings (where *a* and *b* are
mappings, *k* is a key, and *v* and *x* are arbitrary objects):
Return a new dictionary initialized from an optional positional argument or from
a set of keyword arguments. If no arguments are given, return a new empty
dictionary. If the positional argument *arg* is a mapping object, return a
dictionary mapping the same keys to the same values as does the mapping object.
Otherwise the positional argument must be a sequence, a container that supports
iteration, or an iterator object. The elements of the argument must each also
be of one of those kinds, and each must in turn contain exactly two objects.
The first is used as a key in the new dictionary, and the second as the key's
value. If a given key is seen more than once, the last value associated with it
is retained in the new dictionary.
+--------------------------------+---------------------------------+-----------+
| Operation | Result | Notes |
+================================+=================================+===========+
| ``len(a)`` | the number of items in *a* | |
+--------------------------------+---------------------------------+-----------+
| ``a[k]`` | the item of *a* with key *k* | (1), (10) |
+--------------------------------+---------------------------------+-----------+
| ``a[k] = v`` | set ``a[k]`` to *v* | |
+--------------------------------+---------------------------------+-----------+
| ``del a[k]`` | remove ``a[k]`` from *a* | \(1) |
+--------------------------------+---------------------------------+-----------+
| ``a.clear()`` | remove all items from ``a`` | |
+--------------------------------+---------------------------------+-----------+
| ``a.copy()`` | a (shallow) copy of ``a`` | |
+--------------------------------+---------------------------------+-----------+
| ``k in a`` | ``True`` if *a* has a key *k*, | \(2) |
| | else ``False`` | |
+--------------------------------+---------------------------------+-----------+
| ``k not in a`` | Equivalent to ``not`` *k* in | \(2) |
| | *a* | |
+--------------------------------+---------------------------------+-----------+
| ``a.has_key(k)`` | Equivalent to *k* ``in`` *a*, | |
| | use that form in new code | |
+--------------------------------+---------------------------------+-----------+
| ``a.items()`` | a copy of *a*'s list of (*key*, | \(3) |
| | *value*) pairs | |
+--------------------------------+---------------------------------+-----------+
| ``a.keys()`` | a copy of *a*'s list of keys | \(3) |
+--------------------------------+---------------------------------+-----------+
| ``a.update([b])`` | updates *a* with key/value | \(9) |
| | pairs from *b*, overwriting | |
| | existing keys, returns ``None`` | |
+--------------------------------+---------------------------------+-----------+
| ``a.fromkeys(seq[, value])`` | Creates a new dictionary with | \(7) |
| | keys from *seq* and values set | |
| | to *value* | |
+--------------------------------+---------------------------------+-----------+
| ``a.values()`` | a copy of *a*'s list of values | \(3) |
+--------------------------------+---------------------------------+-----------+
| ``a.get(k[, x])`` | ``a[k]`` if ``k in a``, else | \(4) |
| | *x* | |
+--------------------------------+---------------------------------+-----------+
| ``a.setdefault(k[, x])`` | ``a[k]`` if ``k in a``, else | \(5) |
| | *x* (also setting it) | |
+--------------------------------+---------------------------------+-----------+
| ``a.pop(k[, x])`` | ``a[k]`` if ``k in a``, else | \(8) |
| | *x* (and remove k) | |
+--------------------------------+---------------------------------+-----------+
| ``a.popitem()`` | remove and return an arbitrary | \(6) |
| | (*key*, *value*) pair | |
+--------------------------------+---------------------------------+-----------+
| ``a.iteritems()`` | return an iterator over (*key*, | (2), (3) |
| | *value*) pairs | |
+--------------------------------+---------------------------------+-----------+
| ``a.iterkeys()`` | return an iterator over the | (2), (3) |
| | mapping's keys | |
+--------------------------------+---------------------------------+-----------+
| ``a.itervalues()`` | return an iterator over the | (2), (3) |
| | mapping's values | |
+--------------------------------+---------------------------------+-----------+
If keyword arguments are given, the keywords themselves with their associated
values are added as items to the dictionary. If a key is specified both in the
positional argument and as a keyword argument, the value associated with the
keyword is retained in the dictionary. For example, these all return a
dictionary equal to ``{"one": 2, "two": 3}``:
Notes:
* ``dict({'one': 2, 'two': 3})``
(1)
Raises a :exc:`KeyError` exception if *k* is not in the map.
* ``dict({'one': 2, 'two': 3}.items())``
* ``dict({'one': 2, 'two': 3}.iteritems())``
* ``dict(zip(('one', 'two'), (2, 3)))``
* ``dict([['two', 3], ['one', 2]])``
* ``dict(one=2, two=3)``
* ``dict([(['one', 'two'][i-2], i) for i in (2, 3)])``
(2)
.. versionadded:: 2.2
(3)
Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations, and depends on the dictionary's history of
insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`,
:meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no
intervening modifications to the dictionary, the lists will directly correspond.
This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
zip(a.values(), a.keys())``. The same relationship holds for the
:meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(a.itervalues(),
a.iterkeys())`` provides the same value for ``pairs``. Another way to create the
same list is ``pairs = [(v, k) for (k, v) in a.iteritems()]``.
.. versionchanged:: 2.3
Support for building a dictionary from keyword arguments added.
(4)
Never raises an exception if *k* is not in the map, instead it returns *x*. *x*
is optional; when *x* is not provided and *k* is not in the map, ``None`` is
returned.
(5)
:func:`setdefault` is like :func:`get`, except that if *k* is missing, *x* is
both returned and inserted into the dictionary as the value of *k*. *x* defaults
to ``None``.
These are the operations that dictionaries support (and therefore, custom mapping
types should support too):
(6)
:func:`popitem` is useful to destructively iterate over a dictionary, as often
used in set algorithms. If the dictionary is empty, calling :func:`popitem`
raises a :exc:`KeyError`.
.. describe:: len(d)
Return the number of items in the dictionary *d*.
.. describe:: d[key]
Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
not in the map.
.. versionadded:: 2.5
If a subclass of dict defines a method :meth:`__missing__`, if the key
*key* is not present, the ``d[key]`` operation calls that method with the
key *key* as argument. The ``d[key]`` operation then returns or raises
whatever is returned or raised by the ``__missing__(key)`` call if the key
is not present. No other operations or methods invoke
:meth:`__missing__`. If :meth:`__missing__` is not defined,
:exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
cannot be an instance variable. For an example, see
:class:`collections.defaultdict`.
.. describe:: d[key] = value
Set ``d[key]`` to *value*.
.. describe:: del d[key]
Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
map.
.. describe:: key in d
Return ``True`` if *d* has a key *key*, else ``False``.
.. versionadded:: 2.2
.. describe:: key not in d
Equivalent to ``not key in d``.
.. versionadded:: 2.2
.. method:: dict.clear()
Remove all items from the dictionary.
.. method:: dict.copy()
Return a shallow copy of the dictionary.
.. method:: dict.fromkeys(seq[, value])
Create a new dictionary with keys from *seq* and values set to *value*.
(7)
:func:`fromkeys` is a class method that returns a new dictionary. *value*
defaults to ``None``.
.. versionadded:: 2.3
(8)
:func:`pop` raises a :exc:`KeyError` when no default value is given and the key
is not found.
.. method:: dict.get(key[, default])
Return the value for *key* if *key* is in the dictionary, else *default*. If
*default* is not given, it defaults to ``None``, so that this method never
raises a :exc:`KeyError`.
.. method:: dict.has_key(key)
``d.has_key(key)`` is equivalent to ``key in d``, but deprecated.
.. method:: dict.items()
Return a copy of the dictionary's list of ``(key, value)`` pairs.
.. note::
Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations, and depends on the dictionary's history of
insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`,
:meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no
intervening modifications to the dictionary, the lists will directly correspond.
This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
zip(d.values(), d.keys())``. The same relationship holds for the
:meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(d.itervalues(),
d.iterkeys())`` provides the same value for ``pairs``. Another way to create the
same list is ``pairs = [(v, k) for (k, v) in d.iteritems()]``.
.. method:: dict.iteritems()
Return an iterator over the dictionary's ``(key, value)`` pairs.
See the note for :meth:`dict.items`.
.. versionadded:: 2.2
.. method:: dict.iterkeys()
Return an iterator over the dictionary's keys. See the note for
:meth:`dict.items`.
.. versionadded:: 2.2
.. method:: dict.itervalues()
Return an iterator over the dictionary's values. See the note for
:meth:`dict.items`.
.. versionadded:: 2.2
.. method:: dict.keys()
Return a copy of the dictionary's list of keys. See the note for
:meth:`dict.items`.
.. method:: dict.pop(key[, default])
If *key* is in the dictionary, remove it and return its value, else return
*default*. If *default* is not given and *key* is not in the dictionary, a
:exc:`KeyError` is raised.
.. versionadded:: 2.3
(9)
:func:`update` accepts either another mapping object or an iterable of key/value
pairs (as a tuple or other iterable of length two). If keyword arguments are
specified, the mapping is then is updated with those key/value pairs:
``d.update(red=1, blue=2)``.
.. method:: dict.popitem()
Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
:func:`popitem` is useful to destructively iterate over a dictionary, as
often used in set algorithms. If the dictionary is empty, calling
:func:`popitem` raises a :exc:`KeyError`.
.. method:: dict.setdefault(key[, default])
If *key* is in the dictionary, return its value. If not, insert *key* with a
value of *default* and return *default*. *default* defaults to ``None``.
.. method:: dict.update([other])
Update the dictionary with the key/value pairs from *other*, overwriting existing
keys. Return ``None``.
:func:`update` accepts either another dictionary object or an iterable of
key/value pairs (as a tuple or other iterable of length two). If keyword
arguments are specified, the dictionary is then is updated with those
key/value pairs: ``d.update(red=1, blue=2)``.
.. versionchanged:: 2.4
Allowed the argument to be an iterable of key/value pairs and allowed keyword
arguments.
Allowed the argument to be an iterable of key/value pairs and allowed
keyword arguments.
(10)
If a subclass of dict defines a method :meth:`__missing__`, if the key *k* is
not present, the ``a[k]`` operation calls that method with the key *k* as
argument. The ``a[k]`` operation then returns or raises whatever is returned
or raised by the ``__missing__(k)`` call if the key is not present. No other
operations or methods invoke :meth:`__missing__`. If :meth:`__missing__` is
not defined, :exc:`KeyError` is raised. :meth:`__missing__` must be a
method; it cannot be an instance variable. For an example, see
:class:`collections.defaultdict`.
.. method:: dict.values()
.. versionadded:: 2.5
Return a copy of the dictionary's list of values. See the note for
:meth:`mapping.items`.
.. _bltin-file-objects:

View File

@@ -15,7 +15,7 @@ classes support the sequence type methods described in the
:ref:`typesseq` section, and also the string-specific methods described
in the :ref:`string-methods` section. To output formatted strings use
template strings or the ``%`` operator described in the
:ref:`typesseq-strings` section. Also, see the :mod:`re` module for
:ref:`string-formatting` section. Also, see the :mod:`re` module for
string functions based on regular expressions.

View File

@@ -12,7 +12,7 @@ In addition, Python's built-in string classes support the sequence type
methods described in the :ref:`typesseq` section, and also the
string-specific methods described in the :ref:`string-methods` section.
To output formatted strings use template strings or the ``%`` operator
described in the :ref:`typesseq-strings` section. Also, see the
described in the :ref:`string-formatting` section. Also, see the
:mod:`re` module for string functions based on regular expressions.

View File

@@ -1701,41 +1701,6 @@ Emulating callable objects
Emulating container types
-------------------------
.. index::
single: keys() (mapping object method)
single: values() (mapping object method)
single: items() (mapping object method)
single: iterkeys() (mapping object method)
single: itervalues() (mapping object method)
single: iteritems() (mapping object method)
single: has_key() (mapping object method)
single: get() (mapping object method)
single: setdefault() (mapping object method)
single: pop() (mapping object method)
single: popitem() (mapping object method)
single: clear() (mapping object method)
single: copy() (mapping object method)
single: update() (mapping object method)
single: __contains__() (mapping object method)
single: append() (sequence object method)
single: count() (sequence object method)
single: extend() (sequence object method)
single: index() (sequence object method)
single: insert() (sequence object method)
single: pop() (sequence object method)
single: remove() (sequence object method)
single: reverse() (sequence object method)
single: sort() (sequence object method)
single: __add__() (sequence object method)
single: __radd__() (sequence object method)
single: __iadd__() (sequence object method)
single: __mul__() (sequence object method)
single: __rmul__() (sequence object method)
single: __imul__() (sequence object method)
single: __contains__() (sequence object method)
single: __iter__() (sequence object method)
single: __coerce__() (numeric object method)
The following methods can be defined to implement container objects. Containers
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
but can represent other containers as well. The first set of methods is used
@@ -1768,7 +1733,7 @@ mappings, :meth:`__iter__` should be the same as :meth:`iterkeys`; for
sequences, it should iterate through the values.
.. method:: container object.__len__(self)
.. method:: object.__len__(self)
.. index::
builtin: len
@@ -1780,7 +1745,7 @@ sequences, it should iterate through the values.
considered to be false in a Boolean context.
.. method:: container object.__getitem__(self, key)
.. method:: object.__getitem__(self, key)
.. index:: object: slice
@@ -1799,7 +1764,7 @@ sequences, it should iterate through the values.
indexes to allow proper detection of the end of the sequence.
.. method:: container object.__setitem__(self, key, value)
.. method:: object.__setitem__(self, key, value)
Called to implement assignment to ``self[key]``. Same note as for
:meth:`__getitem__`. This should only be implemented for mappings if the
@@ -1808,7 +1773,7 @@ sequences, it should iterate through the values.
for improper *key* values as for the :meth:`__getitem__` method.
.. method:: container object.__delitem__(self, key)
.. method:: object.__delitem__(self, key)
Called to implement deletion of ``self[key]``. Same note as for
:meth:`__getitem__`. This should only be implemented for mappings if the
@@ -1817,7 +1782,7 @@ sequences, it should iterate through the values.
values as for the :meth:`__getitem__` method.
.. method:: container object.__iter__(self)
.. method:: object.__iter__(self)
This method is called when an iterator is required for a container. This method
should return a new iterator object that can iterate over all the objects in the
@@ -1833,7 +1798,7 @@ supply the following special method with a more efficient implementation, which
also does not require the object be a sequence.
.. method:: container object.__contains__(self, item)
.. method:: object.__contains__(self, item)
Called to implement membership test operators. Should return true if *item* is
in *self*, false otherwise. For mapping objects, this should consider the keys
@@ -1850,7 +1815,7 @@ objects. Immutable sequences methods should at most only define
:meth:`__getslice__`; mutable sequences might define all three methods.
.. method:: sequence object.__getslice__(self, i, j)
.. method:: object.__getslice__(self, i, j)
.. deprecated:: 2.0
Support slice objects as parameters to the :meth:`__getitem__` method.
@@ -1866,7 +1831,7 @@ objects. Immutable sequences methods should at most only define
is created instead, and passed to :meth:`__getitem__` instead.
.. method:: sequence object.__setslice__(self, i, j, sequence)
.. method:: object.__setslice__(self, i, j, sequence)
Called to implement assignment to ``self[i:j]``. Same notes for *i* and *j* as
for :meth:`__getslice__`.
@@ -1876,7 +1841,7 @@ objects. Immutable sequences methods should at most only define
:meth:`__setitem__`, instead of :meth:`__setslice__` being called.
.. method:: sequence object.__delslice__(self, i, j)
.. method:: object.__delslice__(self, i, j)
Called to implement deletion of ``self[i:j]``. Same notes for *i* and *j* as for
:meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is
@@ -1940,18 +1905,18 @@ number implemented (e.g., bitwise operations for non-integral numbers) should be
left undefined.
.. method:: numeric object.__add__(self, other)
numeric object.__sub__(self, other)
numeric object.__mul__(self, other)
numeric object.__floordiv__(self, other)
numeric object.__mod__(self, other)
numeric object.__divmod__(self, other)
numeric object.__pow__(self, other[, modulo])
numeric object.__lshift__(self, other)
numeric object.__rshift__(self, other)
numeric object.__and__(self, other)
numeric object.__xor__(self, other)
numeric object.__or__(self, other)
.. method:: object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)
.. index::
builtin: divmod
@@ -1972,8 +1937,8 @@ left undefined.
arguments, it should return ``NotImplemented``.
.. method:: numeric object.__div__(self, other)
numeric object.__truediv__(self, other)
.. method:: object.__div__(self, other)
object.__truediv__(self, other)
The division operator (``/``) is implemented by these methods. The
:meth:`__truediv__` method is used when ``__future__.division`` is in effect,
@@ -1982,20 +1947,20 @@ left undefined.
will be raised instead.
.. method:: numeric object.__radd__(self, other)
numeric object.__rsub__(self, other)
numeric object.__rmul__(self, other)
numeric object.__rdiv__(self, other)
numeric object.__rtruediv__(self, other)
numeric object.__rfloordiv__(self, other)
numeric object.__rmod__(self, other)
numeric object.__rdivmod__(self, other)
numeric object.__rpow__(self, other)
numeric object.__rlshift__(self, other)
numeric object.__rrshift__(self, other)
numeric object.__rand__(self, other)
numeric object.__rxor__(self, other)
numeric object.__ror__(self, other)
.. method:: object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rdiv__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)
.. index::
builtin: divmod
@@ -2023,19 +1988,19 @@ left undefined.
subclasses to override their ancestors' operations.
.. method:: numeric object.__iadd__(self, other)
numeric object.__isub__(self, other)
numeric object.__imul__(self, other)
numeric object.__idiv__(self, other)
numeric object.__itruediv__(self, other)
numeric object.__ifloordiv__(self, other)
numeric object.__imod__(self, other)
numeric object.__ipow__(self, other[, modulo])
numeric object.__ilshift__(self, other)
numeric object.__irshift__(self, other)
numeric object.__iand__(self, other)
numeric object.__ixor__(self, other)
numeric object.__ior__(self, other)
.. method:: object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__idiv__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)
These methods are called to implement the augmented arithmetic operations
(``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
@@ -2049,10 +2014,10 @@ left undefined.
and ``y.__radd__(x)`` are considered, as with the evaluation of *x*``+``*y*.
.. method:: numeric object.__neg__(self)
numeric object.__pos__(self)
numeric object.__abs__(self)
numeric object.__invert__(self)
.. method:: object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)
.. index:: builtin: abs
@@ -2060,10 +2025,10 @@ left undefined.
and ``~``).
.. method:: numeric object.__complex__(self)
numeric object.__int__(self)
numeric object.__long__(self)
numeric object.__float__(self)
.. method:: object.__complex__(self)
object.__int__(self)
object.__long__(self)
object.__float__(self)
.. index::
builtin: complex
@@ -2075,8 +2040,8 @@ left undefined.
:func:`long`, and :func:`float`. Should return a value of the appropriate type.
.. method:: numeric object.__oct__(self)
numeric object.__hex__(self)
.. method:: object.__oct__(self)
object.__hex__(self)
.. index::
builtin: oct
@@ -2086,7 +2051,7 @@ left undefined.
return a string value.
.. method:: numeric object.__index__(self)
.. method:: object.__index__(self)
Called to implement :func:`operator.index`. Also called whenever Python needs
an integer object (such as in slicing). Must return an integer (int or long).
@@ -2094,7 +2059,7 @@ left undefined.
.. versionadded:: 2.5
.. method:: numeric object.__coerce__(self, other)
.. method:: object.__coerce__(self, other)
Called to implement "mixed-mode" numeric arithmetic. Should either return a
2-tuple containing *self* and *other* converted to a common numeric type, or
@@ -2233,14 +2198,14 @@ global state, locking and unlocking resources, closing opened files, etc.
For more information on context managers, see :ref:`typecontextmanager`.
.. method:: context manager.__enter__(self)
.. method:: object.__enter__(self)
Enter the runtime context related to this object. The :keyword:`with` statement
will bind this method's return value to the target(s) specified in the
:keyword:`as` clause of the statement, if any.
.. method:: context manager.__exit__(self, exc_type, exc_value, traceback)
.. method:: object.__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters describe the
exception that caused the context to be exited. If the context was exited

View File

@@ -902,7 +902,7 @@ identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
In addition to performing the modulo operation on numbers, the ``%`` operator is
also overloaded by string and unicode objects to perform string formatting (also
known as interpolation). The syntax for string formatting is described in the
Python Library Reference, section :ref:`typesseq-strings`.
Python Library Reference, section :ref:`string-formatting`.
.. deprecated:: 2.3
The floor division operator, the modulo operator, and the :func:`divmod`

View File

@@ -379,7 +379,7 @@ The built-in function :func:`len` returns the length of a string::
Both strings and Unicode strings support a large number of methods for
basic transformations and searching.
:ref:`typesseq-strings`
:ref:`string-formatting`
The formatting operations invoked when strings and Unicode strings are the
left operand of the ``%`` operator are described in more detail here.

View File

@@ -942,7 +942,7 @@ return true, otherwise they return false and raise an appropriate exception.
set and *NULL* returned.
.. _string-formatting:
.. _string-conversion:
String conversion and formatting
================================

View File

@@ -334,7 +334,7 @@ Reader objects (:class:`DictReader` instances and objects returned by the
:func:`reader` function) have the following public methods:
.. method:: csv reader.next()
.. method:: csvreader.next()
Return the next row of the reader's iterable object as a list, parsed according
to the current dialect.
@@ -342,12 +342,12 @@ Reader objects (:class:`DictReader` instances and objects returned by the
Reader objects have the following public attributes:
.. attribute:: csv reader.dialect
.. attribute:: csvreader.dialect
A read-only description of the dialect in use by the parser.
.. attribute:: csv reader.line_num
.. attribute:: csvreader.line_num
The number of lines read from the source iterator. This is not the same as the
number of records returned, as records can span multiple lines.
@@ -367,13 +367,13 @@ out surrounded by parens. This may cause some problems for other programs which
read CSV files (assuming they support complex numbers at all).
.. method:: csv writer.writerow(row)
.. method:: csvwriter.writerow(row)
Write the *row* parameter to the writer's file object, formatted according to
the current dialect.
.. method:: csv writer.writerows(rows)
.. method:: csvwriter.writerows(rows)
Write all the *rows* parameters (a list of *row* objects as described above) to
the writer's file object, formatted according to the current dialect.
@@ -381,7 +381,7 @@ read CSV files (assuming they support complex numbers at all).
Writer objects have the following public attribute:
.. attribute:: csv writer.dialect
.. attribute:: csvwriter.dialect
A read-only description of the dialect in use by the writer.

View File

@@ -231,6 +231,7 @@ available. They are listed here in alphabetical order.
the function serves as a numeric conversion function like :func:`int`,
:func:`long` and :func:`float`. If both arguments are omitted, returns ``0j``.
The complex type is described in :ref:`typesnumeric`.
.. function:: delattr(object, name)
@@ -241,42 +242,10 @@ available. They are listed here in alphabetical order.
.. function:: dict([arg])
:noindex:
Return a new dictionary initialized from an optional positional argument or from
a set of keyword arguments. If no arguments are given, return a new empty
dictionary. If the positional argument *arg* is a mapping object, return a
dictionary mapping the same keys to the same values as does the mapping object.
Otherwise the positional argument must be a sequence, a container that supports
iteration, or an iterator object. The elements of the argument must each also
be of one of those kinds, and each must in turn contain exactly two objects.
The first is used as a key in the new dictionary, and the second as the key's
value. If a given key is seen more than once, the last value associated with it
is retained in the new dictionary.
If keyword arguments are given, the keywords themselves with their associated
values are added as items to the dictionary. If a key is specified both in the
positional argument and as a keyword argument, the value associated with the
keyword is retained in the dictionary. For example, these all return a
dictionary equal to ``{"one": 2, "two": 3}``:
* ``dict({'one': 2, 'two': 3})``
* ``dict({'one': 2, 'two': 3}.items())``
* ``dict({'one': 2, 'two': 3}.iteritems())``
* ``dict(zip(('one', 'two'), (2, 3)))``
* ``dict([['two', 3], ['one', 2]])``
* ``dict(one=2, two=3)``
* ``dict([(['one', 'two'][i-2], i) for i in (2, 3)])``
.. versionadded:: 2.2
.. versionchanged:: 2.3
Support for building a dictionary from keyword arguments added.
Create a new dictionary. The dictionary type is described in
:ref:`typesmapping`.
.. function:: dir([object])
@@ -508,6 +477,7 @@ available. They are listed here in alphabetical order.
these values to be returned depends entirely on the C library and is known to
vary.
The float type is described in :ref:`typesnumeric`.
.. function:: frozenset([iterable])
@@ -518,6 +488,8 @@ available. They are listed here in alphabetical order.
:class:`frozenset` objects. If *iterable* is not specified, returns a new empty
set, ``frozenset([])``.
The frozenset type is described in :ref:`types-set`.
.. versionadded:: 2.4
@@ -596,6 +568,8 @@ available. They are listed here in alphabetical order.
is outside the integer range a long object will be returned instead. If no
arguments are given, returns ``0``.
The integer type is described in :ref:`typesnumeric`.
.. function:: isinstance(object, classinfo)
@@ -655,6 +629,8 @@ available. They are listed here in alphabetical order.
returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If
no argument is given, returns a new empty list, ``[]``.
:class:`list` is a mutable sequence type, as documented in :ref:`typesseq`.
.. function:: locals()
@@ -680,6 +656,7 @@ available. They are listed here in alphabetical order.
with the same value is returned. Conversion of floating point numbers to
integers truncates (towards zero). If no arguments are given, returns ``0L``.
The long type is described in :ref:`typesnumeric`.
.. function:: map(function, iterable, ...)
@@ -942,6 +919,8 @@ available. They are listed here in alphabetical order.
:class:`frozenset` objects. If *iterable* is not specified, returns a new empty
set, ``set([])``.
The set type is described in :ref:`types-set`.
.. versionadded:: 2.4
@@ -1032,13 +1011,12 @@ available. They are listed here in alphabetical order.
acceptable to :func:`eval`; its goal is to return a printable string. If no
argument is given, returns the empty string, ``''``.
For more information on strings see :ref:`typesseq` which describes
sequence functionality (strings are sequences), and also the
string-specific methods described in the :ref:`string-methods`
section. To output formatted strings use template strings or the
``%`` operator described in the :ref:`typesseq-strings` section. In
addition see the :ref:`stringservices` section. See also
:func:`unicode`.
For more information on strings see :ref:`typesseq` which describes sequence
functionality (strings are sequences), and also the string-specific methods
described in the :ref:`string-methods` section. To output formatted strings
use template strings or the ``%`` operator described in the
:ref:`string-formatting` section. In addition see the :ref:`stringservices`
section. See also :func:`unicode`.
.. function:: sum(iterable[, start])
@@ -1082,6 +1060,7 @@ available. They are listed here in alphabetical order.
3])`` returns ``(1, 2, 3)``. If no argument is given, returns a new empty
tuple, ``()``.
:class:`tuple` is a mutable sequence type, as documented in :ref:`typesseq`.
.. function:: type(object)
@@ -1152,11 +1131,10 @@ available. They are listed here in alphabetical order.
For more information on Unicode strings see :ref:`typesseq` which describes
sequence functionality (Unicode strings are sequences), and also the
string-specific methods described in the :ref:`string-methods`
section. To output formatted strings use template strings or the
``%`` operator described in the :ref:`typesseq-strings` section. In
addition see the :ref:`stringservices` section. See also
:func:`str`.
string-specific methods described in the :ref:`string-methods` section. To
output formatted strings use template strings or the ``%`` operator described
in the :ref:`string-formatting` section. In addition see the
:ref:`stringservices` section. See also :func:`str`.
.. versionadded:: 2.0

View File

@@ -612,7 +612,7 @@ format of the messages was also changed, and output went to the specified file
rather than the console.
Formatting uses standard Python string formatting - see section
:ref:`typesseq-strings`. The format string takes the following common
:ref:`string-formatting`. The format string takes the following common
specifiers. For a complete list of specifiers, consult the :class:`Formatter`
documentation.
@@ -1483,7 +1483,7 @@ A Formatter can be initialized with a format string which makes use of knowledge
of the :class:`LogRecord` attributes - such as the default value mentioned above
making use of the fact that the user's message and arguments are pre-formatted
into a :class:`LogRecord`'s *message* attribute. This format string contains
standard python %-style mapping keys. See section :ref:`typesseq-strings`
standard python %-style mapping keys. See section :ref:`string-formatting`
for more information on string formatting.
Currently, the useful mapping keys in a :class:`LogRecord` are:

View File

@@ -124,19 +124,19 @@ The audio device objects returned by :func:`open` define the following methods
and (read-only) attributes:
.. method:: audio device.close()
.. method:: oss_audio_device.close()
Explicitly close the audio device. When you are done writing to or reading from
an audio device, you should explicitly close it. A closed device cannot be used
again.
.. method:: audio device.fileno()
.. method:: oss_audio_device.fileno()
Return the file descriptor associated with the device.
.. method:: audio device.read(size)
.. method:: oss_audio_device.read(size)
Read *size* bytes from the audio input and return them as a Python string.
Unlike most Unix device drivers, OSS audio devices in blocking mode (the
@@ -144,7 +144,7 @@ and (read-only) attributes:
available.
.. method:: audio device.write(data)
.. method:: oss_audio_device.write(data)
Write the Python string *data* to the audio device and return the number of
bytes written. If the audio device is in blocking mode (the default), the
@@ -153,7 +153,7 @@ and (read-only) attributes:
---see :meth:`writeall`.
.. method:: audio device.writeall(data)
.. method:: oss_audio_device.writeall(data)
Write the entire Python string *data* to the audio device: waits until the audio
device is able to accept data, writes as much data as it will accept, and
@@ -169,13 +169,13 @@ be useful when consulting the OSS documentation). If the underlying
:func:`ioctl` fails, they all raise :exc:`IOError`.
.. method:: audio device.nonblock()
.. method:: oss_audio_device.nonblock()
Put the device into non-blocking mode. Once in non-blocking mode, there is no
way to return it to blocking mode.
.. method:: audio device.getfmts()
.. method:: oss_audio_device.getfmts()
Return a bitmask of the audio output formats supported by the soundcard. Some
of the formats supported by OSS are:
@@ -212,7 +212,7 @@ be useful when consulting the OSS documentation). If the underlying
:const:`AFMT_S16_LE`.
.. method:: audio device.setfmt(format)
.. method:: oss_audio_device.setfmt(format)
Try to set the current audio format to *format*---see :meth:`getfmts` for a
list. Returns the audio format that the device was set to, which may not be the
@@ -220,7 +220,7 @@ be useful when consulting the OSS documentation). If the underlying
by passing an "audio format" of :const:`AFMT_QUERY`.
.. method:: audio device.channels(nchannels)
.. method:: oss_audio_device.channels(nchannels)
Set the number of output channels to *nchannels*. A value of 1 indicates
monophonic sound, 2 stereophonic. Some devices may have more than 2 channels,
@@ -228,7 +228,7 @@ be useful when consulting the OSS documentation). If the underlying
the device was set to.
.. method:: audio device.speed(samplerate)
.. method:: oss_audio_device.speed(samplerate)
Try to set the audio sampling rate to *samplerate* samples per second. Returns
the rate actually set. Most sound devices don't support arbitrary sampling
@@ -250,21 +250,21 @@ be useful when consulting the OSS documentation). If the underlying
+-------+-------------------------------------------+
.. method:: audio device.sync()
.. method:: oss_audio_device.sync()
Wait until the sound device has played every byte in its buffer. (This happens
implicitly when the device is closed.) The OSS documentation recommends closing
and re-opening the device rather than using :meth:`sync`.
.. method:: audio device.reset()
.. method:: oss_audio_device.reset()
Immediately stop playing or recording and return the device to a state where it
can accept commands. The OSS documentation recommends closing and re-opening
the device after calling :meth:`reset`.
.. method:: audio device.post()
.. method:: oss_audio_device.post()
Tell the driver that there is likely to be a pause in the output, making it
possible for the device to handle the pause more intelligently. You might use
@@ -275,7 +275,7 @@ The following convenience methods combine several ioctls, or one ioctl and some
simple calculations.
.. method:: audio device.setparameters(format, nchannels, samplerate [, strict=False])
.. method:: oss_audio_device.setparameters(format, nchannels, samplerate [, strict=False])
Set the key audio sampling parameters---sample format, number of channels, and
sampling rate---in one method call. *format*, *nchannels*, and *samplerate*
@@ -298,17 +298,17 @@ simple calculations.
rate = dsp.rate(channels)
.. method:: audio device.bufsize()
.. method:: oss_audio_device.bufsize()
Returns the size of the hardware buffer, in samples.
.. method:: audio device.obufcount()
.. method:: oss_audio_device.obufcount()
Returns the number of samples that are in the hardware buffer yet to be played.
.. method:: audio device.obuffree()
.. method:: oss_audio_device.obuffree()
Returns the number of samples that could be queued into the hardware buffer to
be played without blocking.
@@ -316,17 +316,17 @@ simple calculations.
Audio device objects also support several read-only attributes:
.. attribute:: audio device.closed
.. attribute:: oss_audio_device.closed
Boolean indicating whether the device has been closed.
.. attribute:: audio device.name
.. attribute:: oss_audio_device.name
String containing the name of the device file.
.. attribute:: audio device.mode
.. attribute:: oss_audio_device.mode
The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.
@@ -339,20 +339,20 @@ Mixer Device Objects
The mixer object provides two file-like methods:
.. method:: mixer device.close()
.. method:: oss_mixer_device.close()
This method closes the open mixer device file. Any further attempts to use the
mixer after this file is closed will raise an :exc:`IOError`.
.. method:: mixer device.fileno()
.. method:: oss_mixer_device.fileno()
Returns the file handle number of the open mixer device file.
The remaining methods are specific to audio mixing:
.. method:: mixer device.controls()
.. method:: oss_mixer_device.controls()
This method returns a bitmask specifying the available mixer controls ("Control"
being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
@@ -372,7 +372,7 @@ The remaining methods are specific to audio mixing:
Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.
.. method:: mixer device.stereocontrols()
.. method:: oss_mixer_device.stereocontrols()
Returns a bitmask indicating stereo mixer controls. If a bit is set, the
corresponding control is stereo; if it is unset, the control is either
@@ -383,13 +383,13 @@ The remaining methods are specific to audio mixing:
data from a bitmask.
.. method:: mixer device.reccontrols()
.. method:: oss_mixer_device.reccontrols()
Returns a bitmask specifying the mixer controls that may be used to record. See
the code example for :meth:`controls` for an example of reading from a bitmask.
.. method:: mixer device.get(control)
.. method:: oss_mixer_device.get(control)
Returns the volume of a given mixer control. The returned volume is a 2-tuple
``(left_volume,right_volume)``. Volumes are specified as numbers from 0
@@ -400,7 +400,7 @@ The remaining methods are specific to audio mixing:
:exc:`IOError` if an unsupported control is specified.
.. method:: mixer device.set(control, (left, right))
.. method:: oss_mixer_device.set(control, (left, right))
Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
``right`` must be ints and between 0 (silent) and 100 (full volume). On
@@ -412,13 +412,13 @@ The remaining methods are specific to audio mixing:
specified volumes were out-of-range.
.. method:: mixer device.get_recsrc()
.. method:: oss_mixer_device.get_recsrc()
This method returns a bitmask indicating which control(s) are currently being
used as a recording source.
.. method:: mixer device.set_recsrc(bitmask)
.. method:: oss_mixer_device.set_recsrc(bitmask)
Call this function to specify a recording source. Returns a bitmask indicating
the new recording source (or sources) if successful; raises :exc:`IOError` if an

View File

@@ -47,17 +47,17 @@ The class descriptor objects used as values in the dictionary returned by
:func:`readmodule` and :func:`readmodule_ex` provide the following data members:
.. attribute:: class descriptor.module
.. attribute:: class_descriptor.module
The name of the module defining the class described by the class descriptor.
.. attribute:: class descriptor.name
.. attribute:: class_descriptor.name
The name of the class.
.. attribute:: class descriptor.super
.. attribute:: class_descriptor.super
A list of class descriptors which describe the immediate base classes of the
class being described. Classes which are named as superclasses but which are
@@ -65,17 +65,17 @@ The class descriptor objects used as values in the dictionary returned by
name instead of class descriptors.
.. attribute:: class descriptor.methods
.. attribute:: class_descriptor.methods
A dictionary mapping method names to line numbers.
.. attribute:: class descriptor.file
.. attribute:: class_descriptor.file
Name of the file containing the ``class`` statement defining the class.
.. attribute:: class descriptor.lineno
.. attribute:: class_descriptor.lineno
The line number of the ``class`` statement within the file named by
:attr:`file`.
@@ -90,23 +90,23 @@ The function descriptor objects used as values in the dictionary returned by
:func:`readmodule_ex` provide the following data members:
.. attribute:: function descriptor.module
.. attribute:: function_descriptor.module
The name of the module defining the function described by the function
descriptor.
.. attribute:: function descriptor.name
.. attribute:: function_descriptor.name
The name of the function.
.. attribute:: function descriptor.file
.. attribute:: function_descriptor.file
Name of the file containing the ``def`` statement defining the function.
.. attribute:: function descriptor.lineno
.. attribute:: function_descriptor.lineno
The line number of the ``def`` statement within the file named by :attr:`file`.

View File

@@ -1,3 +1,5 @@
.. XXX: reference/datamodel and this have quite a few overlaps!
.. _bltin-types:
@@ -490,6 +492,8 @@ and range objects.
object: Unicode
object: tuple
object: list
object: buffer
object: range
String literals are written in single or double quotes: ``'xyzzy'``,
``"frobozz"``. See :ref:`strings` for more about string literals. Unicode
@@ -501,18 +505,10 @@ parentheses, but an empty tuple must have the enclosing parentheses, such as
``a, b, c`` or ``()``. A single item tuple must have a trailing comma, such as
``(d,)``.
.. index::
builtin: buffer
object: buffer
Buffer objects are not directly supported by Python syntax, but can be created
by calling the builtin function :func:`buffer`. They don't support
concatenation or repetition.
.. index::
builtin: range
object: range
Xrange objects are similar to buffers in that there is no specific syntax to
create them, but they are created using the :func:`range` function. They don't
support slicing, concatenation or repetition, and using ``in``, ``not in``,
@@ -650,12 +646,11 @@ String Methods
.. index:: pair: string; methods
Below are listed the string methods which both 8-bit strings and Unicode
objects support. In addition, Python's strings support the
sequence type methods described in the
:ref:`typesseq` section (above). To output formatted strings use
template strings or the ``%`` operator described in the
:ref:`typesseq-strings` section (below). Also, see the :mod:`re` module for
Below are listed the string methods which both 8-bit strings and Unicode objects
support. In addition, Python's strings support the sequence type methods
described in the :ref:`typesseq` section (above). To output formatted strings
use template strings or the ``%`` operator described in the
:ref:`string-formatting` section (below). Also, see the :mod:`re` module for
string functions based on regular expressions.
.. method:: str.capitalize()
@@ -1031,7 +1026,7 @@ string functions based on regular expressions.
.. versionadded:: 2.2.2
.. _typesseq-strings:
.. _string-formatting:
String Formatting Operations
----------------------------
@@ -1098,86 +1093,72 @@ sequential parameter list).
The conversion flag characters are:
+---------+-----------------------------------------------+
| Flag | Meaning |
+=========+===============================================+
| ``'#'`` | The value conversion will use the "alternate |
| | form" (where defined below). |
+---------+-----------------------------------------------+
| ``'0'`` | The conversion will be zero padded for |
| | numeric values. |
+---------+-----------------------------------------------+
| ``'-'`` | The converted value is left adjusted |
| | (overrides the ``'0'`` conversion if both are |
| | given). |
+---------+-----------------------------------------------+
| ``' '`` | (a space) A blank should be left before a |
| | positive number (or empty string) produced by |
| | a signed conversion. |
+---------+-----------------------------------------------+
| ``'+'`` | A sign character (``'+'`` or ``'-'``) will |
| | precede the conversion (overrides a "space" |
| | flag). |
+---------+-----------------------------------------------+
+---------+---------------------------------------------------------------------+
| Flag | Meaning |
+=========+=====================================================================+
| ``'#'`` | The value conversion will use the "alternate form" (where defined |
| | below). |
+---------+---------------------------------------------------------------------+
| ``'0'`` | The conversion will be zero padded for numeric values. |
+---------+---------------------------------------------------------------------+
| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
| | conversion if both are given). |
+---------+---------------------------------------------------------------------+
| ``' '`` | (a space) A blank should be left before a positive number (or empty |
| | string) produced by a signed conversion. |
+---------+---------------------------------------------------------------------+
| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
| | (overrides a "space" flag). |
+---------+---------------------------------------------------------------------+
A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
is not necessary for Python.
The conversion types are:
+------------+---------------------------------+-------+
| Conversion | Meaning | Notes |
+============+=================================+=======+
| ``'d'`` | Signed integer decimal. | |
+------------+---------------------------------+-------+
| ``'i'`` | Signed integer decimal. | |
+------------+---------------------------------+-------+
| ``'o'`` | Unsigned octal. | \(1) |
+------------+---------------------------------+-------+
| ``'u'`` | Unsigned decimal. | |
+------------+---------------------------------+-------+
| ``'x'`` | Unsigned hexadecimal | \(2) |
| | (lowercase). | |
+------------+---------------------------------+-------+
| ``'X'`` | Unsigned hexadecimal | \(2) |
| | (uppercase). | |
+------------+---------------------------------+-------+
| ``'e'`` | Floating point exponential | \(3) |
| | format (lowercase). | |
+------------+---------------------------------+-------+
| ``'E'`` | Floating point exponential | \(3) |
| | format (uppercase). | |
+------------+---------------------------------+-------+
| ``'f'`` | Floating point decimal format. | \(3) |
+------------+---------------------------------+-------+
| ``'F'`` | Floating point decimal format. | \(3) |
+------------+---------------------------------+-------+
| ``'g'`` | Floating point format. Uses | \(4) |
| | exponential format if exponent | |
| | is greater than -4 or less than | |
| | precision, decimal format | |
| | otherwise. | |
+------------+---------------------------------+-------+
| ``'G'`` | Floating point format. Uses | \(4) |
| | exponential format if exponent | |
| | is greater than -4 or less than | |
| | precision, decimal format | |
| | otherwise. | |
+------------+---------------------------------+-------+
| ``'c'`` | Single character (accepts | |
| | integer or single character | |
| | string). | |
+------------+---------------------------------+-------+
| ``'r'`` | String (converts any python | \(5) |
| | object using :func:`repr`). | |
+------------+---------------------------------+-------+
| ``'s'`` | String (converts any python | \(6) |
| | object using :func:`str`). | |
+------------+---------------------------------+-------+
| ``'%'`` | No argument is converted, | |
| | results in a ``'%'`` character | |
| | in the result. | |
+------------+---------------------------------+-------+
+------------+-----------------------------------------------------+-------+
| Conversion | Meaning | Notes |
+============+=====================================================+=======+
| ``'d'`` | Signed integer decimal. | |
+------------+-----------------------------------------------------+-------+
| ``'i'`` | Signed integer decimal. | |
+------------+-----------------------------------------------------+-------+
| ``'o'`` | Unsigned octal. | \(1) |
+------------+-----------------------------------------------------+-------+
| ``'u'`` | Unsigned decimal. | |
+------------+-----------------------------------------------------+-------+
| ``'x'`` | Unsigned hexadecimal (lowercase). | \(2) |
+------------+-----------------------------------------------------+-------+
| ``'X'`` | Unsigned hexadecimal (uppercase). | \(2) |
+------------+-----------------------------------------------------+-------+
| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'f'`` | Floating point decimal format. | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'F'`` | Floating point decimal format. | \(3) |
+------------+-----------------------------------------------------+-------+
| ``'g'`` | Floating point format. Uses exponential format if | \(4) |
| | exponent is greater than -4 or less than precision, | |
| | decimal format otherwise. | |
+------------+-----------------------------------------------------+-------+
| ``'G'`` | Floating point format. Uses exponential format if | \(4) |
| | exponent is greater than -4 or less than precision, | |
| | decimal format otherwise. | |
+------------+-----------------------------------------------------+-------+
| ``'c'`` | Single character (accepts integer or single | |
| | character string). | |
+------------+-----------------------------------------------------+-------+
| ``'r'`` | String (converts any python object using | \(5) |
| | :func:`repr`). | |
+------------+-----------------------------------------------------+-------+
| ``'s'`` | String (converts any python object using | \(6) |
| | :func:`str`). | |
+------------+-----------------------------------------------------+-------+
| ``'%'`` | No argument is converted, results in a ``'%'`` | |
| | character in the result. | |
+------------+-----------------------------------------------------+-------+
Notes:
@@ -1437,37 +1418,52 @@ element of another set.
Instances of :class:`set` and :class:`frozenset` provide the following
operations:
+-------------------------------+------------+---------------------------------+
| Operation | Equivalent | Result |
+===============================+============+=================================+
| ``len(s)`` | | cardinality of set *s* |
+-------------------------------+------------+---------------------------------+
| ``x in s`` | | test *x* for membership in *s* |
+-------------------------------+------------+---------------------------------+
| ``x not in s`` | | test *x* for non-membership in |
| | | *s* |
+-------------------------------+------------+---------------------------------+
| ``s.issubset(t)`` | ``s <= t`` | test whether every element in |
| | | *s* is in *t* |
+-------------------------------+------------+---------------------------------+
| ``s.issuperset(t)`` | ``s >= t`` | test whether every element in |
| | | *t* is in *s* |
+-------------------------------+------------+---------------------------------+
| ``s.union(t)`` | *s* \| *t* | new set with elements from both |
| | | *s* and *t* |
+-------------------------------+------------+---------------------------------+
| ``s.intersection(t)`` | *s* & *t* | new set with elements common to |
| | | *s* and *t* |
+-------------------------------+------------+---------------------------------+
| ``s.difference(t)`` | *s* - *t* | new set with elements in *s* |
| | | but not in *t* |
+-------------------------------+------------+---------------------------------+
| ``s.symmetric_difference(t)`` | *s* ^ *t* | new set with elements in either |
| | | *s* or *t* but not both |
+-------------------------------+------------+---------------------------------+
| ``s.copy()`` | | new set with a shallow copy of |
| | | *s* |
+-------------------------------+------------+---------------------------------+
.. describe:: len(s)
Return the cardinality of set *s*.
.. describe:: x in s
Test *x* for membership in *s*.
.. describe:: x not in s
Test *x* for non-membership in *s*.
.. method:: set.issubset(other)
set <= other
Test whether every element in the set is in *other*.
.. method:: set.issuperset(other)
set >= other
Test whether every element in *other* is in the set.
.. method:: set.union(other)
set | other
Return a new set with elements from both sets.
.. method:: set.intersection(other)
set & other
Return a new set with elements common to both sets.
.. method:: set.difference(other)
set - other
Return a new set with elements in the set that are not in *other*.
.. method:: set.symmetric_difference(other)
set ^ other
Return a new set with elements in either the set or *other* but not both.
.. method:: set.copy()
Return a new set with a shallow copy of *s*.
Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
:meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
@@ -1505,38 +1501,48 @@ returns an instance of :class:`frozenset`.
The following table lists operations available for :class:`set` that do not
apply to immutable instances of :class:`frozenset`:
+--------------------------------------+-------------+---------------------------------+
| Operation | Equivalent | Result |
+======================================+=============+=================================+
| ``s.update(t)`` | *s* \|= *t* | update set *s*, adding elements |
| | | from *t* |
+--------------------------------------+-------------+---------------------------------+
| ``s.intersection_update(t)`` | *s* &= *t* | update set *s*, keeping only |
| | | elements found in both *s* and |
| | | *t* |
+--------------------------------------+-------------+---------------------------------+
| ``s.difference_update(t)`` | *s* -= *t* | update set *s*, removing |
| | | elements found in *t* |
+--------------------------------------+-------------+---------------------------------+
| ``s.symmetric_difference_update(t)`` | *s* ^= *t* | update set *s*, keeping only |
| | | elements found in either *s* or |
| | | *t* but not in both |
+--------------------------------------+-------------+---------------------------------+
| ``s.add(x)`` | | add element *x* to set *s* |
+--------------------------------------+-------------+---------------------------------+
| ``s.remove(x)`` | | remove *x* from set *s*; raises |
| | | :exc:`KeyError` if not present |
+--------------------------------------+-------------+---------------------------------+
| ``s.discard(x)`` | | removes *x* from set *s* if |
| | | present |
+--------------------------------------+-------------+---------------------------------+
| ``s.pop()`` | | remove and return an arbitrary |
| | | element from *s*; raises |
| | | :exc:`KeyError` if empty |
+--------------------------------------+-------------+---------------------------------+
| ``s.clear()`` | | remove all elements from set |
| | | *s* |
+--------------------------------------+-------------+---------------------------------+
.. method:: set.update(other)
set |= other
Update the set, adding elements from *other*.
.. method:: set.intersection_update(other)
set &= other
Update the set, keeping only elements found in it and *other*.
.. method:: set.difference_update(other)
set -= other
Update the set, removing elements found in *other*.
.. method:: set.symmetric_difference_update(other)
set ^= other
Update the set, keeping only elements found in either set, but not in both.
.. method:: set.add(el)
Add element *el* to the set.
.. method:: set.remove(el)
Remove element *el* from the set. Raises :exc:`KeyError` if *el* is not
contained in the set.
.. method:: set.discard(el)
Remove element *el* from the set if it is present.
.. method:: set.pop()
Remove and return an arbitrary element from the set. Raises :exc:`KeyError`
if the set is empty.
.. method:: set.clear()
Remove all elements from the set.
Note, the non-operator versions of the :meth:`update`,
:meth:`intersection_update`, :meth:`difference_update`, and
@@ -1552,173 +1558,216 @@ Mapping Types --- :class:`dict`
.. index::
object: mapping
object: dictionary
triple: operations on; mapping; types
triple: operations on; dictionary; type
statement: del
builtin: len
A :dfn:`mapping` object maps immutable values to arbitrary objects. Mappings
A :dfn:`mapping` object maps immutable values to arbitrary objects. Mappings
are mutable objects. There is currently only one standard mapping type, the
:dfn:`dictionary`. A dictionary's keys are almost arbitrary values. Only
:dfn:`dictionary`. A dictionary's keys are *almost* arbitrary values. Only
values containing lists, dictionaries or other mutable types (that are compared
by value rather than by object identity) may not be used as keys. Numeric types
used for keys obey the normal rules for numeric comparison: if two numbers
compare equal (such as ``1`` and ``1.0``) then they can be used interchangeably
to index the same dictionary entry.
Dictionaries are created by placing a comma-separated list of ``key: value``
Dictionaries can be created by placing a comma-separated list of ``key: value``
pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
'jack', 4127: 'sjoerd'}``.
'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
.. index::
triple: operations on; mapping; types
triple: operations on; dictionary; type
statement: del
builtin: len
single: clear() (dictionary method)
single: copy() (dictionary method)
single: has_key() (dictionary method)
single: fromkeys() (dictionary method)
single: items() (dictionary method)
single: keys() (dictionary method)
single: update() (dictionary method)
single: values() (dictionary method)
single: get() (dictionary method)
single: setdefault() (dictionary method)
single: pop() (dictionary method)
single: popitem() (dictionary method)
single: iteritems() (dictionary method)
single: iterkeys() (dictionary method)
single: itervalues() (dictionary method)
.. class:: dict([arg])
The following operations are defined on mappings (where *a* and *b* are
mappings, *k* is a key, and *v* and *x* are arbitrary objects):
Return a new dictionary initialized from an optional positional argument or from
a set of keyword arguments. If no arguments are given, return a new empty
dictionary. If the positional argument *arg* is a mapping object, return a
dictionary mapping the same keys to the same values as does the mapping object.
Otherwise the positional argument must be a sequence, a container that supports
iteration, or an iterator object. The elements of the argument must each also
be of one of those kinds, and each must in turn contain exactly two objects.
The first is used as a key in the new dictionary, and the second as the key's
value. If a given key is seen more than once, the last value associated with it
is retained in the new dictionary.
+--------------------------------+---------------------------------+-----------+
| Operation | Result | Notes |
+================================+=================================+===========+
| ``len(a)`` | the number of items in *a* | |
+--------------------------------+---------------------------------+-----------+
| ``a[k]`` | the item of *a* with key *k* | (1), (10) |
+--------------------------------+---------------------------------+-----------+
| ``a[k] = v`` | set ``a[k]`` to *v* | |
+--------------------------------+---------------------------------+-----------+
| ``del a[k]`` | remove ``a[k]`` from *a* | \(1) |
+--------------------------------+---------------------------------+-----------+
| ``a.clear()`` | remove all items from ``a`` | |
+--------------------------------+---------------------------------+-----------+
| ``a.copy()`` | a (shallow) copy of ``a`` | |
+--------------------------------+---------------------------------+-----------+
| ``k in a`` | ``True`` if *a* has a key *k*, | \(2) |
| | else ``False`` | |
+--------------------------------+---------------------------------+-----------+
| ``k not in a`` | Equivalent to ``not`` *k* in | \(2) |
| | *a* | |
+--------------------------------+---------------------------------+-----------+
| ``a.has_key(k)`` | Equivalent to *k* ``in`` *a*, | |
| | use that form in new code | |
+--------------------------------+---------------------------------+-----------+
| ``a.items()`` | a copy of *a*'s list of (*key*, | \(3) |
| | *value*) pairs | |
+--------------------------------+---------------------------------+-----------+
| ``a.keys()`` | a copy of *a*'s list of keys | \(3) |
+--------------------------------+---------------------------------+-----------+
| ``a.update([b])`` | updates *a* with key/value | \(9) |
| | pairs from *b*, overwriting | |
| | existing keys, returns ``None`` | |
+--------------------------------+---------------------------------+-----------+
| ``a.fromkeys(seq[, value])`` | Creates a new dictionary with | \(7) |
| | keys from *seq* and values set | |
| | to *value* | |
+--------------------------------+---------------------------------+-----------+
| ``a.values()`` | a copy of *a*'s list of values | \(3) |
+--------------------------------+---------------------------------+-----------+
| ``a.get(k[, x])`` | ``a[k]`` if ``k in a``, else | \(4) |
| | *x* | |
+--------------------------------+---------------------------------+-----------+
| ``a.setdefault(k[, x])`` | ``a[k]`` if ``k in a``, else | \(5) |
| | *x* (also setting it) | |
+--------------------------------+---------------------------------+-----------+
| ``a.pop(k[, x])`` | ``a[k]`` if ``k in a``, else | \(8) |
| | *x* (and remove k) | |
+--------------------------------+---------------------------------+-----------+
| ``a.popitem()`` | remove and return an arbitrary | \(6) |
| | (*key*, *value*) pair | |
+--------------------------------+---------------------------------+-----------+
| ``a.iteritems()`` | return an iterator over (*key*, | (2), (3) |
| | *value*) pairs | |
+--------------------------------+---------------------------------+-----------+
| ``a.iterkeys()`` | return an iterator over the | (2), (3) |
| | mapping's keys | |
+--------------------------------+---------------------------------+-----------+
| ``a.itervalues()`` | return an iterator over the | (2), (3) |
| | mapping's values | |
+--------------------------------+---------------------------------+-----------+
If keyword arguments are given, the keywords themselves with their associated
values are added as items to the dictionary. If a key is specified both in the
positional argument and as a keyword argument, the value associated with the
keyword is retained in the dictionary. For example, these all return a
dictionary equal to ``{"one": 2, "two": 3}``:
Notes:
* ``dict({'one': 2, 'two': 3})``
(1)
Raises a :exc:`KeyError` exception if *k* is not in the map.
* ``dict({'one': 2, 'two': 3}.items())``
* ``dict({'one': 2, 'two': 3}.iteritems())``
* ``dict(zip(('one', 'two'), (2, 3)))``
* ``dict([['two', 3], ['one', 2]])``
* ``dict(one=2, two=3)``
* ``dict([(['one', 'two'][i-2], i) for i in (2, 3)])``
(2)
.. versionadded:: 2.2
(3)
Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations, and depends on the dictionary's history of
insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`,
:meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no
intervening modifications to the dictionary, the lists will directly correspond.
This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
zip(a.values(), a.keys())``. The same relationship holds for the
:meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(a.itervalues(),
a.iterkeys())`` provides the same value for ``pairs``. Another way to create the
same list is ``pairs = [(v, k) for (k, v) in a.iteritems()]``.
.. versionchanged:: 2.3
Support for building a dictionary from keyword arguments added.
(4)
Never raises an exception if *k* is not in the map, instead it returns *x*. *x*
is optional; when *x* is not provided and *k* is not in the map, ``None`` is
returned.
(5)
:func:`setdefault` is like :func:`get`, except that if *k* is missing, *x* is
both returned and inserted into the dictionary as the value of *k*. *x* defaults
to ``None``.
These are the operations that dictionaries support (and therefore, custom mapping
types should support too):
(6)
:func:`popitem` is useful to destructively iterate over a dictionary, as often
used in set algorithms. If the dictionary is empty, calling :func:`popitem`
raises a :exc:`KeyError`.
.. describe:: len(d)
Return the number of items in the dictionary *d*.
.. describe:: d[key]
Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
not in the map.
.. versionadded:: 2.5
If a subclass of dict defines a method :meth:`__missing__`, if the key
*key* is not present, the ``d[key]`` operation calls that method with the
key *key* as argument. The ``d[key]`` operation then returns or raises
whatever is returned or raised by the ``__missing__(key)`` call if the key
is not present. No other operations or methods invoke
:meth:`__missing__`. If :meth:`__missing__` is not defined,
:exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
cannot be an instance variable. For an example, see
:class:`collections.defaultdict`.
.. describe:: d[key] = value
Set ``d[key]`` to *value*.
.. describe:: del d[key]
Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
map.
.. describe:: key in d
Return ``True`` if *d* has a key *key*, else ``False``.
.. versionadded:: 2.2
.. describe:: key not in d
Equivalent to ``not key in d``.
.. versionadded:: 2.2
.. method:: dict.clear()
Remove all items from the dictionary.
.. method:: dict.copy()
Return a shallow copy of the dictionary.
.. method:: dict.fromkeys(seq[, value])
Create a new dictionary with keys from *seq* and values set to *value*.
(7)
:func:`fromkeys` is a class method that returns a new dictionary. *value*
defaults to ``None``.
.. versionadded:: 2.3
(8)
:func:`pop` raises a :exc:`KeyError` when no default value is given and the key
is not found.
.. method:: dict.get(key[, default])
Return the value for *key* if *key* is in the dictionary, else *default*. If
*default* is not given, it defaults to ``None``, so that this method never
raises a :exc:`KeyError`.
.. method:: dict.has_key(key)
``d.has_key(key)`` is equivalent to ``key in d``, but deprecated.
.. method:: dict.items()
Return a copy of the dictionary's list of ``(key, value)`` pairs.
.. note::
Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations, and depends on the dictionary's history of
insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`,
:meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no
intervening modifications to the dictionary, the lists will directly correspond.
This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
zip(d.values(), d.keys())``. The same relationship holds for the
:meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(d.itervalues(),
d.iterkeys())`` provides the same value for ``pairs``. Another way to create the
same list is ``pairs = [(v, k) for (k, v) in d.iteritems()]``.
.. method:: dict.iteritems()
Return an iterator over the dictionary's ``(key, value)`` pairs.
See the note for :meth:`dict.items`.
.. versionadded:: 2.2
.. method:: dict.iterkeys()
Return an iterator over the dictionary's keys. See the note for
:meth:`dict.items`.
.. versionadded:: 2.2
.. method:: dict.itervalues()
Return an iterator over the dictionary's values. See the note for
:meth:`dict.items`.
.. versionadded:: 2.2
.. method:: dict.keys()
Return a copy of the dictionary's list of keys. See the note for
:meth:`dict.items`.
.. method:: dict.pop(key[, default])
If *key* is in the dictionary, remove it and return its value, else return
*default*. If *default* is not given and *key* is not in the dictionary, a
:exc:`KeyError` is raised.
.. versionadded:: 2.3
(9)
:func:`update` accepts either another mapping object or an iterable of key/value
pairs (as a tuple or other iterable of length two). If keyword arguments are
specified, the mapping is then is updated with those key/value pairs:
``d.update(red=1, blue=2)``.
.. method:: dict.popitem()
Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
:func:`popitem` is useful to destructively iterate over a dictionary, as
often used in set algorithms. If the dictionary is empty, calling
:func:`popitem` raises a :exc:`KeyError`.
.. method:: dict.setdefault(key[, default])
If *key* is in the dictionary, return its value. If not, insert *key* with a
value of *default* and return *default*. *default* defaults to ``None``.
.. method:: dict.update([other])
Update the dictionary with the key/value pairs from *other*, overwriting existing
keys. Return ``None``.
:func:`update` accepts either another dictionary object or an iterable of
key/value pairs (as a tuple or other iterable of length two). If keyword
arguments are specified, the dictionary is then is updated with those
key/value pairs: ``d.update(red=1, blue=2)``.
.. versionchanged:: 2.4
Allowed the argument to be an iterable of key/value pairs and allowed keyword
arguments.
Allowed the argument to be an iterable of key/value pairs and allowed
keyword arguments.
(10)
If a subclass of dict defines a method :meth:`__missing__`, if the key *k* is
not present, the ``a[k]`` operation calls that method with the key *k* as
argument. The ``a[k]`` operation then returns or raises whatever is returned
or raised by the ``__missing__(k)`` call if the key is not present. No other
operations or methods invoke :meth:`__missing__`. If :meth:`__missing__` is
not defined, :exc:`KeyError` is raised. :meth:`__missing__` must be a
method; it cannot be an instance variable. For an example, see
:class:`collections.defaultdict`.
.. method:: dict.values()
.. versionadded:: 2.5
Return a copy of the dictionary's list of values. See the note for
:meth:`mapping.items`.
.. _bltin-file-objects:

View File

@@ -15,7 +15,7 @@ classes support the sequence type methods described in the
:ref:`typesseq` section, and also the string-specific methods described
in the :ref:`string-methods` section. To output formatted strings use
template strings or the ``%`` operator described in the
:ref:`typesseq-strings` section. Also, see the :mod:`re` module for
:ref:`string-formatting` section. Also, see the :mod:`re` module for
string functions based on regular expressions.

View File

@@ -12,7 +12,7 @@ In addition, Python's built-in string classes support the sequence type
methods described in the :ref:`typesseq` section, and also the
string-specific methods described in the :ref:`string-methods` section.
To output formatted strings use template strings or the ``%`` operator
described in the :ref:`typesseq-strings` section. Also, see the
described in the :ref:`string-formatting` section. Also, see the
:mod:`re` module for string functions based on regular expressions.

View File

@@ -1699,40 +1699,6 @@ Emulating callable objects
Emulating container types
-------------------------
.. index::
single: keys() (mapping object method)
single: values() (mapping object method)
single: items() (mapping object method)
single: iterkeys() (mapping object method)
single: itervalues() (mapping object method)
single: iteritems() (mapping object method)
single: has_key() (mapping object method)
single: get() (mapping object method)
single: setdefault() (mapping object method)
single: pop() (mapping object method)
single: popitem() (mapping object method)
single: clear() (mapping object method)
single: copy() (mapping object method)
single: update() (mapping object method)
single: __contains__() (mapping object method)
single: append() (sequence object method)
single: count() (sequence object method)
single: extend() (sequence object method)
single: index() (sequence object method)
single: insert() (sequence object method)
single: pop() (sequence object method)
single: remove() (sequence object method)
single: reverse() (sequence object method)
single: sort() (sequence object method)
single: __add__() (sequence object method)
single: __radd__() (sequence object method)
single: __iadd__() (sequence object method)
single: __mul__() (sequence object method)
single: __rmul__() (sequence object method)
single: __imul__() (sequence object method)
single: __contains__() (sequence object method)
single: __iter__() (sequence object method)
The following methods can be defined to implement container objects. Containers
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
but can represent other containers as well. The first set of methods is used
@@ -1765,7 +1731,7 @@ be the same as :meth:`iterkeys`; for sequences, it should iterate through the
values.
.. method:: container object.__len__(self)
.. method:: object.__len__(self)
.. index::
builtin: len
@@ -1777,7 +1743,7 @@ values.
considered to be false in a Boolean context.
.. method:: container object.__getitem__(self, key)
.. method:: object.__getitem__(self, key)
.. index:: object: slice
@@ -1796,7 +1762,7 @@ values.
indexes to allow proper detection of the end of the sequence.
.. method:: container object.__setitem__(self, key, value)
.. method:: object.__setitem__(self, key, value)
Called to implement assignment to ``self[key]``. Same note as for
:meth:`__getitem__`. This should only be implemented for mappings if the
@@ -1805,7 +1771,7 @@ values.
for improper *key* values as for the :meth:`__getitem__` method.
.. method:: container object.__delitem__(self, key)
.. method:: object.__delitem__(self, key)
Called to implement deletion of ``self[key]``. Same note as for
:meth:`__getitem__`. This should only be implemented for mappings if the
@@ -1814,7 +1780,7 @@ values.
values as for the :meth:`__getitem__` method.
.. method:: container object.__iter__(self)
.. method:: object.__iter__(self)
This method is called when an iterator is required for a container. This method
should return a new iterator object that can iterate over all the objects in the
@@ -1830,7 +1796,7 @@ supply the following special method with a more efficient implementation, which
also does not require the object be a sequence.
.. method:: container object.__contains__(self, item)
.. method:: object.__contains__(self, item)
Called to implement membership test operators. Should return true if *item* is
in *self*, false otherwise. For mapping objects, this should consider the keys
@@ -1847,7 +1813,7 @@ objects. Immutable sequences methods should at most only define
:meth:`__getslice__`; mutable sequences might define all three methods.
.. method:: sequence object.__getslice__(self, i, j)
.. method:: object.__getslice__(self, i, j)
.. deprecated:: 2.0
Support slice objects as parameters to the :meth:`__getitem__` method.
@@ -1863,7 +1829,7 @@ objects. Immutable sequences methods should at most only define
is created instead, and passed to :meth:`__getitem__` instead.
.. method:: sequence object.__setslice__(self, i, j, sequence)
.. method:: object.__setslice__(self, i, j, sequence)
Called to implement assignment to ``self[i:j]``. Same notes for *i* and *j* as
for :meth:`__getslice__`.
@@ -1873,7 +1839,7 @@ objects. Immutable sequences methods should at most only define
:meth:`__setitem__`, instead of :meth:`__setslice__` being called.
.. method:: sequence object.__delslice__(self, i, j)
.. method:: object.__delslice__(self, i, j)
Called to implement deletion of ``self[i:j]``. Same notes for *i* and *j* as for
:meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is
@@ -1937,18 +1903,18 @@ number implemented (e.g., bitwise operations for non-integral numbers) should be
left undefined.
.. method:: numeric object.__add__(self, other)
numeric object.__sub__(self, other)
numeric object.__mul__(self, other)
numeric object.__floordiv__(self, other)
numeric object.__mod__(self, other)
numeric object.__divmod__(self, other)
numeric object.__pow__(self, other[, modulo])
numeric object.__lshift__(self, other)
numeric object.__rshift__(self, other)
numeric object.__and__(self, other)
numeric object.__xor__(self, other)
numeric object.__or__(self, other)
.. method:: object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)
.. index::
builtin: divmod
@@ -1969,8 +1935,8 @@ left undefined.
arguments, it should return ``NotImplemented``.
.. method:: numeric object.__div__(self, other)
numeric object.__truediv__(self, other)
.. method:: object.__div__(self, other)
object.__truediv__(self, other)
The division operator (``/``) is implemented by these methods. The
:meth:`__truediv__` method is used when ``__future__.division`` is in effect,
@@ -1979,20 +1945,20 @@ left undefined.
will be raised instead.
.. method:: numeric object.__radd__(self, other)
numeric object.__rsub__(self, other)
numeric object.__rmul__(self, other)
numeric object.__rdiv__(self, other)
numeric object.__rtruediv__(self, other)
numeric object.__rfloordiv__(self, other)
numeric object.__rmod__(self, other)
numeric object.__rdivmod__(self, other)
numeric object.__rpow__(self, other)
numeric object.__rlshift__(self, other)
numeric object.__rrshift__(self, other)
numeric object.__rand__(self, other)
numeric object.__rxor__(self, other)
numeric object.__ror__(self, other)
.. method:: object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rdiv__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)
.. index::
builtin: divmod
@@ -2020,19 +1986,19 @@ left undefined.
subclasses to override their ancestors' operations.
.. method:: numeric object.__iadd__(self, other)
numeric object.__isub__(self, other)
numeric object.__imul__(self, other)
numeric object.__idiv__(self, other)
numeric object.__itruediv__(self, other)
numeric object.__ifloordiv__(self, other)
numeric object.__imod__(self, other)
numeric object.__ipow__(self, other[, modulo])
numeric object.__ilshift__(self, other)
numeric object.__irshift__(self, other)
numeric object.__iand__(self, other)
numeric object.__ixor__(self, other)
numeric object.__ior__(self, other)
.. method:: object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__idiv__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)
These methods are called to implement the augmented arithmetic operations
(``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
@@ -2046,10 +2012,10 @@ left undefined.
and ``y.__radd__(x)`` are considered, as with the evaluation of *x*``+``*y*.
.. method:: numeric object.__neg__(self)
numeric object.__pos__(self)
numeric object.__abs__(self)
numeric object.__invert__(self)
.. method:: object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)
.. index:: builtin: abs
@@ -2057,10 +2023,10 @@ left undefined.
and ``~``).
.. method:: numeric object.__complex__(self)
numeric object.__int__(self)
numeric object.__long__(self)
numeric object.__float__(self)
.. method:: object.__complex__(self)
object.__int__(self)
object.__long__(self)
object.__float__(self)
.. index::
builtin: complex
@@ -2072,7 +2038,7 @@ left undefined.
:func:`long`, and :func:`float`. Should return a value of the appropriate type.
.. method:: numeric object.__index__(self)
.. method:: object.__index__(self)
Called to implement :func:`operator.index`. Also called whenever Python needs
an integer object (such as in slicing, or in the built-in :func:`bin`,
@@ -2105,14 +2071,14 @@ global state, locking and unlocking resources, closing opened files, etc.
For more information on context managers, see :ref:`typecontextmanager`.
.. method:: context manager.__enter__(self)
.. method:: object.__enter__(self)
Enter the runtime context related to this object. The :keyword:`with` statement
will bind this method's return value to the target(s) specified in the
:keyword:`as` clause of the statement, if any.
.. method:: context manager.__exit__(self, exc_type, exc_value, traceback)
.. method:: object.__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters describe the
exception that caused the context to be exited. If the context was exited

View File

@@ -854,7 +854,7 @@ identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
In addition to performing the modulo operation on numbers, the ``%`` operator is
also overloaded by string and unicode objects to perform string formatting (also
known as interpolation). The syntax for string formatting is described in the
Python Library Reference, section :ref:`typesseq-strings`.
Python Library Reference, section :ref:`string-formatting`.
.. deprecated:: 2.3
The floor division operator, the modulo operator, and the :func:`divmod`

View File

@@ -379,7 +379,7 @@ The built-in function :func:`len` returns the length of a string::
Both strings and Unicode strings support a large number of methods for
basic transformations and searching.
:ref:`typesseq-strings`
:ref:`string-formatting`
The formatting operations invoked when strings and Unicode strings are the
left operand of the ``%`` operator are described in more detail here.

View File

@@ -64,7 +64,7 @@ def highlight_block(source, lang):
# maybe Python -- try parsing it
try:
parser.suite(source + '\n')
except SyntaxError:
except (SyntaxError, UnicodeEncodeError):
return '<pre>' + cgi.escape(source) + '</pre>\n'
else:
lexer = lexers['python']