1 .. XXX: reference/datamodel and this have quite a few overlaps!
10 The following sections describe the standard types that are built into the
15 Historically (until release 2.2), Python's built-in types have differed from
16 user-defined types because it was not possible to use the built-in types as the
17 basis for object-oriented inheritance. This limitation no longer
20 .. index:: pair: built-in; types
22 The principal built-in types are numerics, sequences, mappings, files, classes,
23 instances and exceptions.
25 .. index:: statement: print
27 Some operations are supported by several object types; in particular,
28 practically all objects can be compared, tested for truth value, and converted
29 to a string (with the :func:`repr` function or the slightly different
30 :func:`str` function). The latter function is implicitly used when an object is
31 written by the :func:`print` function.
43 pair: Boolean; operations
46 Any object can be tested for truth value, for use in an :keyword:`if` or
47 :keyword:`while` condition or as operand of the Boolean operations below. The
48 following values are considered false:
50 .. index:: single: None (Built-in object)
54 .. index:: single: False (Built-in object)
58 * zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.
60 * any empty sequence, for example, ``''``, ``()``, ``[]``.
62 * any empty mapping, for example, ``{}``.
64 * instances of user-defined classes, if the class defines a :meth:`__nonzero__`
65 or :meth:`__len__` method, when that method returns the integer zero or
66 :class:`bool` value ``False``. [#]_
68 .. index:: single: true
70 All other values are considered true --- so objects of many types are always
79 Operations and built-in functions that have a Boolean result always return ``0``
80 or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
81 (Important exception: the Boolean operations ``or`` and ``and`` always return
82 one of their operands.)
87 Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
88 ====================================================================
90 .. index:: pair: Boolean; operations
92 These are the Boolean operations, ordered by ascending priority:
94 +-------------+---------------------------------+-------+
95 | Operation | Result | Notes |
96 +=============+=================================+=======+
97 | ``x or y`` | if *x* is false, then *y*, else | \(1) |
99 +-------------+---------------------------------+-------+
100 | ``x and y`` | if *x* is false, then *x*, else | \(2) |
102 +-------------+---------------------------------+-------+
103 | ``not x`` | if *x* is false, then ``True``, | \(3) |
104 | | else ``False`` | |
105 +-------------+---------------------------------+-------+
115 This is a short-circuit operator, so it only evaluates the second
116 argument if the first one is :const:`False`.
119 This is a short-circuit operator, so it only evaluates the second
120 argument if the first one is :const:`True`.
123 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
124 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
132 .. index:: pair: chaining; comparisons
134 Comparison operations are supported by all objects. They all have the same
135 priority (which is higher than that of the Boolean operations). Comparisons can
136 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
137 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
138 evaluated at all when ``x < y`` is found to be false).
140 This table summarizes the comparison operations:
142 +------------+-------------------------+-------+
143 | Operation | Meaning | Notes |
144 +============+=========================+=======+
145 | ``<`` | strictly less than | |
146 +------------+-------------------------+-------+
147 | ``<=`` | less than or equal | |
148 +------------+-------------------------+-------+
149 | ``>`` | strictly greater than | |
150 +------------+-------------------------+-------+
151 | ``>=`` | greater than or equal | |
152 +------------+-------------------------+-------+
154 +------------+-------------------------+-------+
155 | ``!=`` | not equal | \(1) |
156 +------------+-------------------------+-------+
157 | ``is`` | object identity | |
158 +------------+-------------------------+-------+
159 | ``is not`` | negated object identity | |
160 +------------+-------------------------+-------+
163 pair: operator; comparison
176 ``!=`` can also be written ``<>``, but this is an obsolete usage
177 kept for backwards compatibility only. New code should always use
181 pair: object; numeric
182 pair: objects; comparing
184 Objects of different types, except different numeric types and different string
185 types, never compare equal; such objects are ordered consistently but
186 arbitrarily (so that sorting a heterogeneous array yields a consistent result).
187 Furthermore, some types (for example, file objects) support only a degenerate
188 notion of comparison where any two objects of that type are unequal. Again,
189 such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
190 and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
193 .. index:: single: __cmp__() (instance method)
195 Instances of a class normally compare as non-equal unless the class defines the
196 :meth:`__cmp__` method. Refer to :ref:`customization`) for information on the
197 use of this method to effect object comparisons.
199 **Implementation note:** Objects of different types except numbers are ordered
200 by their type names; objects of the same types that don't support proper
201 comparison are ordered by their address.
207 Two more operations with the same syntactic priority, ``in`` and ``not in``, are
208 supported only by sequence types (below).
213 Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
214 ===============================================================================
221 object: floating point
222 object: complex number
225 There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
226 integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
227 addition, Booleans are a subtype of plain integers. Plain integers (also just
228 called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives
229 them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
230 plain integer value for the current platform, the minimum value is
231 ``-sys.maxint - 1``). Long integers have unlimited precision. Floating point
232 numbers are implemented using :ctype:`double` in C. All bets on their precision
233 are off unless you happen to know the machine you are working with.
235 Complex numbers have a real and imaginary part, which are each implemented using
236 :ctype:`double` in C. To extract these parts from a complex number *z*, use
237 ``z.real`` and ``z.imag``.
240 pair: numeric; literals
241 pair: integer; literals
242 triple: long; integer; literals
243 pair: floating point; literals
244 pair: complex number; literals
245 pair: hexadecimal; literals
246 pair: octal; literals
248 Numbers are created by numeric literals or as the result of built-in functions
249 and operators. Unadorned integer literals (including hex and octal numbers)
250 yield plain integers unless the value they denote is too large to be represented
251 as a plain integer, in which case they yield a long integer. Integer literals
252 with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` is preferred
253 because ``1l`` looks too much like eleven!). Numeric literals containing a
254 decimal point or an exponent sign yield floating point numbers. Appending
255 ``'j'`` or ``'J'`` to a numeric literal yields a complex number with a zero real
256 part. A complex numeric literal is the sum of a real and an imaginary part.
265 Python fully supports mixed arithmetic: when a binary arithmetic operator has
266 operands of different numeric types, the operand with the "narrower" type is
267 widened to that of the other, where plain integer is narrower than long integer
268 is narrower than floating point is narrower than complex. Comparisons between
269 numbers of mixed type use the same rule. [#]_ The constructors :func:`int`,
270 :func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
273 All builtin numeric types support the following operations. See
274 :ref:`power` and later sections for the operators' priorities.
276 +--------------------+---------------------------------+--------+
277 | Operation | Result | Notes |
278 +====================+=================================+========+
279 | ``x + y`` | sum of *x* and *y* | |
280 +--------------------+---------------------------------+--------+
281 | ``x - y`` | difference of *x* and *y* | |
282 +--------------------+---------------------------------+--------+
283 | ``x * y`` | product of *x* and *y* | |
284 +--------------------+---------------------------------+--------+
285 | ``x / y`` | quotient of *x* and *y* | \(1) |
286 +--------------------+---------------------------------+--------+
287 | ``x // y`` | (floored) quotient of *x* and | (4)(5) |
289 +--------------------+---------------------------------+--------+
290 | ``x % y`` | remainder of ``x / y`` | \(4) |
291 +--------------------+---------------------------------+--------+
292 | ``-x`` | *x* negated | |
293 +--------------------+---------------------------------+--------+
294 | ``+x`` | *x* unchanged | |
295 +--------------------+---------------------------------+--------+
296 | ``abs(x)`` | absolute value or magnitude of | \(3) |
298 +--------------------+---------------------------------+--------+
299 | ``int(x)`` | *x* converted to integer | \(2) |
300 +--------------------+---------------------------------+--------+
301 | ``long(x)`` | *x* converted to long integer | \(2) |
302 +--------------------+---------------------------------+--------+
303 | ``float(x)`` | *x* converted to floating point | \(6) |
304 +--------------------+---------------------------------+--------+
305 | ``complex(re,im)`` | a complex number with real part | |
306 | | *re*, imaginary part *im*. | |
307 | | *im* defaults to zero. | |
308 +--------------------+---------------------------------+--------+
309 | ``c.conjugate()`` | conjugate of the complex number | |
310 | | *c*. (Identity on real numbers) | |
311 +--------------------+---------------------------------+--------+
312 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) |
313 +--------------------+---------------------------------+--------+
314 | ``pow(x, y)`` | *x* to the power *y* | (3)(7) |
315 +--------------------+---------------------------------+--------+
316 | ``x ** y`` | *x* to the power *y* | \(7) |
317 +--------------------+---------------------------------+--------+
320 triple: operations on; numeric; types
321 single: conjugate() (complex number method)
327 pair: integer; division
328 triple: long; integer; division
330 For (plain or long) integer division, the result is an integer. The result is
331 always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
332 (-1)/(-2) is 0. Note that the result is a long integer if either operand is a
333 long integer, regardless of the numeric value.
338 single: floor() (in module math)
339 single: ceil() (in module math)
340 pair: numeric; conversions
343 Conversion from floating point to (long or plain) integer may round or
344 truncate as in C; see functions :func:`math.floor` and :func:`math.ceil` for
345 well-defined conversions.
348 Instead, convert floats to long explicitly with :func:`trunc`.
351 See :ref:`built-in-funcs` for a full description.
354 Complex floor division operator, modulo operator, and :func:`divmod`.
357 Instead convert to float using :func:`abs` if appropriate.
360 Also referred to as integer division. The resultant value is a whole integer,
361 though the result's type is not necessarily int.
364 float also accepts the strings "nan" and "inf" with an optional prefix "+"
365 or "-" for Not a Number (NaN) and positive or negative infinity.
367 .. versionadded:: 2.6
370 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
371 programming languages.
373 All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
374 :class:`float`) also include the following operations:
376 +--------------------+------------------------------------+--------+
377 | Operation | Result | Notes |
378 +====================+====================================+========+
379 | ``trunc(x)`` | *x* truncated to Integral | |
380 +--------------------+------------------------------------+--------+
381 | ``round(x[, n])`` | *x* rounded to n digits, | |
382 | | rounding half to even. If n is | |
383 | | omitted, it defaults to 0. | |
384 +--------------------+------------------------------------+--------+
385 | ``math.floor(x)`` | the greatest integral float <= *x* | |
386 +--------------------+------------------------------------+--------+
387 | ``math.ceil(x)`` | the least integral float >= *x* | |
388 +--------------------+------------------------------------+--------+
390 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
395 Bit-string Operations on Integer Types
396 --------------------------------------
398 .. _bit-string-operations:
400 Plain and long integer types support additional operations that make sense only
401 for bit-strings. Negative numbers are treated as their 2's complement value
402 (for long integers, this assumes a sufficiently large number of bits that no
403 overflow occurs during the operation).
405 The priorities of the binary bitwise operations are all lower than the numeric
406 operations and higher than the comparisons; the unary operation ``~`` has the
407 same priority as the other unary numeric operations (``+`` and ``-``).
409 This table lists the bit-string operations sorted in ascending priority:
411 +------------+--------------------------------+----------+
412 | Operation | Result | Notes |
413 +============+================================+==========+
414 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
416 +------------+--------------------------------+----------+
417 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
419 +------------+--------------------------------+----------+
420 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
422 +------------+--------------------------------+----------+
423 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
424 +------------+--------------------------------+----------+
425 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
426 +------------+--------------------------------+----------+
427 | ``~x`` | the bits of *x* inverted | |
428 +------------+--------------------------------+----------+
431 triple: operations on; integer; types
432 pair: bit-string; operations
433 pair: shifting; operations
434 pair: masking; operations
439 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
442 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. A
443 long integer is returned if the result exceeds the range of plain integers.
446 A right shift by *n* bits is equivalent to division by ``pow(2, n)``.
454 .. versionadded:: 2.2
457 single: iterator protocol
458 single: protocol; iterator
459 single: sequence; iteration
460 single: container; iteration over
462 Python supports a concept of iteration over containers. This is implemented
463 using two distinct methods; these are used to allow user-defined classes to
464 support iteration. Sequences, described below in more detail, always support
465 the iteration methods.
467 One method needs to be defined for container objects to provide iteration
470 .. XXX duplicated in reference/datamodel!
472 .. method:: container.__iter__()
474 Return an iterator object. The object is required to support the iterator
475 protocol described below. If a container supports different types of
476 iteration, additional methods can be provided to specifically request
477 iterators for those iteration types. (An example of an object supporting
478 multiple forms of iteration would be a tree structure which supports both
479 breadth-first and depth-first traversal.) This method corresponds to the
480 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
483 The iterator objects themselves are required to support the following two
484 methods, which together form the :dfn:`iterator protocol`:
487 .. method:: iterator.__iter__()
489 Return the iterator object itself. This is required to allow both containers
490 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
491 This method corresponds to the :attr:`tp_iter` slot of the type structure for
492 Python objects in the Python/C API.
495 .. method:: iterator.next()
497 Return the next item from the container. If there are no further items, raise
498 the :exc:`StopIteration` exception. This method corresponds to the
499 :attr:`tp_iternext` slot of the type structure for Python objects in the
502 Python defines several iterator objects to support iteration over general and
503 specific sequence types, dictionaries, and other more specialized forms. The
504 specific types are not important beyond their implementation of the iterator
507 The intention of the protocol is that once an iterator's :meth:`next` method
508 raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
509 Implementations that do not obey this property are deemed broken. (This
510 constraint was added in Python 2.3; in Python 2.2, various iterators are broken
511 according to this rule.)
513 Python's :term:`generator`\s provide a convenient way to implement the iterator
514 protocol. If a container object's :meth:`__iter__` method is implemented as a
515 generator, it will automatically return an iterator object (technically, a
516 generator object) supplying the :meth:`__iter__` and :meth:`next` methods.
521 Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`buffer`, :class:`xrange`
522 ==================================================================================================================
524 There are six sequence types: strings, Unicode strings, lists, tuples, buffers,
526 (For other containers see the built in :class:`dict`, :class:`list`,
527 :class:`set`, and :class:`tuple` classes, and the :mod:`collections`
540 String literals are written in single or double quotes: ``'xyzzy'``,
541 ``"frobozz"``. See :ref:`strings` for more about string literals.
542 Unicode strings are much like strings, but are specified in the syntax
543 using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
544 to the functionality described here, there are also string-specific
545 methods described in the :ref:`string-methods` section. Lists are
546 constructed with square brackets, separating items with commas: ``[a, b, c]``.
547 Tuples are constructed by the comma operator (not within square
548 brackets), with or without enclosing parentheses, but an empty tuple
549 must have the enclosing parentheses, such as ``a, b, c`` or ``()``. A
550 single item tuple must have a trailing comma, such as ``(d,)``.
552 Buffer objects are not directly supported by Python syntax, but can be created
553 by calling the builtin function :func:`buffer`. They don't support
554 concatenation or repetition.
556 Objects of type xrange are similar to buffers in that there is no specific syntax to
557 create them, but they are created using the :func:`xrange` function. They don't
558 support slicing, concatenation or repetition, and using ``in``, ``not in``,
559 :func:`min` or :func:`max` on them is inefficient.
561 Most sequence types support the following operations. The ``in`` and ``not in``
562 operations have the same priorities as the comparison operations. The ``+`` and
563 ``*`` operations have the same priority as the corresponding numeric operations.
564 [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
566 This table lists the sequence operations sorted in ascending priority
567 (operations in the same box have the same priority). In the table, *s* and *t*
568 are sequences of the same type; *n*, *i* and *j* are integers:
570 +------------------+--------------------------------+----------+
571 | Operation | Result | Notes |
572 +==================+================================+==========+
573 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
574 | | equal to *x*, else ``False`` | |
575 +------------------+--------------------------------+----------+
576 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
577 | | equal to *x*, else ``True`` | |
578 +------------------+--------------------------------+----------+
579 | ``s + t`` | the concatenation of *s* and | \(6) |
581 +------------------+--------------------------------+----------+
582 | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
584 +------------------+--------------------------------+----------+
585 | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
586 +------------------+--------------------------------+----------+
587 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
588 +------------------+--------------------------------+----------+
589 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
590 | | with step *k* | |
591 +------------------+--------------------------------+----------+
592 | ``len(s)`` | length of *s* | |
593 +------------------+--------------------------------+----------+
594 | ``min(s)`` | smallest item of *s* | |
595 +------------------+--------------------------------+----------+
596 | ``max(s)`` | largest item of *s* | |
597 +------------------+--------------------------------+----------+
599 Sequence types also support comparisons. In particular, tuples and lists
600 are compared lexicographically by comparing corresponding
601 elements. This means that to compare equal, every element must compare
602 equal and the two sequences must be of the same type and have the same
603 length. (For full details see :ref:`comparisons` in the language
607 triple: operations on; sequence; types
611 pair: concatenation; operation
612 pair: repetition; operation
613 pair: subscript; operation
614 pair: slice; operation
615 pair: extended slice; operation
622 When *s* is a string or Unicode string object the ``in`` and ``not in``
623 operations act like a substring test. In Python versions before 2.3, *x* had to
624 be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
628 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
629 sequence of the same type as *s*). Note also that the copies are shallow;
630 nested structures are not copied. This often haunts new Python programmers;
636 >>> lists[0].append(3)
640 What has happened is that ``[[]]`` is a one-element list containing an empty
641 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
642 list. Modifying any of the elements of ``lists`` modifies this single list.
643 You can create a list of different lists this way:
645 >>> lists = [[] for i in range(3)]
646 >>> lists[0].append(3)
647 >>> lists[1].append(5)
648 >>> lists[2].append(7)
653 If *i* or *j* is negative, the index is relative to the end of the string:
654 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is still
658 The slice of *s* from *i* to *j* is defined as the sequence of items with index
659 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
660 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
661 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
665 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
666 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
667 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
668 *j* is reached (but never including *j*). If *i* or *j* is greater than
669 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
670 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
671 If *k* is ``None``, it is treated like ``1``.
674 If *s* and *t* are both strings, some Python implementations such as CPython can
675 usually perform an in-place optimization for assignments of the form ``s=s+t``
676 or ``s+=t``. When applicable, this optimization makes quadratic run-time much
677 less likely. This optimization is both version and implementation dependent.
678 For performance sensitive code, it is preferable to use the :meth:`str.join`
679 method which assures consistent linear concatenation performance across versions
682 .. versionchanged:: 2.4
683 Formerly, string concatenation never occurred in-place.
691 .. index:: pair: string; methods
693 Below are listed the string methods which both 8-bit strings and Unicode objects
694 support. Note that none of these methods take keyword arguments.
696 In addition, Python's strings support the sequence type methods
697 described in the :ref:`typesseq` section. To output formatted strings
698 use template strings or the ``%`` operator described in the
699 :ref:`string-formatting` section. Also, see the :mod:`re` module for
700 string functions based on regular expressions.
702 .. method:: str.capitalize()
704 Return a copy of the string with only its first character capitalized.
706 For 8-bit strings, this method is locale-dependent.
709 .. method:: str.center(width[, fillchar])
711 Return centered in a string of length *width*. Padding is done using the
712 specified *fillchar* (default is a space).
714 .. versionchanged:: 2.4
715 Support for the *fillchar* argument.
718 .. method:: str.count(sub[, start[, end]])
720 Return the number of occurrences of substring *sub* in the range [*start*,
721 *end*]. Optional arguments *start* and *end* are interpreted as in slice
725 .. method:: str.decode([encoding[, errors]])
727 Decodes the string using the codec registered for *encoding*. *encoding*
728 defaults to the default string encoding. *errors* may be given to set a
729 different error handling scheme. The default is ``'strict'``, meaning that
730 encoding errors raise :exc:`UnicodeError`. Other possible values are
731 ``'ignore'``, ``'replace'`` and any other name registered via
732 :func:`codecs.register_error`, see section :ref:`codec-base-classes`.
734 .. versionadded:: 2.2
736 .. versionchanged:: 2.3
737 Support for other error handling schemes added.
740 .. method:: str.encode([encoding[,errors]])
742 Return an encoded version of the string. Default encoding is the current
743 default string encoding. *errors* may be given to set a different error
744 handling scheme. The default for *errors* is ``'strict'``, meaning that
745 encoding errors raise a :exc:`UnicodeError`. Other possible values are
746 ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
747 any other name registered via :func:`codecs.register_error`, see section
748 :ref:`codec-base-classes`. For a list of possible encodings, see section
749 :ref:`standard-encodings`.
751 .. versionadded:: 2.0
753 .. versionchanged:: 2.3
754 Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
755 handling schemes added.
758 .. method:: str.endswith(suffix[, start[, end]])
760 Return ``True`` if the string ends with the specified *suffix*, otherwise return
761 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
762 *start*, test beginning at that position. With optional *end*, stop comparing
765 .. versionchanged:: 2.5
766 Accept tuples as *suffix*.
769 .. method:: str.expandtabs([tabsize])
771 Return a copy of the string where all tab characters are replaced by one or
772 more spaces, depending on the current column and the given tab size. The
773 column number is reset to zero after each newline occurring in the string.
774 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
775 doesn't understand other non-printing characters or escape sequences.
778 .. method:: str.find(sub[, start[, end]])
780 Return the lowest index in the string where substring *sub* is found, such that
781 *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
782 and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
786 .. method:: str.format(format_string, *args, **kwargs)
788 Perform a string formatting operation. The *format_string* argument can
789 contain literal text or replacement fields delimited by braces ``{}``. Each
790 replacement field contains either the numeric index of a positional argument,
791 or the name of a keyword argument. Returns a copy of *format_string* where
792 each replacement field is replaced with the string value of the corresponding
795 >>> "The sum of 1 + 2 is {0}".format(1+2)
796 'The sum of 1 + 2 is 3'
798 See :ref:`formatstrings` for a description of the various formatting options
799 that can be specified in format strings.
801 This method of string formatting is the new standard in Python 3.0, and
802 should be preferred to the ``%`` formatting described in
803 :ref:`string-formatting` in new code.
805 .. versionadded:: 2.6
808 .. method:: str.index(sub[, start[, end]])
810 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
813 .. method:: str.isalnum()
815 Return true if all characters in the string are alphanumeric and there is at
816 least one character, false otherwise.
818 For 8-bit strings, this method is locale-dependent.
821 .. method:: str.isalpha()
823 Return true if all characters in the string are alphabetic and there is at least
824 one character, false otherwise.
826 For 8-bit strings, this method is locale-dependent.
829 .. method:: str.isdigit()
831 Return true if all characters in the string are digits and there is at least one
832 character, false otherwise.
834 For 8-bit strings, this method is locale-dependent.
837 .. method:: str.islower()
839 Return true if all cased characters in the string are lowercase and there is at
840 least one cased character, false otherwise.
842 For 8-bit strings, this method is locale-dependent.
845 .. method:: str.isspace()
847 Return true if there are only whitespace characters in the string and there is
848 at least one character, false otherwise.
850 For 8-bit strings, this method is locale-dependent.
853 .. method:: str.istitle()
855 Return true if the string is a titlecased string and there is at least one
856 character, for example uppercase characters may only follow uncased characters
857 and lowercase characters only cased ones. Return false otherwise.
859 For 8-bit strings, this method is locale-dependent.
862 .. method:: str.isupper()
864 Return true if all cased characters in the string are uppercase and there is at
865 least one cased character, false otherwise.
867 For 8-bit strings, this method is locale-dependent.
870 .. method:: str.join(seq)
872 Return a string which is the concatenation of the strings in the sequence *seq*.
873 The separator between elements is the string providing this method.
876 .. method:: str.ljust(width[, fillchar])
878 Return the string left justified in a string of length *width*. Padding is done
879 using the specified *fillchar* (default is a space). The original string is
880 returned if *width* is less than ``len(s)``.
882 .. versionchanged:: 2.4
883 Support for the *fillchar* argument.
886 .. method:: str.lower()
888 Return a copy of the string converted to lowercase.
890 For 8-bit strings, this method is locale-dependent.
893 .. method:: str.lstrip([chars])
895 Return a copy of the string with leading characters removed. The *chars*
896 argument is a string specifying the set of characters to be removed. If omitted
897 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
898 argument is not a prefix; rather, all combinations of its values are stripped:
900 >>> ' spacious '.lstrip()
902 >>> 'www.example.com'.lstrip('cmowz.')
905 .. versionchanged:: 2.2.2
906 Support for the *chars* argument.
909 .. method:: str.partition(sep)
911 Split the string at the first occurrence of *sep*, and return a 3-tuple
912 containing the part before the separator, the separator itself, and the part
913 after the separator. If the separator is not found, return a 3-tuple containing
914 the string itself, followed by two empty strings.
916 .. versionadded:: 2.5
919 .. method:: str.replace(old, new[, count])
921 Return a copy of the string with all occurrences of substring *old* replaced by
922 *new*. If the optional argument *count* is given, only the first *count*
923 occurrences are replaced.
926 .. method:: str.rfind(sub [,start [,end]])
928 Return the highest index in the string where substring *sub* is found, such that
929 *sub* is contained within s[start,end]. Optional arguments *start* and *end*
930 are interpreted as in slice notation. Return ``-1`` on failure.
933 .. method:: str.rindex(sub[, start[, end]])
935 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
939 .. method:: str.rjust(width[, fillchar])
941 Return the string right justified in a string of length *width*. Padding is done
942 using the specified *fillchar* (default is a space). The original string is
943 returned if *width* is less than ``len(s)``.
945 .. versionchanged:: 2.4
946 Support for the *fillchar* argument.
949 .. method:: str.rpartition(sep)
951 Split the string at the last occurrence of *sep*, and return a 3-tuple
952 containing the part before the separator, the separator itself, and the part
953 after the separator. If the separator is not found, return a 3-tuple containing
954 two empty strings, followed by the string itself.
956 .. versionadded:: 2.5
959 .. method:: str.rsplit([sep [,maxsplit]])
961 Return a list of the words in the string, using *sep* as the delimiter string.
962 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
963 ones. If *sep* is not specified or ``None``, any whitespace string is a
964 separator. Except for splitting from the right, :meth:`rsplit` behaves like
965 :meth:`split` which is described in detail below.
967 .. versionadded:: 2.4
970 .. method:: str.rstrip([chars])
972 Return a copy of the string with trailing characters removed. The *chars*
973 argument is a string specifying the set of characters to be removed. If omitted
974 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
975 argument is not a suffix; rather, all combinations of its values are stripped:
977 >>> ' spacious '.rstrip()
979 >>> 'mississippi'.rstrip('ipz')
982 .. versionchanged:: 2.2.2
983 Support for the *chars* argument.
986 .. method:: str.split([sep[, maxsplit]])
988 Return a list of the words in the string, using *sep* as the delimiter
989 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
990 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
991 specified, then there is no limit on the number of splits (all possible
994 If *sep* is given, consecutive delimiters are not grouped together and are
995 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
996 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
997 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
998 Splitting an empty string with a specified separator returns ``['']``.
1000 If *sep* is not specified or is ``None``, a different splitting algorithm is
1001 applied: runs of consecutive whitespace are regarded as a single separator,
1002 and the result will contain no empty strings at the start or end if the
1003 string has leading or trailing whitespace. Consequently, splitting an empty
1004 string or a string consisting of just whitespace with a ``None`` separator
1007 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1008 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
1011 .. method:: str.splitlines([keepends])
1013 Return a list of the lines in the string, breaking at line boundaries. Line
1014 breaks are not included in the resulting list unless *keepends* is given and
1018 .. method:: str.startswith(prefix[, start[, end]])
1020 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1021 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1022 test string beginning at that position. With optional *end*, stop comparing
1023 string at that position.
1025 .. versionchanged:: 2.5
1026 Accept tuples as *prefix*.
1029 .. method:: str.strip([chars])
1031 Return a copy of the string with the leading and trailing characters removed.
1032 The *chars* argument is a string specifying the set of characters to be removed.
1033 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1034 The *chars* argument is not a prefix or suffix; rather, all combinations of its
1035 values are stripped:
1037 >>> ' spacious '.strip()
1039 >>> 'www.example.com'.strip('cmowz.')
1042 .. versionchanged:: 2.2.2
1043 Support for the *chars* argument.
1046 .. method:: str.swapcase()
1048 Return a copy of the string with uppercase characters converted to lowercase and
1051 For 8-bit strings, this method is locale-dependent.
1054 .. method:: str.title()
1056 Return a titlecased version of the string: words start with uppercase
1057 characters, all remaining cased characters are lowercase.
1059 For 8-bit strings, this method is locale-dependent.
1062 .. method:: str.translate(table[, deletechars])
1064 Return a copy of the string where all characters occurring in the optional
1065 argument *deletechars* are removed, and the remaining characters have been
1066 mapped through the given translation table, which must be a string of length
1069 You can use the :func:`maketrans` helper function in the :mod:`string` module to
1070 create a translation table. For string objects, set the *table* argument to
1071 ``None`` for translations that only delete characters:
1073 >>> 'read this short text'.translate(None, 'aeiou')
1076 .. versionadded:: 2.6
1077 Support for a ``None`` *table* argument.
1079 For Unicode objects, the :meth:`translate` method does not accept the optional
1080 *deletechars* argument. Instead, it returns a copy of the *s* where all
1081 characters have been mapped through the given translation table which must be a
1082 mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
1083 Unmapped characters are left untouched. Characters mapped to ``None`` are
1084 deleted. Note, a more flexible approach is to create a custom character mapping
1085 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1089 .. method:: str.upper()
1091 Return a copy of the string converted to uppercase.
1093 For 8-bit strings, this method is locale-dependent.
1096 .. method:: str.zfill(width)
1098 Return the numeric string left filled with zeros in a string of length
1099 *width*. A sign prefix is handled correctly. The original string is
1100 returned if *width* is less than ``len(s)``.
1103 .. versionadded:: 2.2.2
1105 The following methods are present only on unicode objects:
1107 .. method:: unicode.isnumeric()
1109 Return ``True`` if there are only numeric characters in S, ``False``
1110 otherwise. Numeric characters include digit characters, and all characters
1111 that have the Unicode numeric value property, e.g. U+2155,
1112 VULGAR FRACTION ONE FIFTH.
1114 .. method:: unicode.isdecimal()
1116 Return ``True`` if there are only decimal characters in S, ``False``
1117 otherwise. Decimal characters include digit characters, and all characters
1118 that that can be used to form decimal-radix numbers, e.g. U+0660,
1119 ARABIC-INDIC DIGIT ZERO.
1122 .. _string-formatting:
1124 String Formatting Operations
1125 ----------------------------
1128 single: formatting, string (%)
1129 single: interpolation, string (%)
1130 single: string; formatting
1131 single: string; interpolation
1132 single: printf-style formatting
1133 single: sprintf-style formatting
1134 single: % formatting
1135 single: % interpolation
1137 String and Unicode objects have one unique built-in operation: the ``%``
1138 operator (modulo). This is also known as the string *formatting* or
1139 *interpolation* operator. Given ``format % values`` (where *format* is a string
1140 or Unicode object), ``%`` conversion specifications in *format* are replaced
1141 with zero or more elements of *values*. The effect is similar to the using
1142 :cfunc:`sprintf` in the C language. If *format* is a Unicode object, or if any
1143 of the objects being converted using the ``%s`` conversion are Unicode objects,
1144 the result will also be a Unicode object.
1146 If *format* requires a single argument, *values* may be a single non-tuple
1147 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1148 items specified by the format string, or a single mapping object (for example, a
1151 A conversion specifier contains two or more characters and has the following
1152 components, which must occur in this order:
1154 #. The ``'%'`` character, which marks the start of the specifier.
1156 #. Mapping key (optional), consisting of a parenthesised sequence of characters
1157 (for example, ``(somename)``).
1159 #. Conversion flags (optional), which affect the result of some conversion
1162 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1163 actual width is read from the next element of the tuple in *values*, and the
1164 object to convert comes after the minimum field width and optional precision.
1166 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1167 specified as ``'*'`` (an asterisk), the actual width is read from the next
1168 element of the tuple in *values*, and the value to convert comes after the
1171 #. Length modifier (optional).
1175 When the right argument is a dictionary (or other mapping type), then the
1176 formats in the string *must* include a parenthesised mapping key into that
1177 dictionary inserted immediately after the ``'%'`` character. The mapping key
1178 selects the value to be formatted from the mapping. For example:
1180 >>> print '%(language)s has %(#)03d quote types.' % \
1181 ... {'language': "Python", "#": 2}
1182 Python has 002 quote types.
1184 In this case no ``*`` specifiers may occur in a format (since they require a
1185 sequential parameter list).
1187 The conversion flag characters are:
1189 +---------+---------------------------------------------------------------------+
1191 +=========+=====================================================================+
1192 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
1194 +---------+---------------------------------------------------------------------+
1195 | ``'0'`` | The conversion will be zero padded for numeric values. |
1196 +---------+---------------------------------------------------------------------+
1197 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1198 | | conversion if both are given). |
1199 +---------+---------------------------------------------------------------------+
1200 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
1201 | | string) produced by a signed conversion. |
1202 +---------+---------------------------------------------------------------------+
1203 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1204 | | (overrides a "space" flag). |
1205 +---------+---------------------------------------------------------------------+
1207 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
1208 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1210 The conversion types are:
1212 +------------+-----------------------------------------------------+-------+
1213 | Conversion | Meaning | Notes |
1214 +============+=====================================================+=======+
1215 | ``'d'`` | Signed integer decimal. | |
1216 +------------+-----------------------------------------------------+-------+
1217 | ``'i'`` | Signed integer decimal. | |
1218 +------------+-----------------------------------------------------+-------+
1219 | ``'o'`` | Signed octal value. | \(1) |
1220 +------------+-----------------------------------------------------+-------+
1221 | ``'u'`` | Obselete type -- it is identical to ``'d'``. | \(7) |
1222 +------------+-----------------------------------------------------+-------+
1223 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
1224 +------------+-----------------------------------------------------+-------+
1225 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
1226 +------------+-----------------------------------------------------+-------+
1227 | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1228 +------------+-----------------------------------------------------+-------+
1229 | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1230 +------------+-----------------------------------------------------+-------+
1231 | ``'f'`` | Floating point decimal format. | \(3) |
1232 +------------+-----------------------------------------------------+-------+
1233 | ``'F'`` | Floating point decimal format. | \(3) |
1234 +------------+-----------------------------------------------------+-------+
1235 | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1236 | | format if exponent is less than -4 or not less than | |
1237 | | precision, decimal format otherwise. | |
1238 +------------+-----------------------------------------------------+-------+
1239 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1240 | | format if exponent is less than -4 or not less than | |
1241 | | precision, decimal format otherwise. | |
1242 +------------+-----------------------------------------------------+-------+
1243 | ``'c'`` | Single character (accepts integer or single | |
1244 | | character string). | |
1245 +------------+-----------------------------------------------------+-------+
1246 | ``'r'`` | String (converts any python object using | \(5) |
1247 | | :func:`repr`). | |
1248 +------------+-----------------------------------------------------+-------+
1249 | ``'s'`` | String (converts any python object using | \(6) |
1250 | | :func:`str`). | |
1251 +------------+-----------------------------------------------------+-------+
1252 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1253 | | character in the result. | |
1254 +------------+-----------------------------------------------------+-------+
1259 The alternate form causes a leading zero (``'0'``) to be inserted between
1260 left-hand padding and the formatting of the number if the leading character
1261 of the result is not already a zero.
1264 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1265 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1266 and the formatting of the number if the leading character of the result is not
1270 The alternate form causes the result to always contain a decimal point, even if
1271 no digits follow it.
1273 The precision determines the number of digits after the decimal point and
1277 The alternate form causes the result to always contain a decimal point, and
1278 trailing zeroes are not removed as they would otherwise be.
1280 The precision determines the number of significant digits before and after the
1281 decimal point and defaults to 6.
1284 The ``%r`` conversion was added in Python 2.0.
1286 The precision determines the maximal number of characters used.
1289 If the object or format provided is a :class:`unicode` string, the resulting
1290 string will also be :class:`unicode`.
1292 The precision determines the maximal number of characters used.
1297 Since Python strings have an explicit length, ``%s`` conversions do not assume
1298 that ``'\0'`` is the end of the string.
1302 For safety reasons, floating point precisions are clipped to 50; ``%f``
1303 conversions for numbers whose absolute value is over 1e25 are replaced by ``%g``
1304 conversions. [#]_ All other errors raise exceptions.
1310 Additional string operations are defined in standard modules :mod:`string` and
1314 .. _typesseq-xrange:
1319 .. index:: object: xrange
1321 The :class:`xrange` type is an immutable sequence which is commonly used for
1322 looping. The advantage of the :class:`xrange` type is that an :class:`xrange`
1323 object will always take the same amount of memory, no matter the size of the
1324 range it represents. There are no consistent performance advantages.
1326 XRange objects have very little behavior: they only support indexing, iteration,
1327 and the :func:`len` function.
1330 .. _typesseq-mutable:
1332 Mutable Sequence Types
1333 ----------------------
1336 triple: mutable; sequence; types
1339 List objects support additional operations that allow in-place modification of
1340 the object. Other mutable sequence types (when added to the language) should
1341 also support these operations. Strings and tuples are immutable sequence types:
1342 such objects cannot be modified once created. The following operations are
1343 defined on mutable sequence types (where *x* is an arbitrary object):
1345 +------------------------------+--------------------------------+---------------------+
1346 | Operation | Result | Notes |
1347 +==============================+================================+=====================+
1348 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1350 +------------------------------+--------------------------------+---------------------+
1351 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1352 | | is replaced by the contents of | |
1353 | | the iterable *t* | |
1354 +------------------------------+--------------------------------+---------------------+
1355 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1356 +------------------------------+--------------------------------+---------------------+
1357 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1358 | | are replaced by those of *t* | |
1359 +------------------------------+--------------------------------+---------------------+
1360 | ``del s[i:j:k]`` | removes the elements of | |
1361 | | ``s[i:j:k]`` from the list | |
1362 +------------------------------+--------------------------------+---------------------+
1363 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1365 +------------------------------+--------------------------------+---------------------+
1366 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(3) |
1368 +------------------------------+--------------------------------+---------------------+
1369 | ``s.count(x)`` | return number of *i*'s for | |
1370 | | which ``s[i] == x`` | |
1371 +------------------------------+--------------------------------+---------------------+
1372 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(4) |
1373 | | ``s[k] == x`` and ``i <= k < | |
1375 +------------------------------+--------------------------------+---------------------+
1376 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(5) |
1377 +------------------------------+--------------------------------+---------------------+
1378 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(6) |
1380 +------------------------------+--------------------------------+---------------------+
1381 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(4) |
1382 +------------------------------+--------------------------------+---------------------+
1383 | ``s.reverse()`` | reverses the items of *s* in | \(7) |
1385 +------------------------------+--------------------------------+---------------------+
1386 | ``s.sort([cmp[, key[, | sort the items of *s* in place | (7)(8)(9)(10) |
1387 | reverse]]])`` | | |
1388 +------------------------------+--------------------------------+---------------------+
1391 triple: operations on; sequence; types
1392 triple: operations on; list; type
1393 pair: subscript; assignment
1394 pair: slice; assignment
1395 pair: extended slice; assignment
1397 single: append() (list method)
1398 single: extend() (list method)
1399 single: count() (list method)
1400 single: index() (list method)
1401 single: insert() (list method)
1402 single: pop() (list method)
1403 single: remove() (list method)
1404 single: reverse() (list method)
1405 single: sort() (list method)
1410 *t* must have the same length as the slice it is replacing.
1413 The C implementation of Python has historically accepted multiple parameters and
1414 implicitly joined them into a tuple; this no longer works in Python 2.0. Use of
1415 this misfeature has been deprecated since Python 1.4.
1418 *x* can be any iterable object.
1421 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1422 passed as the second or third parameter to the :meth:`index` method, the list
1423 length is added, as for slice indices. If it is still negative, it is truncated
1424 to zero, as for slice indices.
1426 .. versionchanged:: 2.3
1427 Previously, :meth:`index` didn't have arguments for specifying start and stop
1431 When a negative index is passed as the first parameter to the :meth:`insert`
1432 method, the list length is added, as for slice indices. If it is still
1433 negative, it is truncated to zero, as for slice indices.
1435 .. versionchanged:: 2.3
1436 Previously, all negative indices were truncated to zero.
1439 The :meth:`pop` method is only supported by the list and array types. The
1440 optional argument *i* defaults to ``-1``, so that by default the last item is
1441 removed and returned.
1444 The :meth:`sort` and :meth:`reverse` methods modify the list in place for
1445 economy of space when sorting or reversing a large list. To remind you that
1446 they operate by side effect, they don't return the sorted or reversed list.
1449 The :meth:`sort` method takes optional arguments for controlling the
1452 *cmp* specifies a custom comparison function of two arguments (list items) which
1453 should return a negative, zero or positive number depending on whether the first
1454 argument is considered smaller than, equal to, or larger than the second
1455 argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``. The default value
1458 *key* specifies a function of one argument that is used to extract a comparison
1459 key from each list element: ``key=str.lower``. The default value is ``None``.
1461 *reverse* is a boolean value. If set to ``True``, then the list elements are
1462 sorted as if each comparison were reversed.
1464 In general, the *key* and *reverse* conversion processes are much faster than
1465 specifying an equivalent *cmp* function. This is because *cmp* is called
1466 multiple times for each list element while *key* and *reverse* touch each
1469 .. versionchanged:: 2.3
1470 Support for ``None`` as an equivalent to omitting *cmp* was added.
1472 .. versionchanged:: 2.4
1473 Support for *key* and *reverse* was added.
1476 Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A
1477 sort is stable if it guarantees not to change the relative order of elements
1478 that compare equal --- this is helpful for sorting in multiple passes (for
1479 example, sort by department, then by salary grade).
1482 While a list is being sorted, the effect of attempting to mutate, or even
1483 inspect, the list is undefined. The C implementation of Python 2.3 and newer
1484 makes the list appear empty for the duration, and raises :exc:`ValueError` if it
1485 can detect that the list has been mutated during a sort.
1490 Set Types --- :class:`set`, :class:`frozenset`
1491 ==============================================
1493 .. index:: object: set
1495 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1496 Common uses include membership testing, removing duplicates from a sequence, and
1497 computing mathematical operations such as intersection, union, difference, and
1498 symmetric difference.
1499 (For other containers see the built in :class:`dict`, :class:`list`,
1500 and :class:`tuple` classes, and the :mod:`collections` module.)
1503 .. versionadded:: 2.4
1505 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1506 set``. Being an unordered collection, sets do not record element position or
1507 order of insertion. Accordingly, sets do not support indexing, slicing, or
1508 other sequence-like behavior.
1510 There are currently two builtin set types, :class:`set` and :class:`frozenset`.
1511 The :class:`set` type is mutable --- the contents can be changed using methods
1512 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1513 and cannot be used as either a dictionary key or as an element of another set.
1514 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
1515 altered after it is created; it can therefore be used as a dictionary key or as
1516 an element of another set.
1518 The constructors for both classes work the same:
1520 .. class:: set([iterable])
1521 frozenset([iterable])
1523 Return a new set or frozenset object whose elements are taken from
1524 *iterable*. The elements of a set must be hashable. To represent sets of
1525 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1526 not specified, a new empty set is returned.
1528 Instances of :class:`set` and :class:`frozenset` provide the following
1531 .. describe:: len(s)
1533 Return the cardinality of set *s*.
1535 .. describe:: x in s
1537 Test *x* for membership in *s*.
1539 .. describe:: x not in s
1541 Test *x* for non-membership in *s*.
1543 .. method:: isdisjoint(other)
1545 Return True if the set has no elements in common with *other*. Sets are
1546 disjoint if and only if their interesection is the empty set.
1548 .. versionadded:: 2.6
1550 .. method:: issubset(other)
1553 Test whether every element in the set is in *other*.
1555 .. method:: set < other
1557 Test whether the set is a true subset of *other*, that is,
1558 ``set <= other and set != other``.
1560 .. method:: issuperset(other)
1563 Test whether every element in *other* is in the set.
1565 .. method:: set > other
1567 Test whether the set is a true superset of *other*, that is, ``set >=
1568 other and set != other``.
1570 .. method:: union(other)
1573 Return a new set with elements from both sets.
1575 .. method:: intersection(other)
1578 Return a new set with elements common to both sets.
1580 .. method:: difference(other)
1583 Return a new set with elements in the set that are not in *other*.
1585 .. method:: symmetric_difference(other)
1588 Return a new set with elements in either the set or *other* but not both.
1592 Return a new set with a shallow copy of *s*.
1595 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1596 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1597 :meth:`issuperset` methods will accept any iterable as an argument. In
1598 contrast, their operator based counterparts require their arguments to be
1599 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1600 in favor of the more readable ``set('abc').intersection('cbs')``.
1602 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1603 sets are equal if and only if every element of each set is contained in the
1604 other (each is a subset of the other). A set is less than another set if and
1605 only if the first set is a proper subset of the second set (is a subset, but
1606 is not equal). A set is greater than another set if and only if the first set
1607 is a proper superset of the second set (is a superset, but is not equal).
1609 Instances of :class:`set` are compared to instances of :class:`frozenset`
1610 based on their members. For example, ``set('abc') == frozenset('abc')``
1611 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1613 The subset and equality comparisons do not generalize to a complete ordering
1614 function. For example, any two disjoint sets are not equal and are not
1615 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1616 ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
1619 Since sets only define partial ordering (subset relationships), the output of
1620 the :meth:`list.sort` method is undefined for lists of sets.
1622 Set elements, like dictionary keys, must be :term:`hashable`.
1624 Binary operations that mix :class:`set` instances with :class:`frozenset`
1625 return the type of the first operand. For example: ``frozenset('ab') |
1626 set('bc')`` returns an instance of :class:`frozenset`.
1628 The following table lists operations available for :class:`set` that do not
1629 apply to immutable instances of :class:`frozenset`:
1631 .. method:: update(other)
1634 Update the set, adding elements from *other*.
1636 .. method:: intersection_update(other)
1639 Update the set, keeping only elements found in it and *other*.
1641 .. method:: difference_update(other)
1644 Update the set, removing elements found in *other*.
1646 .. method:: symmetric_difference_update(other)
1649 Update the set, keeping only elements found in either set, but not in both.
1651 .. method:: add(elem)
1653 Add element *elem* to the set.
1655 .. method:: remove(elem)
1657 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1658 not contained in the set.
1660 .. method:: discard(elem)
1662 Remove element *elem* from the set if it is present.
1666 Remove and return an arbitrary element from the set. Raises
1667 :exc:`KeyError` if the set is empty.
1671 Remove all elements from the set.
1674 Note, the non-operator versions of the :meth:`update`,
1675 :meth:`intersection_update`, :meth:`difference_update`, and
1676 :meth:`symmetric_difference_update` methods will accept any iterable as an
1679 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1680 :meth:`discard` methods may be a set. To support searching for an equivalent
1681 frozenset, the *elem* set is temporarily mutated during the search and then
1682 restored. During the search, the *elem* set should not be read or mutated
1683 since it does not have a meaningful value.
1688 :ref:`comparison-to-builtin-set`
1689 Differences between the :mod:`sets` module and the built-in set types.
1694 Mapping Types --- :class:`dict`
1695 ===============================
1700 triple: operations on; mapping; types
1701 triple: operations on; dictionary; type
1705 A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1706 Mappings are mutable objects. There is currently only one standard mapping
1707 type, the :dfn:`dictionary`. (For other containers see the built in
1708 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
1709 :mod:`collections` module.)
1711 A dictionary's keys are *almost* arbitrary values. Values that are not
1712 :term:`hashable`, that is, values containing lists, dictionaries or other
1713 mutable types (that are compared by value rather than by object identity) may
1714 not be used as keys. Numeric types used for keys obey the normal rules for
1715 numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1716 then they can be used interchangeably to index the same dictionary entry. (Note
1717 however, that since computers store floating-point numbers as approximations it
1718 is usually unwise to use them as dictionary keys.)
1720 Dictionaries can be created by placing a comma-separated list of ``key: value``
1721 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1722 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1724 .. class:: dict([arg])
1726 Return a new dictionary initialized from an optional positional argument or from
1727 a set of keyword arguments. If no arguments are given, return a new empty
1728 dictionary. If the positional argument *arg* is a mapping object, return a
1729 dictionary mapping the same keys to the same values as does the mapping object.
1730 Otherwise the positional argument must be a sequence, a container that supports
1731 iteration, or an iterator object. The elements of the argument must each also
1732 be of one of those kinds, and each must in turn contain exactly two objects.
1733 The first is used as a key in the new dictionary, and the second as the key's
1734 value. If a given key is seen more than once, the last value associated with it
1735 is retained in the new dictionary.
1737 If keyword arguments are given, the keywords themselves with their associated
1738 values are added as items to the dictionary. If a key is specified both in the
1739 positional argument and as a keyword argument, the value associated with the
1740 keyword is retained in the dictionary. For example, these all return a
1741 dictionary equal to ``{"one": 2, "two": 3}``:
1743 * ``dict(one=2, two=3)``
1745 * ``dict({'one': 2, 'two': 3})``
1747 * ``dict(zip(('one', 'two'), (2, 3)))``
1749 * ``dict([['two', 3], ['one', 2]])``
1751 The first example only works for keys that are valid Python
1752 identifiers; the others work with any valid keys.
1754 .. versionadded:: 2.2
1756 .. versionchanged:: 2.3
1757 Support for building a dictionary from keyword arguments added.
1760 These are the operations that dictionaries support (and therefore, custom
1761 mapping types should support too):
1763 .. describe:: len(d)
1765 Return the number of items in the dictionary *d*.
1767 .. describe:: d[key]
1769 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key*
1772 .. versionadded:: 2.5
1773 If a subclass of dict defines a method :meth:`__missing__`, if the key
1774 *key* is not present, the ``d[key]`` operation calls that method with
1775 the key *key* as argument. The ``d[key]`` operation then returns or
1776 raises whatever is returned or raised by the ``__missing__(key)`` call
1777 if the key is not present. No other operations or methods invoke
1778 :meth:`__missing__`. If :meth:`__missing__` is not defined,
1779 :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it
1780 cannot be an instance variable. For an example, see
1781 :class:`collections.defaultdict`.
1783 .. describe:: d[key] = value
1785 Set ``d[key]`` to *value*.
1787 .. describe:: del d[key]
1789 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1792 .. describe:: key in d
1794 Return ``True`` if *d* has a key *key*, else ``False``.
1796 .. versionadded:: 2.2
1798 .. describe:: key not in d
1800 Equivalent to ``not key in d``.
1802 .. versionadded:: 2.2
1806 Remove all items from the dictionary.
1810 Return a shallow copy of the dictionary.
1812 .. method:: fromkeys(seq[, value])
1814 Create a new dictionary with keys from *seq* and values set to *value*.
1816 :func:`fromkeys` is a class method that returns a new dictionary. *value*
1817 defaults to ``None``.
1819 .. versionadded:: 2.3
1821 .. method:: get(key[, default])
1823 Return the value for *key* if *key* is in the dictionary, else *default*.
1824 If *default* is not given, it defaults to ``None``, so that this method
1825 never raises a :exc:`KeyError`.
1827 .. method:: has_key(key)
1829 ``dict.has_key(key)`` is equivalent to ``key in d``, but deprecated.
1833 Return a copy of the dictionary's list of ``(key, value)`` pairs.
1837 Keys and values are listed in an arbitrary order which is non-random,
1838 varies across Python implementations, and depends on the dictionary's
1839 history of insertions and deletions. If :meth:`items`, :meth:`keys`,
1840 :meth:`values`, :meth:`iteritems`, :meth:`iterkeys`, and
1841 :meth:`itervalues` are called with no intervening modifications to the
1842 dictionary, the lists will directly correspond. This allows the
1843 creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
1844 zip(d.values(), d.keys())``. The same relationship holds for the
1845 :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
1846 zip(d.itervalues(), d.iterkeys())`` provides the same value for
1847 ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
1848 (k, v) in d.iteritems()]``.
1850 .. method:: iteritems()
1852 Return an iterator over the dictionary's ``(key, value)`` pairs. See the
1853 note for :meth:`dict.items`.
1855 .. versionadded:: 2.2
1857 .. method:: iterkeys()
1859 Return an iterator over the dictionary's keys. See the note for
1862 .. versionadded:: 2.2
1864 .. method:: itervalues()
1866 Return an iterator over the dictionary's values. See the note for
1869 .. versionadded:: 2.2
1873 Return a copy of the dictionary's list of keys. See the note for
1876 .. method:: pop(key[, default])
1878 If *key* is in the dictionary, remove it and return its value, else return
1879 *default*. If *default* is not given and *key* is not in the dictionary,
1880 a :exc:`KeyError` is raised.
1882 .. versionadded:: 2.3
1884 .. method:: popitem()
1886 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
1888 :func:`popitem` is useful to destructively iterate over a dictionary, as
1889 often used in set algorithms. If the dictionary is empty, calling
1890 :func:`popitem` raises a :exc:`KeyError`.
1892 .. method:: setdefault(key[, default])
1894 If *key* is in the dictionary, return its value. If not, insert *key*
1895 with a value of *default* and return *default*. *default* defaults to
1898 .. method:: update([other])
1900 Update the dictionary with the key/value pairs from *other*, overwriting
1901 existing keys. Return ``None``.
1903 :func:`update` accepts either another dictionary object or an iterable of
1904 key/value pairs (as a tuple or other iterable of length two). If keyword
1905 arguments are specified, the dictionary is then is updated with those
1906 key/value pairs: ``d.update(red=1, blue=2)``.
1908 .. versionchanged:: 2.4
1909 Allowed the argument to be an iterable of key/value pairs and allowed
1912 .. method:: values()
1914 Return a copy of the dictionary's list of values. See the note for
1918 .. _bltin-file-objects:
1929 File objects are implemented using C's ``stdio`` package and can be
1930 created with the built-in :func:`open` function. File
1931 objects are also returned by some other built-in functions and methods,
1932 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
1933 method of socket objects. Temporary files can be created using the
1934 :mod:`tempfile` module, and high-level file operations such as copying,
1935 moving, and deleting files and directories can be achieved with the
1936 :mod:`shutil` module.
1938 When a file operation fails for an I/O-related reason, the exception
1939 :exc:`IOError` is raised. This includes situations where the operation is not
1940 defined for some reason, like :meth:`seek` on a tty device or writing a file
1943 Files have the following methods:
1946 .. method:: file.close()
1948 Close the file. A closed file cannot be read or written any more. Any operation
1949 which requires that the file be open will raise a :exc:`ValueError` after the
1950 file has been closed. Calling :meth:`close` more than once is allowed.
1952 As of Python 2.5, you can avoid having to call this method explicitly if you use
1953 the :keyword:`with` statement. For example, the following code will
1954 automatically close *f* when the :keyword:`with` block is exited::
1956 from __future__ import with_statement
1958 with open("hello.txt") as f:
1962 In older versions of Python, you would have needed to do this to get the same
1965 f = open("hello.txt")
1974 Not all "file-like" types in Python support use as a context manager for the
1975 :keyword:`with` statement. If your code is intended to work with any file-like
1976 object, you can use the function :func:`contextlib.closing` instead of using
1977 the object directly.
1980 .. method:: file.flush()
1982 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
1983 no-op on some file-like objects.
1986 .. method:: file.fileno()
1989 pair: file; descriptor
1992 Return the integer "file descriptor" that is used by the underlying
1993 implementation to request I/O operations from the operating system. This can be
1994 useful for other, lower level interfaces that use file descriptors, such as the
1995 :mod:`fcntl` module or :func:`os.read` and friends.
1999 File-like objects which do not have a real file descriptor should *not* provide
2003 .. method:: file.isatty()
2005 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
2009 If a file-like object is not associated with a real file, this method should
2010 *not* be implemented.
2013 .. method:: file.next()
2015 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2016 *f* is closed). When a file is used as an iterator, typically in a
2017 :keyword:`for` loop (for example, ``for line in f: print line``), the
2018 :meth:`next` method is called repeatedly. This method returns the next input
2019 line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
2020 reading (behavior is undefined when the file is open for writing). In order to
2021 make a :keyword:`for` loop the most efficient way of looping over the lines of a
2022 file (a very common operation), the :meth:`next` method uses a hidden read-ahead
2023 buffer. As a consequence of using a read-ahead buffer, combining :meth:`next`
2024 with other file methods (like :meth:`readline`) does not work right. However,
2025 using :meth:`seek` to reposition the file to an absolute position will flush the
2028 .. versionadded:: 2.3
2031 .. method:: file.read([size])
2033 Read at most *size* bytes from the file (less if the read hits EOF before
2034 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2035 all data until EOF is reached. The bytes are returned as a string object. An
2036 empty string is returned when EOF is encountered immediately. (For certain
2037 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2038 that this method may call the underlying C function :cfunc:`fread` more than
2039 once in an effort to acquire as close to *size* bytes as possible. Also note
2040 that when in non-blocking mode, less data than what was requested may be
2041 returned, even if no *size* parameter was given.
2044 .. method:: file.readline([size])
2046 Read one entire line from the file. A trailing newline character is kept in the
2047 string (but may be absent when a file ends with an incomplete line). [#]_ If
2048 the *size* argument is present and non-negative, it is a maximum byte count
2049 (including the trailing newline) and an incomplete line may be returned. An
2050 empty string is returned *only* when EOF is encountered immediately.
2054 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
2055 (``'\0'``) if they occurred in the input.
2058 .. method:: file.readlines([sizehint])
2060 Read until EOF using :meth:`readline` and return a list containing the lines
2061 thus read. If the optional *sizehint* argument is present, instead of
2062 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2063 (possibly after rounding up to an internal buffer size) are read. Objects
2064 implementing a file-like interface may choose to ignore *sizehint* if it
2065 cannot be implemented, or cannot be implemented efficiently.
2068 .. method:: file.xreadlines()
2070 This method returns the same thing as ``iter(f)``.
2072 .. versionadded:: 2.1
2075 Use ``for line in file`` instead.
2078 .. method:: file.seek(offset[, whence])
2080 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
2081 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2082 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2083 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2084 end). There is no return value.
2086 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2087 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2089 Note that if the file is opened for appending
2090 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2091 next write. If the file is only opened for writing in append mode (mode
2092 ``'a'``), this method is essentially a no-op, but it remains useful for files
2093 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2094 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2095 legal. Use of other offsets causes undefined behavior.
2097 Note that not all file objects are seekable.
2099 .. versionchanged:: 2.6
2100 Passing float values as offset has been deprecated.
2103 .. method:: file.tell()
2105 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2109 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
2110 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2111 circumvent this problem.
2114 .. method:: file.truncate([size])
2116 Truncate the file's size. If the optional *size* argument is present, the file
2117 is truncated to (at most) that size. The size defaults to the current position.
2118 The current file position is not changed. Note that if a specified size exceeds
2119 the file's current size, the result is platform-dependent: possibilities
2120 include that the file may remain unchanged, increase to the specified size as if
2121 zero-filled, or increase to the specified size with undefined new content.
2122 Availability: Windows, many Unix variants.
2125 .. method:: file.write(str)
2127 Write a string to the file. There is no return value. Due to buffering, the
2128 string may not actually show up in the file until the :meth:`flush` or
2129 :meth:`close` method is called.
2132 .. method:: file.writelines(sequence)
2134 Write a sequence of strings to the file. The sequence can be any iterable
2135 object producing strings, typically a list of strings. There is no return value.
2136 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2137 add line separators.)
2139 Files support the iterator protocol. Each iteration returns the same result as
2140 ``file.readline()``, and iteration ends when the :meth:`readline` method returns
2143 File objects also offer a number of other interesting attributes. These are not
2144 required for file-like objects, but should be implemented if they make sense for
2145 the particular object.
2148 .. attribute:: file.closed
2150 bool indicating the current state of the file object. This is a read-only
2151 attribute; the :meth:`close` method changes the value. It may not be available
2152 on all file-like objects.
2155 .. attribute:: file.encoding
2157 The encoding that this file uses. When Unicode strings are written to a file,
2158 they will be converted to byte strings using this encoding. In addition, when
2159 the file is connected to a terminal, the attribute gives the encoding that the
2160 terminal is likely to use (that information might be incorrect if the user has
2161 misconfigured the terminal). The attribute is read-only and may not be present
2162 on all file-like objects. It may also be ``None``, in which case the file uses
2163 the system default encoding for converting Unicode strings.
2165 .. versionadded:: 2.3
2168 .. attribute:: file.mode
2170 The I/O mode for the file. If the file was created using the :func:`open`
2171 built-in function, this will be the value of the *mode* parameter. This is a
2172 read-only attribute and may not be present on all file-like objects.
2175 .. attribute:: file.name
2177 If the file object was created using :func:`open`, the name of the file.
2178 Otherwise, some string that indicates the source of the file object, of the
2179 form ``<...>``. This is a read-only attribute and may not be present on all
2183 .. attribute:: file.newlines
2185 If Python was built with the :option:`--with-universal-newlines` option to
2186 :program:`configure` (the default) this read-only attribute exists, and for
2187 files opened in universal newline read mode it keeps track of the types of
2188 newlines encountered while reading the file. The values it can take are
2189 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2190 tuple containing all the newline types seen, to indicate that multiple newline
2191 conventions were encountered. For files not opened in universal newline read
2192 mode the value of this attribute will be ``None``.
2195 .. attribute:: file.softspace
2197 Boolean that indicates whether a space character needs to be printed before
2198 another value when using the :keyword:`print` statement. Classes that are trying
2199 to simulate a file object should also have a writable :attr:`softspace`
2200 attribute, which should be initialized to zero. This will be automatic for most
2201 classes implemented in Python (care may be needed for objects that override
2202 attribute access); types implemented in C will have to provide a writable
2203 :attr:`softspace` attribute.
2207 This attribute is not used to control the :keyword:`print` statement, but to
2208 allow the implementation of :keyword:`print` to keep track of its internal
2212 .. _typecontextmanager:
2214 Context Manager Types
2215 =====================
2217 .. versionadded:: 2.5
2220 single: context manager
2221 single: context management protocol
2222 single: protocol; context management
2224 Python's :keyword:`with` statement supports the concept of a runtime context
2225 defined by a context manager. This is implemented using two separate methods
2226 that allow user-defined classes to define a runtime context that is entered
2227 before the statement body is executed and exited when the statement ends.
2229 The :dfn:`context management protocol` consists of a pair of methods that need
2230 to be provided for a context manager object to define a runtime context:
2233 .. method:: contextmanager.__enter__()
2235 Enter the runtime context and return either this object or another object
2236 related to the runtime context. The value returned by this method is bound to
2237 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2238 this context manager.
2240 An example of a context manager that returns itself is a file object. File
2241 objects return themselves from __enter__() to allow :func:`open` to be used as
2242 the context expression in a :keyword:`with` statement.
2244 An example of a context manager that returns a related object is the one
2245 returned by :func:`decimal.localcontext`. These managers set the active
2246 decimal context to a copy of the original decimal context and then return the
2247 copy. This allows changes to be made to the current decimal context in the body
2248 of the :keyword:`with` statement without affecting code outside the
2249 :keyword:`with` statement.
2252 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2254 Exit the runtime context and return a Boolean flag indicating if any exception
2255 that occurred should be suppressed. If an exception occurred while executing the
2256 body of the :keyword:`with` statement, the arguments contain the exception type,
2257 value and traceback information. Otherwise, all three arguments are ``None``.
2259 Returning a true value from this method will cause the :keyword:`with` statement
2260 to suppress the exception and continue execution with the statement immediately
2261 following the :keyword:`with` statement. Otherwise the exception continues
2262 propagating after this method has finished executing. Exceptions that occur
2263 during execution of this method will replace any exception that occurred in the
2264 body of the :keyword:`with` statement.
2266 The exception passed in should never be reraised explicitly - instead, this
2267 method should return a false value to indicate that the method completed
2268 successfully and does not want to suppress the raised exception. This allows
2269 context management code (such as ``contextlib.nested``) to easily detect whether
2270 or not an :meth:`__exit__` method has actually failed.
2272 Python defines several context managers to support easy thread synchronisation,
2273 prompt closure of files or other objects, and simpler manipulation of the active
2274 decimal arithmetic context. The specific types are not treated specially beyond
2275 their implementation of the context management protocol. See the
2276 :mod:`contextlib` module for some examples.
2278 Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
2279 provide a convenient way to implement these protocols. If a generator function is
2280 decorated with the ``contextlib.contextfactory`` decorator, it will return a
2281 context manager implementing the necessary :meth:`__enter__` and
2282 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2285 Note that there is no specific slot for any of these methods in the type
2286 structure for Python objects in the Python/C API. Extension types wanting to
2287 define these methods must provide them as a normal Python accessible method.
2288 Compared to the overhead of setting up the runtime context, the overhead of a
2289 single class dictionary lookup is negligible.
2294 Other Built-in Types
2295 ====================
2297 The interpreter supports several other kinds of objects. Most of these support
2298 only one or two operations.
2306 The only special operation on a module is attribute access: ``m.name``, where
2307 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
2308 Module attributes can be assigned to. (Note that the :keyword:`import`
2309 statement is not, strictly speaking, an operation on a module object; ``import
2310 foo`` does not require a module object named *foo* to exist, rather it requires
2311 an (external) *definition* for a module named *foo* somewhere.)
2313 A special member of every module is :attr:`__dict__`. This is the dictionary
2314 containing the module's symbol table. Modifying this dictionary will actually
2315 change the module's symbol table, but direct assignment to the :attr:`__dict__`
2316 attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2317 ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2318 :attr:`__dict__` directly is not recommended.
2320 Modules built into the interpreter are written like this: ``<module 'sys'
2321 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2322 '/usr/local/lib/pythonX.Y/os.pyc'>``.
2327 Classes and Class Instances
2328 ---------------------------
2330 See :ref:`objects` and :ref:`class` for these.
2338 Function objects are created by function definitions. The only operation on a
2339 function object is to call it: ``func(argument-list)``.
2341 There are really two flavors of function objects: built-in functions and
2342 user-defined functions. Both support the same operation (to call the function),
2343 but the implementation is different, hence the different object types.
2345 See :ref:`function` for more information.
2353 .. index:: object: method
2355 Methods are functions that are called using the attribute notation. There are
2356 two flavors: built-in methods (such as :meth:`append` on lists) and class
2357 instance methods. Built-in methods are described with the types that support
2360 The implementation adds two special read-only attributes to class instance
2361 methods: ``m.im_self`` is the object on which the method operates, and
2362 ``m.im_func`` is the function implementing the method. Calling ``m(arg-1,
2363 arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
2364 arg-1, arg-2, ..., arg-n)``.
2366 Class instance methods are either *bound* or *unbound*, referring to whether the
2367 method was accessed through an instance or a class, respectively. When a method
2368 is unbound, its ``im_self`` attribute will be ``None`` and if called, an
2369 explicit ``self`` object must be passed as the first argument. In this case,
2370 ``self`` must be an instance of the unbound method's class (or a subclass of
2371 that class), otherwise a :exc:`TypeError` is raised.
2373 Like function objects, methods objects support getting arbitrary attributes.
2374 However, since method attributes are actually stored on the underlying function
2375 object (``meth.im_func``), setting method attributes on either bound or unbound
2376 methods is disallowed. Attempting to set a method attribute results in a
2377 :exc:`TypeError` being raised. In order to set a method attribute, you need to
2378 explicitly set it on the underlying function object::
2385 c.method.im_func.whoami = 'my name is c'
2387 See :ref:`types` for more information.
2390 .. _bltin-code-objects:
2395 .. index:: object: code
2399 single: func_code (function object attribute)
2401 Code objects are used by the implementation to represent "pseudo-compiled"
2402 executable Python code such as a function body. They differ from function
2403 objects because they don't contain a reference to their global execution
2404 environment. Code objects are returned by the built-in :func:`compile` function
2405 and can be extracted from function objects through their :attr:`func_code`
2406 attribute. See also the :mod:`code` module.
2412 A code object can be executed or evaluated by passing it (instead of a source
2413 string) to the :keyword:`exec` statement or the built-in :func:`eval` function.
2415 See :ref:`types` for more information.
2418 .. _bltin-type-objects:
2427 Type objects represent the various object types. An object's type is accessed
2428 by the built-in function :func:`type`. There are no special operations on
2429 types. The standard module :mod:`types` defines names for all standard built-in
2432 Types are written like this: ``<type 'int'>``.
2435 .. _bltin-null-object:
2440 This object is returned by functions that don't explicitly return a value. It
2441 supports no special operations. There is exactly one null object, named
2442 ``None`` (a built-in name).
2444 It is written as ``None``.
2447 .. _bltin-ellipsis-object:
2452 This object is used by extended slice notation (see :ref:`slicings`). It
2453 supports no special operations. There is exactly one ellipsis object, named
2454 :const:`Ellipsis` (a built-in name).
2456 It is written as ``Ellipsis``.
2462 Boolean values are the two constant objects ``False`` and ``True``. They are
2463 used to represent truth values (although other values can also be considered
2464 false or true). In numeric contexts (for example when used as the argument to
2465 an arithmetic operator), they behave like the integers 0 and 1, respectively.
2466 The built-in function :func:`bool` can be used to cast any value to a Boolean,
2467 if the value can be interpreted as a truth value (see section Truth Value
2473 pair: Boolean; values
2475 They are written as ``False`` and ``True``, respectively.
2483 See :ref:`types` for this information. It describes stack frame objects,
2484 traceback objects, and slice objects.
2492 The implementation adds a few special read-only attributes to several object
2493 types, where they are relevant. Some of these are not reported by the
2494 :func:`dir` built-in function.
2497 .. attribute:: object.__dict__
2499 A dictionary or other mapping object used to store an object's (writable)
2503 .. attribute:: object.__methods__
2506 Use the built-in function :func:`dir` to get a list of an object's attributes.
2507 This attribute is no longer available.
2510 .. attribute:: object.__members__
2513 Use the built-in function :func:`dir` to get a list of an object's attributes.
2514 This attribute is no longer available.
2517 .. attribute:: instance.__class__
2519 The class to which a class instance belongs.
2522 .. attribute:: class.__bases__
2524 The tuple of base classes of a class object. If there are no base classes, this
2525 will be an empty tuple.
2528 .. attribute:: class.__name__
2530 The name of the class or type.
2532 .. rubric:: Footnotes
2534 .. [#] Additional information on these special methods may be found in the Python
2535 Reference Manual (:ref:`customization`).
2537 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2538 similarly for tuples.
2540 .. [#] They must have since the parser can't tell the type of the operands.
2542 .. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2543 element is the tuple to be formatted.
2545 .. [#] These numbers are fairly arbitrary. They are intended to avoid printing endless
2546 strings of meaningless digits without hampering correct use and without having
2547 to know the exact precision of floating point values on a particular machine.
2549 .. [#] The advantage of leaving the newline on is that returning an empty string is
2550 then an unambiguous EOF indication. It is also possible (in cases where it
2551 might matter, for example, if you want to make an exact copy of a file while
2552 scanning its lines) to tell whether the last line of a file ended in a newline
2553 or not (yes this happens!).