Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/library/functions.rst

    r2 r391  
    77The Python interpreter has a number of functions built into it that are always
    88available.  They are listed here in alphabetical order.
     9
     10===================  =================  ==================  =================  ====================
     11..                   ..                 Built-in Functions  ..                 ..
     12===================  =================  ==================  =================  ====================
     13:func:`abs`          :func:`divmod`     :func:`input`       :func:`open`       :func:`staticmethod`
     14:func:`all`          :func:`enumerate`  :func:`int`         :func:`ord`        :func:`str`
     15:func:`any`          :func:`eval`       :func:`isinstance`  :func:`pow`        :func:`sum`
     16:func:`basestring`   :func:`execfile`   :func:`issubclass`  :func:`print`      :func:`super`
     17:func:`bin`          :func:`file`       :func:`iter`        :func:`property`   :func:`tuple`
     18:func:`bool`         :func:`filter`     :func:`len`         :func:`range`      :func:`type`
     19:func:`bytearray`    :func:`float`      :func:`list`        :func:`raw_input`  :func:`unichr`
     20:func:`callable`     :func:`format`     :func:`locals`      :func:`reduce`     :func:`unicode`
     21:func:`chr`          |func-frozenset|_  :func:`long`        :func:`reload`     :func:`vars`
     22:func:`classmethod`  :func:`getattr`    :func:`map`         |func-repr|_       :func:`xrange`
     23:func:`cmp`          :func:`globals`    :func:`max`         :func:`reversed`   :func:`zip`
     24:func:`compile`      :func:`hasattr`    |func-memoryview|_  :func:`round`      :func:`__import__`
     25:func:`complex`      :func:`hash`       :func:`min`         |func-set|_        :func:`apply`
     26:func:`delattr`      :func:`help`       :func:`next`        :func:`setattr`    :func:`buffer`
     27|func-dict|_         :func:`hex`        :func:`object`      :func:`slice`      :func:`coerce`
     28:func:`dir`          :func:`id`         :func:`oct`         :func:`sorted`     :func:`intern`
     29===================  =================  ==================  =================  ====================
     30
     31.. using :func:`dict` would create a link to another page, so local targets are
     32   used, with replacement texts to make the output in the table consistent
     33
     34.. |func-dict| replace:: ``dict()``
     35.. |func-frozenset| replace:: ``frozenset()``
     36.. |func-memoryview| replace:: ``memoryview()``
     37.. |func-repr| replace:: ``repr()``
     38.. |func-set| replace:: ``set()``
    939
    1040
     
    77107   .. versionchanged:: 2.3
    78108      If no argument is given, this function returns :const:`False`.
     109
     110
     111.. function:: bytearray([source[, encoding[, errors]]])
     112
     113   Return a new array of bytes.  The :class:`bytearray` type is a mutable
     114   sequence of integers in the range 0 <= x < 256.  It has most of the usual
     115   methods of mutable sequences, described in :ref:`typesseq-mutable`, as well
     116   as most methods that the :class:`str` type has, see :ref:`string-methods`.
     117
     118   The optional *source* parameter can be used to initialize the array in a few
     119   different ways:
     120
     121   * If it is a *string*, you must also give the *encoding* (and optionally,
     122     *errors*) parameters; :func:`bytearray` then converts the string to
     123     bytes using :meth:`str.encode`.
     124
     125   * If it is an *integer*, the array will have that size and will be
     126     initialized with null bytes.
     127
     128   * If it is an object conforming to the *buffer* interface, a read-only buffer
     129     of the object will be used to initialize the bytes array.
     130
     131   * If it is an *iterable*, it must be an iterable of integers in the range
     132     ``0 <= x < 256``, which are used as the initial contents of the array.
     133
     134   Without an argument, an array of size 0 is created.
     135
     136   .. versionadded:: 2.6
    79137
    80138
     
    106164   idiom::
    107165
    108       class C:
     166      class C(object):
    109167          @classmethod
    110           def f(cls, arg1, arg2, ...): ...
     168          def f(cls, arg1, arg2, ...):
     169              ...
    111170
    112171   The ``@classmethod`` form is a function :term:`decorator` -- see the description
     
    141200   Compile the *source* into a code or AST object.  Code objects can be executed
    142201   by an :keyword:`exec` statement or evaluated by a call to :func:`eval`.
    143    *source* can either be a string or an AST object.  Refer to the :mod:`ast`
    144    module documentation for information on how to work with AST objects.
     202   *source* can either be a Unicode string, a *Latin-1* encoded string or an
     203   AST object.
     204   Refer to the :mod:`ast` module documentation for information on how to work
     205   with AST objects.
    145206
    146207   The *filename* argument should give the file from which the code was read;
     
    166227   Future statements are specified by bits which can be bitwise ORed together to
    167228   specify multiple statements.  The bitfield required to specify a given feature
    168    can be found as the :attr:`compiler_flag` attribute on the :class:`_Feature`
    169    instance in the :mod:`__future__` module.
     229   can be found as the :attr:`~__future__._Feature.compiler_flag` attribute on
     230   the :class:`~__future__._Feature` instance in the :mod:`__future__` module.
    170231
    171232   This function raises :exc:`SyntaxError` if the compiled source is invalid,
     
    174235   .. note::
    175236
    176       When compiling a string with multi-line statements, line endings must be
    177       represented by a single newline character (``'\n'``), and the input must
    178       be terminated by at least one newline character.  If line endings are
    179       represented by ``'\r\n'``, use :meth:`str.replace` to change them into
    180       ``'\n'``.
     237      When compiling a string with multi-line code in ``'single'`` or
     238      ``'eval'`` mode, input must be terminated by at least one newline
     239      character.  This is to facilitate detection of incomplete and complete
     240      statements in the :mod:`code` module.
    181241
    182242   .. versionchanged:: 2.3
     
    185245   .. versionchanged:: 2.6
    186246      Support for compiling AST objects.
     247
     248   .. versionchanged:: 2.7
     249      Allowed use of Windows and Mac newlines.  Also input in ``'exec'`` mode
     250      does not have to end in a newline anymore.
    187251
    188252
     
    197261   :func:`long` and :func:`float`.  If both arguments are omitted, returns ``0j``.
    198262
     263   .. note::
     264
     265      When converting from a string, the string must not contain whitespace
     266      around the central ``+`` or ``-`` operator.  For example,
     267      ``complex('1+2j')`` is fine, but ``complex('1 + 2j')`` raises
     268      :exc:`ValueError`.
     269
    199270   The complex type is described in :ref:`typesnumeric`.
    200271
     
    208279
    209280
    210 .. function:: dict([arg])
     281.. _func-dict:
     282.. function:: dict(**kwarg)
     283              dict(mapping, **kwarg)
     284              dict(iterable, **kwarg)
    211285   :noindex:
    212286
    213    Create a new data dictionary, optionally with items taken from *arg*.
    214    The dictionary type is described in :ref:`typesmapping`.
    215 
    216    For other containers see the built in :class:`list`, :class:`set`, and
    217    :class:`tuple` classes, and the :mod:`collections` module.
     287   Create a new dictionary.  The :class:`dict` object is the dictionary class.
     288   See :class:`dict` and :ref:`typesmapping` for documentation about this
     289   class.
     290
     291   For other containers see the built-in :class:`list`, :class:`set`, and
     292   :class:`tuple` classes, as well as the :mod:`collections` module.
    218293
    219294
     
    250325
    251326      >>> import struct
    252       >>> dir()   # doctest: +SKIP
     327      >>> dir()   # show the names in the module namespace
    253328      ['__builtins__', '__doc__', '__name__', 'struct']
    254       >>> dir(struct)   # doctest: +NORMALIZE_WHITESPACE
     329      >>> dir(struct)   # show the names in the struct module
    255330      ['Struct', '__builtins__', '__doc__', '__file__', '__name__',
    256331       '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
    257332       'unpack', 'unpack_from']
    258       >>> class Foo(object):
    259       ...     def __dir__(self):
    260       ...         return ["kan", "ga", "roo"]
    261       ...
    262       >>> f = Foo()
    263       >>> dir(f)
    264       ['ga', 'kan', 'roo']
     333      >>> class Shape(object):
     334              def __dir__(self):
     335                  return ['area', 'perimeter', 'location']
     336      >>> s = Shape()
     337      >>> dir(s)
     338      ['area', 'perimeter', 'location']
    265339
    266340   .. note::
     
    288362
    289363
    290 .. function:: enumerate(sequence[, start=0])
     364.. function:: enumerate(sequence, start=0)
    291365
    292366   Return an enumerate object. *sequence* must be a sequence, an
     
    294368   :meth:`!next` method of the iterator returned by :func:`enumerate` returns a
    295369   tuple containing a count (from *start* which defaults to 0) and the
    296    corresponding value obtained from iterating over *iterable*.
    297    :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``,
    298    ``(1, seq[1])``, ``(2, seq[2])``, .... For example:
    299 
    300       >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
    301       ...     print i, season
    302       0 Spring
    303       1 Summer
    304       2 Fall
    305       3 Winter
     370   values obtained from iterating over *sequence*::
     371
     372      >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
     373      >>> list(enumerate(seasons))
     374      [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
     375      >>> list(enumerate(seasons, start=1))
     376      [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
     377
     378   Equivalent to::
     379
     380      def enumerate(sequence, start=0):
     381          n = start
     382          for elem in sequence:
     383              yield n, elem
     384              n += 1
    306385
    307386   .. versionadded:: 2.3
    308    .. versionadded:: 2.6
    309       The *start* parameter.
     387   .. versionchanged:: 2.6
     388      The *start* parameter was added.
    310389
    311390
    312391.. function:: eval(expression[, globals[, locals]])
    313392
    314    The arguments are a string and optional globals and locals.  If provided,
    315    *globals* must be a dictionary.  If provided, *locals* can be any mapping
    316    object.
     393   The arguments are a Unicode or *Latin-1* encoded string and optional
     394   globals and locals.  If provided, *globals* must be a dictionary.
     395   If provided, *locals* can be any mapping object.
    317396
    318397   .. versionchanged:: 2.4
     
    337416   those created by :func:`compile`).  In this case pass a code object instead
    338417   of a string.  If the code object has been compiled with ``'exec'`` as the
    339    *kind* argument, :func:`eval`\'s return value will be ``None``.
     418   *mode* argument, :func:`eval`\'s return value will be ``None``.
    340419
    341420   Hints: dynamic execution of statements is supported by the :keyword:`exec`
     
    345424   useful to pass around for use by :func:`eval` or :func:`execfile`.
    346425
     426   See :func:`ast.literal_eval` for a function that can safely evaluate strings
     427   with expressions containing only literals.
     428
    347429
    348430.. function:: execfile(filename[, globals[, locals]])
     
    356438   and evaluated as a sequence of Python statements (similarly to a module) using
    357439   the *globals* and *locals* dictionaries as global and local namespace. If
    358    provided, *locals* can be any mapping object.
     440   provided, *locals* can be any mapping object.  Remember that at module level,
     441   globals and locals are the same dictionary. If two separate objects are
     442   passed as *globals* and *locals*, the code will be executed as if it were
     443   embedded in a class definition.
    359444
    360445   .. versionchanged:: 2.4
     
    374459
    375460
    376 .. function:: file(filename[, mode[, bufsize]])
     461.. function:: file(name[, mode[, buffering]])
    377462
    378463   Constructor function for the :class:`file` type, described further in section
     
    400485   in iterable if item]`` if function is ``None``.
    401486
    402    See :func:`itertools.filterfalse` for the complementary function that returns
    403    elements of *iterable* for which *function* returns false.
     487   See :func:`itertools.ifilter` and :func:`itertools.ifilterfalse` for iterator
     488   versions of this function, including a variation that filters for elements
     489   where the *function* returns false.
    404490
    405491
     
    448534
    449535
     536.. _func-frozenset:
    450537.. function:: frozenset([iterable])
    451538   :noindex:
    452539
    453    Return a frozenset object, optionally with elements taken from *iterable*.
    454    The frozenset type is described in :ref:`types-set`.
    455 
    456    For other containers see the built in :class:`dict`, :class:`list`, and
    457    :class:`tuple` classes, and the :mod:`collections` module.
     540   Return a new :class:`frozenset` object, optionally with elements taken from
     541   *iterable*.  ``frozenset`` is a built-in class.  See :class:`frozenset` and
     542   :ref:`types-set` for documentation about this class.
     543
     544   For other containers see the built-in :class:`set`, :class:`list`,
     545   :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections`
     546   module.
    458547
    459548   .. versionadded:: 2.4
     
    462551.. function:: getattr(object, name[, default])
    463552
    464    Return the value of the named attributed of *object*.  *name* must be a string.
     553   Return the value of the named attribute of *object*.  *name* must be a string.
    465554   If the string is the name of one of the object's attributes, the result is the
    466555   value of that attribute.  For example, ``getattr(x, 'foobar')`` is equivalent to
     
    527616   value.
    528617
    529    .. impl-detail:: This is the address of the object.
     618   .. impl-detail:: This is the address of the object in memory.
    530619
    531620
     
    534623   Equivalent to ``eval(raw_input(prompt))``.
    535624
    536    .. warning::
    537 
    538       This function is not safe from user errors!  It expects a valid Python
    539       expression as input; if the input is not syntactically valid, a
    540       :exc:`SyntaxError` will be raised. Other exceptions may be raised if there is an
    541       error during evaluation.  (On the other hand, sometimes this is exactly what you
    542       need when writing a quick script for expert use.)
     625   This function does not catch user errors. If the input is not syntactically
     626   valid, a :exc:`SyntaxError` will be raised. Other exceptions may be raised if
     627   there is an error during evaluation.
    543628
    544629   If the :mod:`readline` module was loaded, then :func:`input` will use it to
     
    548633
    549634
    550 .. function:: int([x[, base]])
    551 
    552    Convert a string or number to a plain integer.  If the argument is a string,
    553    it must contain a possibly signed decimal number representable as a Python
    554    integer, possibly embedded in whitespace.  The *base* parameter gives the
    555    base for the conversion (which is 10 by default) and may be any integer in
    556    the range [2, 36], or zero.  If *base* is zero, the proper radix is
    557    determined based on the contents of string; the interpretation is the same as
    558    for integer literals.  (See :ref:`numbers`.)  If *base* is specified and *x*
    559    is not a string, :exc:`TypeError` is raised. Otherwise, the argument may be a
    560    plain or long integer or a floating point number.  Conversion of floating
    561    point numbers to integers truncates (towards zero).  If the argument is
    562    outside the integer range a long object will be returned instead.  If no
    563    arguments are given, returns ``0``.
     635.. function:: int(x=0)
     636              int(x, base=10)
     637
     638   Convert a number or string *x* to an integer, or return ``0`` if no
     639   arguments are given.  If *x* is a number, it can be a plain integer, a long
     640   integer, or a floating point number.  If *x* is floating point, the conversion
     641   truncates towards zero.  If the argument is outside the integer range, the
     642   function returns a long object instead.
     643
     644   If *x* is not a number or if *base* is given, then *x* must be a string or
     645   Unicode object representing an :ref:`integer literal <integers>` in radix
     646   *base*.  Optionally, the literal can be
     647   preceded by ``+`` or ``-`` (with no space in between) and surrounded by
     648   whitespace.  A base-n literal consists of the digits 0 to n-1, with ``a``
     649   to ``z`` (or ``A`` to ``Z``) having
     650   values 10 to 35.  The default *base* is 10. The allowed values are 0 and 2-36.
     651   Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``,
     652   ``0o``/``0O``/``0``, or ``0x``/``0X``, as with integer literals in code.
     653   Base 0 means to interpret the string exactly as an integer literal, so that
     654   the actual base is 2, 8, 10, or 16.
    564655
    565656   The integer type is described in :ref:`typesnumeric`.
     
    569660
    570661   Return true if the *object* argument is an instance of the *classinfo* argument,
    571    or of a (direct or indirect) subclass thereof.  Also return true if *classinfo*
     662   or of a (direct, indirect or :term:`virtual <abstract base class>`) subclass
     663   thereof.  Also return true if *classinfo*
    572664   is a type object (new-style class) and *object* is an object of that type or of
    573    a (direct or indirect) subclass thereof.  If *object* is not a class instance or
     665   a (direct, indirect or :term:`virtual <abstract base class>`) subclass
     666   thereof.  If *object* is not a class instance or
    574667   an object of the given type, the function always returns false.  If *classinfo*
    575668   is neither a class object nor a type object, it may be a tuple of class or type
     
    584677.. function:: issubclass(class, classinfo)
    585678
    586    Return true if *class* is a subclass (direct or indirect) of *classinfo*.  A
     679   Return true if *class* is a subclass (direct, indirect or :term:`virtual
     680   <abstract base class>`) of *classinfo*.  A
    587681   class is considered a subclass of itself. *classinfo* may be a tuple of class
    588682   objects, in which case every entry in *classinfo* will be checked. In any other
     
    608702   One useful application of the second form of :func:`iter` is to read lines of
    609703   a file until a certain line is reached.  The following example reads a file
    610    until ``"STOP"`` is reached: ::
    611 
    612       with open("mydata.txt") as fp:
    613           for line in iter(fp.readline, "STOP"):
     704   until the :meth:`~io.TextIOBase.readline` method returns an empty string::
     705
     706      with open('mydata.txt') as fp:
     707          for line in iter(fp.readline, ''):
    614708              process_line(line)
    615709
     
    649743
    650744
    651 .. function:: long([x[, base]])
     745.. function:: long(x=0)
     746              long(x, base=10)
    652747
    653748   Convert a string or number to a long integer.  If the argument is a string, it
     
    675770
    676771
    677 .. function:: max(iterable[, args...][key])
    678 
    679    With a single argument *iterable*, return the largest item of a non-empty
    680    iterable (such as a string, tuple or list).  With more than one argument, return
    681    the largest of the arguments.
     772.. function:: max(iterable[, key])
     773              max(arg1, arg2, *args[, key])
     774
     775   Return the largest item in an iterable or the largest of two or more
     776   arguments.
     777
     778   If one positional argument is provided, *iterable* must be a non-empty
     779   iterable (such as a non-empty string, tuple or list).  The largest item
     780   in the iterable is returned.  If two or more positional arguments are
     781   provided, the largest of the positional arguments is returned.
    682782
    683783   The optional *key* argument specifies a one-argument ordering function like that
     
    688788      Added support for the optional *key* argument.
    689789
    690 
    691 .. function:: min(iterable[, args...][key])
    692 
    693    With a single argument *iterable*, return the smallest item of a non-empty
    694    iterable (such as a string, tuple or list).  With more than one argument, return
    695    the smallest of the arguments.
     790.. _func-memoryview:
     791.. function:: memoryview(obj)
     792   :noindex:
     793
     794   Return a "memory view" object created from the given argument.  See
     795   :ref:`typememoryview` for more information.
     796
     797
     798.. function:: min(iterable[, key])
     799              min(arg1, arg2, *args[, key])
     800
     801   Return the smallest item in an iterable or the smallest of two or more
     802   arguments.
     803
     804   If one positional argument is provided, *iterable* must be a non-empty
     805   iterable (such as a non-empty string, tuple or list).  The smallest item
     806   in the iterable is returned.  If two or more positional arguments are
     807   provided, the smallest of the positional arguments is returned.
    696808
    697809   The optional *key* argument specifies a one-argument ordering function like that
     
    734846
    735847
    736 .. function:: open(filename[, mode[, bufsize]])
     848.. function:: open(name[, mode[, buffering]])
    737849
    738850   Open a file, returning an object of the :class:`file` type described in
     
    741853   :func:`open` instead of invoking the :class:`file` constructor directly.
    742854
    743    The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`:
    744    *filename* is the file name to be opened, and *mode* is a string indicating how
     855   The first two arguments are the same as for ``stdio``'s :c:func:`fopen`:
     856   *name* is the file name to be opened, and *mode* is a string indicating how
    745857   the file is to be opened.
    746858
     
    763875      single: I/O control; buffering
    764876
    765    The optional *bufsize* argument specifies the file's desired buffer size: 0
     877   The optional *buffering* argument specifies the file's desired buffer size: 0
    766878   means unbuffered, 1 means line buffered, any other positive value means use a
    767    buffer of (approximately) that size.  A negative *bufsize* means to use the
    768    system default, which is usually line buffered for tty devices and fully
    769    buffered for other files.  If omitted, the system default is used. [#]_
     879   buffer of (approximately) that size (in bytes).  A negative *buffering* means
     880   to use the system default, which is usually line buffered for tty devices and
     881   fully buffered for other files.  If omitted, the system default is used. [#]_
    770882
    771883   Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note that
     
    774886   systems that don't have this distinction, adding the ``'b'`` has no effect.
    775887
    776    In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or
    777    ``'rU'``.  Python is usually built with universal newline support; supplying
    778    ``'U'`` opens the file as a text file, but lines may be terminated by any of the
    779    following: the Unix end-of-line convention ``'\n'``,  the Macintosh convention
    780    ``'\r'``, or the Windows convention ``'\r\n'``. All of these external
    781    representations are seen as ``'\n'`` by the Python program. If Python is built
    782    without universal newline support a *mode* with ``'U'`` is the same as normal
    783    text mode.  Note that file objects so opened also have an attribute called
    784    :attr:`newlines` which has a value of ``None`` (if no newlines have yet been
    785    seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple containing all the newline
    786    types seen.
     888   .. index::
     889      single: universal newlines; open() built-in function
     890
     891   In addition to the standard :c:func:`fopen` values *mode* may be ``'U'`` or
     892   ``'rU'``.  Python is usually built with :term:`universal newlines` support;
     893   supplying ``'U'`` opens the file as a text file, but lines may be terminated
     894   by any of the following: the Unix end-of-line convention ``'\n'``,  the
     895   Macintosh convention ``'\r'``, or the Windows convention ``'\r\n'``. All of
     896   these external representations are seen as ``'\n'`` by the Python program.
     897   If Python is built without universal newlines support a *mode* with ``'U'``
     898   is the same as normal text mode.  Note that file objects so opened also have
     899   an attribute called :attr:`newlines` which has a value of ``None`` (if no
     900   newlines have yet been seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple
     901   containing all the newline types seen.
    787902
    788903   Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``,
     
    830945
    831946
    832 .. function:: print([object, ...][, sep=' '][, end='\\n'][, file=sys.stdout])
    833 
    834    Print *object*\(s) to the stream *file*, separated by *sep* and followed by
     947.. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout)
     948
     949   Print *objects* to the stream *file*, separated by *sep* and followed by
    835950   *end*.  *sep*, *end* and *file*, if present, must be given as keyword
    836951   arguments.
     
    839954   written to the stream, separated by *sep* and followed by *end*.  Both *sep*
    840955   and *end* must be strings; they can also be ``None``, which means to use the
    841    default values.  If no *object* is given, :func:`print` will just write
     956   default values.  If no *objects* are given, :func:`print` will just write
    842957   *end*.
    843958
    844959   The *file* argument must be an object with a ``write(string)`` method; if it
    845    is not present or ``None``, :data:`sys.stdout` will be used.
     960   is not present or ``None``, :data:`sys.stdout` will be used.  Output buffering
     961   is determined by *file*.  Use ``file.flush()`` to ensure, for instance,
     962   immediate appearance on a screen.
    846963
    847964   .. note::
     
    864981   *fget* is a function for getting an attribute value, likewise *fset* is a
    865982   function for setting, and *fdel* a function for del'ing, an attribute.  Typical
    866    use is to define a managed attribute x::
     983   use is to define a managed attribute ``x``::
    867984
    868985      class C(object):
     
    878995          x = property(getx, setx, delx, "I'm the 'x' property.")
    879996
     997   If then *c* is an instance of *C*, ``c.x`` will invoke the getter,
     998   ``c.x = value`` will invoke the setter and ``del c.x`` the deleter.
     999
    8801000   If given, *doc* will be the docstring of the property attribute. Otherwise, the
    8811001   property will copy *fget*'s docstring (if it exists).  This makes it possible to
     
    8941014   with the same name.
    8951015
    896    A property object has :attr:`getter`, :attr:`setter`, and :attr:`deleter`
    897    methods usable as decorators that create a copy of the property with the
    898    corresponding accessor function set to the decorated function.  This is
    899    best explained with an example::
     1016   A property object has :attr:`~property.getter`, :attr:`~property.setter`,
     1017   and :attr:`~property.deleter` methods usable as decorators that create a
     1018   copy of the property with the corresponding accessor function set to the
     1019   decorated function.  This is best explained with an example::
    9001020
    9011021      class C(object):
     
    9321052
    9331053
    934 .. function:: range([start,] stop[, step])
     1054.. function:: range(stop)
     1055              range(start, stop[, step])
    9351056
    9361057   This is a versatile function to create lists containing arithmetic progressions.
     
    9861107   a default when the iterable is empty.  If *initializer* is not given and
    9871108   *iterable* contains only one item, the first item is returned.
    988 
     1109   Roughly equivalent to::
     1110
     1111      def reduce(function, iterable, initializer=None):
     1112          it = iter(iterable)
     1113          if initializer is None:
     1114              try:
     1115                  initializer = next(it)
     1116              except StopIteration:
     1117                  raise TypeError('reduce() of empty sequence with no initial value')
     1118          accum_value = initializer
     1119          for x in it:
     1120              accum_value = function(accum_value, x)
     1121          return accum_value
    9891122
    9901123.. function:: reload(module)
     
    10501183
    10511184
     1185.. _func-repr:
    10521186.. function:: repr(object)
    10531187
     
    10761210
    10771211
    1078 .. function:: round(x[, n])
    1079 
    1080    Return the floating point value *x* rounded to *n* digits after the decimal
    1081    point.  If *n* is omitted, it defaults to zero. The result is a floating point
    1082    number.  Values are rounded to the closest multiple of 10 to the power minus
    1083    *n*; if two multiples are equally close, rounding is done away from 0 (so. for
    1084    example, ``round(0.5)`` is ``1.0`` and ``round(-0.5)`` is ``-1.0``).
    1085 
    1086 
     1212.. function:: round(number[, ndigits])
     1213
     1214   Return the floating point value *number* rounded to *ndigits* digits after
     1215   the decimal point.  If *ndigits* is omitted, it defaults to zero. The result
     1216   is a floating point number.  Values are rounded to the closest multiple of
     1217   10 to the power minus *ndigits*; if two multiples are equally close,
     1218   rounding is done away from 0 (so. for example, ``round(0.5)`` is ``1.0`` and
     1219   ``round(-0.5)`` is ``-1.0``).
     1220
     1221
     1222   .. note::
     1223
     1224      The behavior of :func:`round` for floats can be surprising: for example,
     1225      ``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``.
     1226      This is not a bug: it's a result of the fact that most decimal fractions
     1227      can't be represented exactly as a float.  See :ref:`tut-fp-issues` for
     1228      more information.
     1229
     1230
     1231.. _func-set:
    10871232.. function:: set([iterable])
    10881233   :noindex:
    10891234
    1090    Return a new set, optionally with elements are taken from *iterable*.
    1091    The set type is described in :ref:`types-set`.
    1092 
    1093    For other containers see the built in :class:`dict`, :class:`list`, and
    1094    :class:`tuple` classes, and the :mod:`collections` module.
     1235   Return a new :class:`set` object, optionally with elements taken from
     1236   *iterable*.  ``set`` is a built-in class.  See :class:`set` and
     1237   :ref:`types-set` for documentation about this class.
     1238
     1239   For other containers see the built-in :class:`frozenset`, :class:`list`,
     1240   :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections`
     1241   module.
    10951242
    10961243   .. versionadded:: 2.4
     
    11061253
    11071254
    1108 .. function:: slice([start,] stop[, step])
     1255.. function:: slice(stop)
     1256              slice(start, stop[, step])
    11091257
    11101258   .. index:: single: Numerical Python
     
    11121260   Return a :term:`slice` object representing the set of indices specified by
    11131261   ``range(start, stop, step)``.  The *start* and *step* arguments default to
    1114    ``None``.  Slice objects have read-only data attributes :attr:`start`,
    1115    :attr:`stop` and :attr:`step` which merely return the argument values (or their
    1116    default).  They have no other explicit functionality; however they are used by
    1117    Numerical Python and other third party extensions.  Slice objects are also
    1118    generated when extended indexing syntax is used.  For example:
    1119    ``a[start:stop:step]`` or ``a[start:stop, i]``.  See :func:`itertools.islice`
    1120    for an alternate version that returns an iterator.
     1262   ``None``.  Slice objects have read-only data attributes :attr:`~slice.start`,
     1263   :attr:`~slice.stop` and :attr:`~slice.step` which merely return the argument
     1264   values (or their default).  They have no other explicit functionality;
     1265   however they are used by Numerical Python and other third party extensions.
     1266   Slice objects are also generated when extended indexing syntax is used.  For
     1267   example: ``a[start:stop:step]`` or ``a[start:stop, i]``.  See
     1268   :func:`itertools.islice` for an alternate version that returns an iterator.
    11211269
    11221270
     
    11361284
    11371285   *key* specifies a function of one argument that is used to extract a comparison
    1138    key from each list element: ``key=str.lower``.  The default value is ``None``.
     1286   key from each list element: ``key=str.lower``.  The default value is ``None``
     1287   (compare the elements directly).
    11391288
    11401289   *reverse* is a boolean value.  If set to ``True``, then the list elements are
     
    11441293   than specifying an equivalent *cmp* function.  This is because *cmp* is
    11451294   called multiple times for each list element while *key* and *reverse* touch
    1146    each element only once.  To convert an old-style *cmp* function to a *key*
    1147    function, see the `CmpToKey recipe in the ASPN cookbook
    1148    <http://code.activestate.com/recipes/576653/>`_\.
     1295   each element only once.  Use :func:`functools.cmp_to_key` to convert an
     1296   old-style *cmp* function to a *key* function.
     1297
     1298   For sorting examples and a brief sorting tutorial, see `Sorting HowTo
     1299   <http://wiki.python.org/moin/HowTo/Sorting/>`_\.
    11491300
    11501301   .. versionadded:: 2.4
     
    11581309   method, use this idiom::
    11591310
    1160       class C:
     1311      class C(object):
    11611312          @staticmethod
    1162           def f(arg1, arg2, ...): ...
     1313          def f(arg1, arg2, ...):
     1314              ...
    11631315
    11641316   The ``@staticmethod`` form is a function :term:`decorator` -- see the
     
    11681320   as ``C().f()``).  The instance is ignored except for its class.
    11691321
    1170    Static methods in Python are similar to those found in Java or C++. For a more
    1171    advanced concept, see :func:`classmethod` in this section.
     1322   Static methods in Python are similar to those found in Java or C++. Also see
     1323   :func:`classmethod` for a variant that is useful for creating alternate
     1324   class constructors.
    11721325
    11731326   For more information on static methods, consult the documentation on the
     
    11801333
    11811334
    1182 .. function:: str([object])
     1335.. function:: str(object='')
    11831336
    11841337   Return a string containing a nicely printable representation of an object.  For
     
    12001353   Sums *start* and the items of an *iterable* from left to right and returns the
    12011354   total.  *start* defaults to ``0``. The *iterable*'s items are normally numbers,
    1202    and are not allowed to be strings.  The fast, correct way to concatenate a
    1203    sequence of strings is by calling ``''.join(sequence)``. Note that
    1204    ``sum(range(n), m)`` is equivalent to ``reduce(operator.add, range(n), m)``
    1205    To add floating point values with extended precision, see :func:`math.fsum`\.
     1355   and the start value is not allowed to be a string.
     1356
     1357   For some use cases, there are good alternatives to :func:`sum`.
     1358   The preferred, fast way to concatenate a sequence of strings is by calling
     1359   ``''.join(sequence)``.  To add floating point values with extended precision,
     1360   see :func:`math.fsum`\.  To concatenate a series of iterables, consider using
     1361   :func:`itertools.chain`.
    12061362
    12071363   .. versionadded:: 2.3
     
    12151371   :func:`getattr` except that the *type* itself is skipped.
    12161372
    1217    The :attr:`__mro__` attribute of the *type* lists the method resolution
    1218    search order used by both :func:`getattr` and :func:`super`.  The attribute
    1219    is dynamic and can change whenever the inheritance hierarchy is updated.
     1373   The :attr:`~class.__mro__` attribute of the *type* lists the method
     1374   resolution search order used by both :func:`getattr` and :func:`super`.  The
     1375   attribute is dynamic and can change whenever the inheritance hierarchy is
     1376   updated.
    12201377
    12211378   If the second argument is omitted, the super object returned is unbound.  If
     
    12591416   references.
    12601417
     1418   For practical suggestions on how to design cooperative classes using
     1419   :func:`super`, see `guide to using super()
     1420   <http://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_.
     1421
    12611422   .. versionadded:: 2.2
    12621423
     
    12771438
    12781439.. function:: type(object)
     1440              type(name, bases, dict)
    12791441
    12801442   .. index:: object: type
    12811443
    1282    Return the type of an *object*.  The return value is a type object.  The
    1283    :func:`isinstance` built-in function is recommended for testing the type of an
    1284    object.
    1285 
    1286    With three arguments, :func:`type` functions as a constructor as detailed below.
    1287 
    1288 
    1289 .. function:: type(name, bases, dict)
    1290    :noindex:
    1291 
    1292    Return a new type object.  This is essentially a dynamic form of the
    1293    :keyword:`class` statement. The *name* string is the class name and becomes the
    1294    :attr:`__name__` attribute; the *bases* tuple itemizes the base classes and
    1295    becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the
    1296    namespace containing definitions for class body and becomes the :attr:`__dict__`
    1297    attribute.  For example, the following two statements create identical
    1298    :class:`type` objects:
     1444   With one argument, return the type of an *object*.  The return value is a
     1445   type object.  The :func:`isinstance` built-in function is recommended for
     1446   testing the type of an object.
     1447
     1448   With three arguments, return a new type object.  This is essentially a
     1449   dynamic form of the :keyword:`class` statement. The *name* string is the
     1450   class name and becomes the :attr:`~class.__name__` attribute; the *bases* tuple
     1451   itemizes the base classes and becomes the :attr:`~class.__bases__` attribute;
     1452   and the *dict* dictionary is the namespace containing definitions for class
     1453   body and becomes the :attr:`~object.__dict__`  attribute.  For example, the
     1454   following two statements create identical :class:`type` objects:
    12991455
    13001456      >>> class X(object):
     
    13181474
    13191475
    1320 .. function:: unicode([object[, encoding [, errors]]])
     1476.. function:: unicode(object='')
     1477              unicode(object[, encoding [, errors]])
    13211478
    13221479   Return the Unicode string version of *object* using one of the following modes:
     
    13581515.. function:: vars([object])
    13591516
    1360    Without an argument, act like :func:`locals`.
    1361 
    1362    With a module, class or class instance object as argument (or anything else that
    1363    has a :attr:`__dict__` attribute), return that attribute.
    1364 
    1365    .. note::
    1366 
    1367       The returned dictionary should not be modified:
    1368       the effects on the corresponding symbol table are undefined. [#]_
    1369 
    1370 
    1371 .. function:: xrange([start,] stop[, step])
    1372 
    1373    This function is very similar to :func:`range`, but returns an "xrange object"
     1517   Return the :attr:`~object.__dict__` attribute for a module, class, instance,
     1518   or any other object with a :attr:`__dict__` attribute.
     1519
     1520   Objects such as modules and instances have an updateable :attr:`__dict__`
     1521   attribute; however, other objects may have write restrictions on their
     1522   :attr:`__dict__` attributes (for example, new-style classes use a
     1523   dictproxy to prevent direct dictionary updates).
     1524
     1525   Without an argument, :func:`vars` acts like :func:`locals`.  Note, the
     1526   locals dictionary is only useful for reads since updates to the locals
     1527   dictionary are ignored.
     1528
     1529
     1530.. function:: xrange(stop)
     1531              xrange(start, stop[, step])
     1532
     1533   This function is very similar to :func:`range`, but returns an :ref:`xrange
     1534   object <typesseq-xrange>`
    13741535   instead of a list.  This is an opaque sequence type which yields the same values
    13751536   as the corresponding list, without actually storing them all simultaneously.
     
    13781539   very large range is used on a memory-starved machine or when all of the range's
    13791540   elements are never used (such as when the loop is usually terminated with
    1380    :keyword:`break`).
     1541   :keyword:`break`).  For more information on xrange objects, see
     1542   :ref:`typesseq-xrange` and :ref:`typesseq`.
    13811543
    13821544   .. impl-detail::
     
    13881550      larger range is needed, an alternate version can be crafted using the
    13891551      :mod:`itertools` module: ``islice(count(start, step),
    1390       (stop-start+step-1)//step)``.
     1552      (stop-start+step-1+2*(step<0))//step)``.
    13911553
    13921554
     
    14331595
    14341596      This is an advanced function that is not needed in everyday Python
    1435       programming.
     1597      programming, unlike :func:`importlib.import_module`.
    14361598
    14371599   This function is invoked by the :keyword:`import` statement.  It can be
    1438    replaced (by importing the :mod:`builtins` module and assigning to
    1439    ``builtins.__import__``) in order to change semantics of the
     1600   replaced (by importing the :mod:`__builtin__` module and assigning to
     1601   ``__builtin__.__import__``) in order to change semantics of the
    14401602   :keyword:`import` statement, but nowadays it is usually simpler to use import
    14411603   hooks (see :pep:`302`).  Direct use of :func:`__import__` is rare, except in
     
    14841646
    14851647   If you simply want to import a module (potentially within a package) by name,
    1486    you can call :func:`__import__` and then look it up in :data:`sys.modules`::
    1487 
    1488       >>> import sys
    1489       >>> name = 'foo.bar.baz'
    1490       >>> __import__(name)
    1491       <module 'foo' from ...>
    1492       >>> baz = sys.modules[name]
    1493       >>> baz
    1494       <module 'foo.bar.baz' from ...>
     1648   use :func:`importlib.import_module`.
     1649
    14951650
    14961651   .. versionchanged:: 2.5
     
    15291684
    15301685   .. deprecated:: 2.3
    1531       Use the extended call syntax with ``*args`` and ``**keywords`` instead.
     1686      Use ``function(*args, **keywords)`` instead of
     1687      ``apply(function, args, keywords)`` (see :ref:`tut-unpacking-arguments`).
    15321688
    15331689
     
    15691725
    15701726.. [#] Specifying a buffer size currently has no effect on systems that don't have
    1571    :cfunc:`setvbuf`.  The interface to specify the buffer size is not done using a
    1572    method that calls :cfunc:`setvbuf`, because that may dump core when called after
     1727   :c:func:`setvbuf`.  The interface to specify the buffer size is not done using a
     1728   method that calls :c:func:`setvbuf`, because that may dump core when called after
    15731729   any I/O has been performed, and there's no reliable way to determine whether
    15741730   this is the case.
Note: See TracChangeset for help on using the changeset viewer.