blob: 1e2c47cd7f531575367b676202f5fe4752f9b22f [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. XXX: reference/datamodel and this have quite a few overlaps!
2
3
4.. _bltin-types:
5
6**************
7Built-in Types
8**************
9
10The following sections describe the standard types that are built into the
11interpreter.
12
Georg Brandl116aa622007-08-15 14:28:22 +000013.. index:: pair: built-in; types
14
Antoine Pitroub1a18102009-12-19 18:23:15 +000015The principal built-in types are numerics, sequences, mappings, classes,
Georg Brandl116aa622007-08-15 14:28:22 +000016instances and exceptions.
17
Georg Brandl116aa622007-08-15 14:28:22 +000018Some operations are supported by several object types; in particular,
19practically all objects can be compared, tested for truth value, and converted
20to a string (with the :func:`repr` function or the slightly different
21:func:`str` function). The latter function is implicitly used when an object is
22written by the :func:`print` function.
23
24
25.. _truth:
26
27Truth Value Testing
28===================
29
30.. index::
31 statement: if
32 statement: while
33 pair: truth; value
34 pair: Boolean; operations
35 single: false
36
37Any object can be tested for truth value, for use in an :keyword:`if` or
38:keyword:`while` condition or as operand of the Boolean operations below. The
39following values are considered false:
40
41 .. index:: single: None (Built-in object)
42
43* ``None``
44
45 .. index:: single: False (Built-in object)
46
47* ``False``
48
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +000049* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51* any empty sequence, for example, ``''``, ``()``, ``[]``.
52
53* any empty mapping, for example, ``{}``.
54
55* instances of user-defined classes, if the class defines a :meth:`__bool__` or
56 :meth:`__len__` method, when that method returns the integer zero or
57 :class:`bool` value ``False``. [#]_
58
59.. index:: single: true
60
61All other values are considered true --- so objects of many types are always
62true.
63
64.. index::
65 operator: or
66 operator: and
67 single: False
68 single: True
69
70Operations and built-in functions that have a Boolean result always return ``0``
71or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
72(Important exception: the Boolean operations ``or`` and ``and`` always return
73one of their operands.)
74
75
76.. _boolean:
77
78Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
79====================================================================
80
81.. index:: pair: Boolean; operations
82
83These are the Boolean operations, ordered by ascending priority:
84
85+-------------+---------------------------------+-------+
86| Operation | Result | Notes |
87+=============+=================================+=======+
88| ``x or y`` | if *x* is false, then *y*, else | \(1) |
89| | *x* | |
90+-------------+---------------------------------+-------+
91| ``x and y`` | if *x* is false, then *x*, else | \(2) |
92| | *y* | |
93+-------------+---------------------------------+-------+
94| ``not x`` | if *x* is false, then ``True``, | \(3) |
95| | else ``False`` | |
96+-------------+---------------------------------+-------+
97
98.. index::
99 operator: and
100 operator: or
101 operator: not
102
103Notes:
104
105(1)
106 This is a short-circuit operator, so it only evaluates the second
107 argument if the first one is :const:`False`.
108
109(2)
110 This is a short-circuit operator, so it only evaluates the second
111 argument if the first one is :const:`True`.
112
113(3)
114 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
115 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
116
117
118.. _stdcomparisons:
119
120Comparisons
121===========
122
Georg Brandlc5605df2009-08-13 08:26:44 +0000123.. index::
124 pair: chaining; comparisons
125 pair: operator; comparison
126 operator: ==
127 operator: <
128 operator: <=
129 operator: >
130 operator: >=
131 operator: !=
132 operator: is
133 operator: is not
Georg Brandl116aa622007-08-15 14:28:22 +0000134
Georg Brandl905ec322007-09-28 13:39:25 +0000135There are eight comparison operations in Python. They all have the same
136priority (which is higher than that of the Boolean operations). Comparisons can
Georg Brandl116aa622007-08-15 14:28:22 +0000137be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
138y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
139evaluated at all when ``x < y`` is found to be false).
140
141This table summarizes the comparison operations:
142
Georg Brandlfd855162008-01-07 09:13:03 +0000143+------------+-------------------------+
144| Operation | Meaning |
145+============+=========================+
146| ``<`` | strictly less than |
147+------------+-------------------------+
148| ``<=`` | less than or equal |
149+------------+-------------------------+
150| ``>`` | strictly greater than |
151+------------+-------------------------+
152| ``>=`` | greater than or equal |
153+------------+-------------------------+
154| ``==`` | equal |
155+------------+-------------------------+
156| ``!=`` | not equal |
157+------------+-------------------------+
158| ``is`` | object identity |
159+------------+-------------------------+
160| ``is not`` | negated object identity |
161+------------+-------------------------+
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000162
163.. index::
Georg Brandl116aa622007-08-15 14:28:22 +0000164 pair: object; numeric
165 pair: objects; comparing
166
Georg Brandl905ec322007-09-28 13:39:25 +0000167Objects of different types, except different numeric types, never compare equal.
Antoine Pitroub1a18102009-12-19 18:23:15 +0000168Furthermore, some types (for example, function objects) support only a degenerate
Georg Brandl905ec322007-09-28 13:39:25 +0000169notion of comparison where any two objects of that type are unequal. The ``<``,
170``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when
171any operand is a complex number, the objects are of different types that cannot
172be compared, or other cases where there is no defined ordering.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Georg Brandl48310cd2009-01-03 21:18:54 +0000174.. index::
Georg Brandl905ec322007-09-28 13:39:25 +0000175 single: __eq__() (instance method)
176 single: __ne__() (instance method)
177 single: __lt__() (instance method)
178 single: __le__() (instance method)
179 single: __gt__() (instance method)
180 single: __ge__() (instance method)
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Georg Brandl05f5ab72008-09-24 09:11:47 +0000182Non-identical instances of a class normally compare as non-equal unless the
183class defines the :meth:`__eq__` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Georg Brandl905ec322007-09-28 13:39:25 +0000185Instances of a class cannot be ordered with respect to other instances of the
186same class, or other types of object, unless the class defines enough of the
Georg Brandl05f5ab72008-09-24 09:11:47 +0000187methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in
188general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the
189conventional meanings of the comparison operators).
Georg Brandl905ec322007-09-28 13:39:25 +0000190
191The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
192customized; also they can be applied to any two objects and never raise an
193exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195.. index::
196 operator: in
197 operator: not in
198
199Two more operations with the same syntactic priority, ``in`` and ``not in``, are
200supported only by sequence types (below).
201
202
203.. _typesnumeric:
204
Georg Brandl905ec322007-09-28 13:39:25 +0000205Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
206================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208.. index::
209 object: numeric
210 object: Boolean
211 object: integer
Georg Brandl116aa622007-08-15 14:28:22 +0000212 object: floating point
213 object: complex number
214 pair: C; language
215
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000216There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
217point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
218subtype of integers. Integers have unlimited precision. Floating point
Mark Dickinsone56a3862010-08-04 18:43:36 +0000219numbers are usually implemented using :ctype:`double` in C; information
220about the precision and internal representation of floating point
221numbers for the machine on which your program is running is available
222in :data:`sys.float_info`. Complex numbers have a real and imaginary
223part, which are each a floating point number. To extract these parts
224from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard
225library includes additional numeric types, :mod:`fractions` that hold
226rationals, and :mod:`decimal` that hold floating-point numbers with
227user-definable precision.)
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229.. index::
230 pair: numeric; literals
231 pair: integer; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000232 pair: floating point; literals
233 pair: complex number; literals
234 pair: hexadecimal; literals
235 pair: octal; literals
Neal Norwitz1d2aef52007-10-02 07:26:14 +0000236 pair: binary; literals
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238Numbers are created by numeric literals or as the result of built-in functions
Georg Brandl905ec322007-09-28 13:39:25 +0000239and operators. Unadorned integer literals (including hex, octal and binary
240numbers) yield integers. Numeric literals containing a decimal point or an
241exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a
242numeric literal yields an imaginary number (a complex number with a zero real
243part) which you can add to an integer or float to get a complex number with real
244and imaginary parts.
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246.. index::
247 single: arithmetic
248 builtin: int
Georg Brandl116aa622007-08-15 14:28:22 +0000249 builtin: float
250 builtin: complex
Georg Brandlc5605df2009-08-13 08:26:44 +0000251 operator: +
252 operator: -
253 operator: *
254 operator: /
255 operator: //
256 operator: %
257 operator: **
Georg Brandl116aa622007-08-15 14:28:22 +0000258
259Python fully supports mixed arithmetic: when a binary arithmetic operator has
260operands of different numeric types, the operand with the "narrower" type is
Georg Brandl905ec322007-09-28 13:39:25 +0000261widened to that of the other, where integer is narrower than floating point,
262which is narrower than complex. Comparisons between numbers of mixed type use
263the same rule. [#]_ The constructors :func:`int`, :func:`float`, and
264:func:`complex` can be used to produce numbers of a specific type.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266All numeric types (except complex) support the following operations, sorted by
267ascending priority (operations in the same box have the same priority; all
268numeric operations have a higher priority than comparison operations):
269
Georg Brandl905ec322007-09-28 13:39:25 +0000270+---------------------+---------------------------------+-------+--------------------+
271| Operation | Result | Notes | Full documentation |
Neal Norwitz1d2aef52007-10-02 07:26:14 +0000272+=====================+=================================+=======+====================+
Georg Brandl905ec322007-09-28 13:39:25 +0000273| ``x + y`` | sum of *x* and *y* | | |
274+---------------------+---------------------------------+-------+--------------------+
275| ``x - y`` | difference of *x* and *y* | | |
276+---------------------+---------------------------------+-------+--------------------+
277| ``x * y`` | product of *x* and *y* | | |
278+---------------------+---------------------------------+-------+--------------------+
279| ``x / y`` | quotient of *x* and *y* | | |
280+---------------------+---------------------------------+-------+--------------------+
281| ``x // y`` | floored quotient of *x* and | \(1) | |
282| | *y* | | |
283+---------------------+---------------------------------+-------+--------------------+
284| ``x % y`` | remainder of ``x / y`` | \(2) | |
285+---------------------+---------------------------------+-------+--------------------+
286| ``-x`` | *x* negated | | |
287+---------------------+---------------------------------+-------+--------------------+
288| ``+x`` | *x* unchanged | | |
289+---------------------+---------------------------------+-------+--------------------+
290| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
291| | *x* | | |
292+---------------------+---------------------------------+-------+--------------------+
293| ``int(x)`` | *x* converted to integer | \(3) | :func:`int` |
294+---------------------+---------------------------------+-------+--------------------+
Georg Brandl74f36692008-01-06 17:39:49 +0000295| ``float(x)`` | *x* converted to floating point | \(4) | :func:`float` |
Georg Brandl905ec322007-09-28 13:39:25 +0000296+---------------------+---------------------------------+-------+--------------------+
297| ``complex(re, im)`` | a complex number with real part | | :func:`complex` |
298| | *re*, imaginary part *im*. | | |
299| | *im* defaults to zero. | | |
300+---------------------+---------------------------------+-------+--------------------+
301| ``c.conjugate()`` | conjugate of the complex number | | |
302| | *c* | | |
303+---------------------+---------------------------------+-------+--------------------+
304| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
305+---------------------+---------------------------------+-------+--------------------+
Georg Brandl60fe2f12008-01-07 09:16:46 +0000306| ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
Georg Brandl905ec322007-09-28 13:39:25 +0000307+---------------------+---------------------------------+-------+--------------------+
Georg Brandl60fe2f12008-01-07 09:16:46 +0000308| ``x ** y`` | *x* to the power *y* | \(5) | |
Georg Brandl905ec322007-09-28 13:39:25 +0000309+---------------------+---------------------------------+-------+--------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. index::
312 triple: operations on; numeric; types
313 single: conjugate() (complex number method)
314
315Notes:
316
317(1)
Georg Brandl905ec322007-09-28 13:39:25 +0000318 Also referred to as integer division. The resultant value is a whole
319 integer, though the result's type is not necessarily int. The result is
320 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
321 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323(2)
Georg Brandl905ec322007-09-28 13:39:25 +0000324 Not for complex numbers. Instead convert to floats using :func:`abs` if
325 appropriate.
326
327(3)
Georg Brandl116aa622007-08-15 14:28:22 +0000328 .. index::
329 module: math
330 single: floor() (in module math)
331 single: ceil() (in module math)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000332 single: trunc() (in module math)
Georg Brandl116aa622007-08-15 14:28:22 +0000333 pair: numeric; conversions
334 pair: C; language
335
Georg Brandlba956ae2007-11-29 17:24:34 +0000336 Conversion from floating point to integer may round or truncate
Georg Brandl116aa622007-08-15 14:28:22 +0000337 as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
338 for well-defined conversions.
339
Georg Brandl74f36692008-01-06 17:39:49 +0000340(4)
Georg Brandl48310cd2009-01-03 21:18:54 +0000341 float also accepts the strings "nan" and "inf" with an optional prefix "+"
Christian Heimes99170a52007-12-19 02:07:34 +0000342 or "-" for Not a Number (NaN) and positive or negative infinity.
Christian Heimes7f044312008-01-06 17:05:40 +0000343
Georg Brandl74f36692008-01-06 17:39:49 +0000344(5)
Christian Heimes7f044312008-01-06 17:05:40 +0000345 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
346 programming languages.
347
Georg Brandl48310cd2009-01-03 21:18:54 +0000348
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000349
Christian Heimesfaf2f632008-01-06 16:59:19 +0000350All :class:`numbers.Real` types (:class:`int` and
351:class:`float`) also include the following operations:
352
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000353+--------------------+------------------------------------+--------+
354| Operation | Result | Notes |
355+====================+====================================+========+
356| ``math.trunc(x)`` | *x* truncated to Integral | |
357+--------------------+------------------------------------+--------+
358| ``round(x[, n])`` | *x* rounded to n digits, | |
359| | rounding half to even. If n is | |
360| | omitted, it defaults to 0. | |
361+--------------------+------------------------------------+--------+
362| ``math.floor(x)`` | the greatest integral float <= *x* | |
363+--------------------+------------------------------------+--------+
364| ``math.ceil(x)`` | the least integral float >= *x* | |
365+--------------------+------------------------------------+--------+
Christian Heimesfaf2f632008-01-06 16:59:19 +0000366
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000367For additional numeric operations see the :mod:`math` and :mod:`cmath`
368modules.
369
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000370.. XXXJH exceptions: overflow (when? what operations?) zerodivision
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372
373.. _bitstring-ops:
374
375Bit-string Operations on Integer Types
376--------------------------------------
377
Georg Brandlc5605df2009-08-13 08:26:44 +0000378.. index::
379 triple: operations on; integer; types
380 pair: bit-string; operations
381 pair: shifting; operations
382 pair: masking; operations
383 operator: ^
384 operator: &
385 operator: <<
386 operator: >>
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Georg Brandl905ec322007-09-28 13:39:25 +0000388Integers support additional operations that make sense only for bit-strings.
389Negative numbers are treated as their 2's complement value (this assumes a
390sufficiently large number of bits that no overflow occurs during the operation).
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Christian Heimesfaf2f632008-01-06 16:59:19 +0000392The priorities of the binary bitwise operations are all lower than the numeric
Georg Brandl116aa622007-08-15 14:28:22 +0000393operations and higher than the comparisons; the unary operation ``~`` has the
394same priority as the other unary numeric operations (``+`` and ``-``).
395
396This table lists the bit-string operations sorted in ascending priority
397(operations in the same box have the same priority):
398
399+------------+--------------------------------+----------+
400| Operation | Result | Notes |
401+============+================================+==========+
402| ``x | y`` | bitwise :dfn:`or` of *x* and | |
403| | *y* | |
404+------------+--------------------------------+----------+
405| ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
406| | *x* and *y* | |
407+------------+--------------------------------+----------+
408| ``x & y`` | bitwise :dfn:`and` of *x* and | |
409| | *y* | |
410+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000411| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
Georg Brandl116aa622007-08-15 14:28:22 +0000412+------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000413| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000414+------------+--------------------------------+----------+
415| ``~x`` | the bits of *x* inverted | |
416+------------+--------------------------------+----------+
417
Georg Brandl116aa622007-08-15 14:28:22 +0000418Notes:
419
420(1)
421 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
422
423(2)
424 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
425 without overflow check.
426
427(3)
428 A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
429 overflow check.
430
431
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000432Additional Methods on Integer Types
433-----------------------------------
434
435.. method:: int.bit_length()
436
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000437 Return the number of bits necessary to represent an integer in binary,
438 excluding the sign and leading zeros::
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000439
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000440 >>> n = -37
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000441 >>> bin(n)
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000442 '-0b100101'
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000443 >>> n.bit_length()
444 6
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000445
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000446 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
447 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
448 Equivalently, when ``abs(x)`` is small enough to have a correctly
449 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
450 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000451
452 Equivalent to::
453
454 def bit_length(self):
Senthil Kumaranfd512702010-06-22 02:46:49 +0000455 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
Raymond Hettingerd3e18b72008-12-19 09:11:49 +0000456 s = s.lstrip('-0b') # remove leading zeros and minus sign
457 return len(s) # len('100101') --> 6
Mark Dickinson54bc1ec2008-12-17 16:19:07 +0000458
459 .. versionadded:: 3.1
460
461
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000462Additional Methods on Float
463---------------------------
464
Benjamin Petersond7b03282008-09-13 15:58:53 +0000465The float type has some additional methods.
466
467.. method:: float.as_integer_ratio()
468
469 Return a pair of integers whose ratio is exactly equal to the
470 original float and with a positive denominator. Raises
471 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
472 NaNs.
Georg Brandl48310cd2009-01-03 21:18:54 +0000473
Benjamin Petersond7b03282008-09-13 15:58:53 +0000474Two methods support conversion to
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000475and from hexadecimal strings. Since Python's floats are stored
476internally as binary numbers, converting a float to or from a
477*decimal* string usually involves a small rounding error. In
478contrast, hexadecimal strings allow exact representation and
479specification of floating-point numbers. This can be useful when
480debugging, and in numerical work.
481
482
483.. method:: float.hex()
484
485 Return a representation of a floating-point number as a hexadecimal
486 string. For finite floating-point numbers, this representation
487 will always include a leading ``0x`` and a trailing ``p`` and
488 exponent.
489
490
Georg Brandlabc38772009-04-12 15:51:51 +0000491.. classmethod:: float.fromhex(s)
Mark Dickinson65fe25e2008-07-16 11:30:51 +0000492
493 Class method to return the float represented by a hexadecimal
494 string *s*. The string *s* may have leading and trailing
495 whitespace.
496
497
498Note that :meth:`float.hex` is an instance method, while
499:meth:`float.fromhex` is a class method.
500
501A hexadecimal string takes the form::
502
503 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
504
505where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
506and ``fraction`` are strings of hexadecimal digits, and ``exponent``
507is a decimal integer with an optional leading sign. Case is not
508significant, and there must be at least one hexadecimal digit in
509either the integer or the fraction. This syntax is similar to the
510syntax specified in section 6.4.4.2 of the C99 standard, and also to
511the syntax used in Java 1.5 onwards. In particular, the output of
512:meth:`float.hex` is usable as a hexadecimal floating-point literal in
513C or Java code, and hexadecimal strings produced by C's ``%a`` format
514character or Java's ``Double.toHexString`` are accepted by
515:meth:`float.fromhex`.
516
517
518Note that the exponent is written in decimal rather than hexadecimal,
519and that it gives the power of 2 by which to multiply the coefficient.
520For example, the hexadecimal string ``0x3.a7p10`` represents the
521floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
522``3740.0``::
523
524 >>> float.fromhex('0x3.a7p10')
525 3740.0
526
527
528Applying the reverse conversion to ``3740.0`` gives a different
529hexadecimal string representing the same number::
530
531 >>> float.hex(3740.0)
532 '0x1.d380000000000p+11'
533
534
Georg Brandl6ea420b2008-07-16 12:58:29 +0000535.. _typeiter:
536
Georg Brandl116aa622007-08-15 14:28:22 +0000537Iterator Types
538==============
539
Georg Brandl116aa622007-08-15 14:28:22 +0000540.. index::
541 single: iterator protocol
542 single: protocol; iterator
543 single: sequence; iteration
544 single: container; iteration over
545
546Python supports a concept of iteration over containers. This is implemented
547using two distinct methods; these are used to allow user-defined classes to
548support iteration. Sequences, described below in more detail, always support
549the iteration methods.
550
551One method needs to be defined for container objects to provide iteration
552support:
553
Christian Heimes790c8232008-01-07 21:14:23 +0000554.. XXX duplicated in reference/datamodel!
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Christian Heimes790c8232008-01-07 21:14:23 +0000556.. method:: container.__iter__()
Georg Brandl116aa622007-08-15 14:28:22 +0000557
558 Return an iterator object. The object is required to support the iterator
559 protocol described below. If a container supports different types of
560 iteration, additional methods can be provided to specifically request
561 iterators for those iteration types. (An example of an object supporting
562 multiple forms of iteration would be a tree structure which supports both
563 breadth-first and depth-first traversal.) This method corresponds to the
564 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
565 API.
566
567The iterator objects themselves are required to support the following two
568methods, which together form the :dfn:`iterator protocol`:
569
570
571.. method:: iterator.__iter__()
572
573 Return the iterator object itself. This is required to allow both containers
574 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
575 This method corresponds to the :attr:`tp_iter` slot of the type structure for
576 Python objects in the Python/C API.
577
578
Georg Brandl905ec322007-09-28 13:39:25 +0000579.. method:: iterator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581 Return the next item from the container. If there are no further items, raise
582 the :exc:`StopIteration` exception. This method corresponds to the
583 :attr:`tp_iternext` slot of the type structure for Python objects in the
584 Python/C API.
585
586Python defines several iterator objects to support iteration over general and
587specific sequence types, dictionaries, and other more specialized forms. The
588specific types are not important beyond their implementation of the iterator
589protocol.
590
Georg Brandl905ec322007-09-28 13:39:25 +0000591Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must
592continue to do so on subsequent calls. Implementations that do not obey this
593property are deemed broken.
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Benjamin Petersond76c8da2009-06-28 17:35:48 +0000595
596.. _generator-types:
597
598Generator Types
599---------------
600
Georg Brandl9afde1c2007-11-01 20:32:30 +0000601Python's :term:`generator`\s provide a convenient way to implement the iterator
602protocol. If a container object's :meth:`__iter__` method is implemented as a
603generator, it will automatically return an iterator object (technically, a
604generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods.
Benjamin Petersond76c8da2009-06-28 17:35:48 +0000605More information about generators can be found in :ref:`the documentation for
606the yield expression <yieldexpr>`.
Georg Brandl116aa622007-08-15 14:28:22 +0000607
608
609.. _typesseq:
610
Georg Brandl95414632007-11-22 11:00:28 +0000611Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`list`, :class:`tuple`, :class:`range`
612==================================================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000613
Georg Brandle17d5862009-01-18 10:40:25 +0000614There are six sequence types: strings, byte sequences (:class:`bytes` objects),
Benjamin Petersonb58dda72009-01-18 22:27:04 +0000615byte arrays (:class:`bytearray` objects), lists, tuples, and range objects. For
616other containers see the built in :class:`dict` and :class:`set` classes, and
617the :mod:`collections` module.
Georg Brandle17d5862009-01-18 10:40:25 +0000618
Georg Brandl116aa622007-08-15 14:28:22 +0000619
620.. index::
621 object: sequence
622 object: string
Georg Brandl4b491312007-08-31 09:22:56 +0000623 object: bytes
Georg Brandle17d5862009-01-18 10:40:25 +0000624 object: bytearray
Georg Brandl116aa622007-08-15 14:28:22 +0000625 object: tuple
626 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000627 object: range
628
Georg Brandl7c676132007-10-23 18:17:00 +0000629Strings contain Unicode characters. Their literals are written in single or
630double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about
631string literals. In addition to the functionality described here, there are
632also string-specific methods described in the :ref:`string-methods` section.
633
Georg Brandl95414632007-11-22 11:00:28 +0000634Bytes and bytearray objects contain single bytes -- the former is immutable
Georg Brandl18da8f02008-07-01 20:08:02 +0000635while the latter is a mutable sequence. Bytes objects can be constructed the
636constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal
637string syntax: ``b'xyzzy'``. To construct byte arrays, use the
638:func:`bytearray` function.
Georg Brandl4b491312007-08-31 09:22:56 +0000639
Georg Brandl226878c2007-08-31 10:15:37 +0000640.. warning::
Georg Brandl4b491312007-08-31 09:22:56 +0000641
642 While string objects are sequences of characters (represented by strings of
Georg Brandl95414632007-11-22 11:00:28 +0000643 length 1), bytes and bytearray objects are sequences of *integers* (between 0
Georg Brandl7c676132007-10-23 18:17:00 +0000644 and 255), representing the ASCII value of single bytes. That means that for
Georg Brandl18da8f02008-07-01 20:08:02 +0000645 a bytes or bytearray object *b*, ``b[0]`` will be an integer, while
646 ``b[0:1]`` will be a bytes or bytearray object of length 1. The
647 representation of bytes objects uses the literal format (``b'...'``) since it
648 is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always
649 convert a bytes object into a list of integers using ``list(b)``.
Georg Brandl4b491312007-08-31 09:22:56 +0000650
Georg Brandl2326a792007-09-01 12:08:51 +0000651 Also, while in previous Python versions, byte strings and Unicode strings
652 could be exchanged for each other rather freely (barring encoding issues),
Georg Brandl7c676132007-10-23 18:17:00 +0000653 strings and bytes are now completely separate concepts. There's no implicit
Ezio Melotti4cadc7f2009-12-31 12:26:02 +0000654 en-/decoding if you pass an object of the wrong type. A string always
Georg Brandl95414632007-11-22 11:00:28 +0000655 compares unequal to a bytes or bytearray object.
Georg Brandl2326a792007-09-01 12:08:51 +0000656
Georg Brandl4b491312007-08-31 09:22:56 +0000657Lists are constructed with square brackets, separating items with commas: ``[a,
658b, c]``. Tuples are constructed by the comma operator (not within square
659brackets), with or without enclosing parentheses, but an empty tuple must have
660the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple
661must have a trailing comma, such as ``(d,)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000662
Georg Brandl95414632007-11-22 11:00:28 +0000663Objects of type range are created using the :func:`range` function. They don't
664support slicing, concatenation or repetition, and using ``in``, ``not in``,
665:func:`min` or :func:`max` on them is inefficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000666
667Most sequence types support the following operations. The ``in`` and ``not in``
668operations have the same priorities as the comparison operations. The ``+`` and
669``*`` operations have the same priority as the corresponding numeric operations.
Christian Heimes043d6f62008-01-07 17:19:16 +0000670[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
Georg Brandl116aa622007-08-15 14:28:22 +0000671
672This table lists the sequence operations sorted in ascending priority
673(operations in the same box have the same priority). In the table, *s* and *t*
674are sequences of the same type; *n*, *i* and *j* are integers:
675
676+------------------+--------------------------------+----------+
677| Operation | Result | Notes |
678+==================+================================+==========+
679| ``x in s`` | ``True`` if an item of *s* is | \(1) |
680| | equal to *x*, else ``False`` | |
681+------------------+--------------------------------+----------+
682| ``x not in s`` | ``False`` if an item of *s* is | \(1) |
683| | equal to *x*, else ``True`` | |
684+------------------+--------------------------------+----------+
685| ``s + t`` | the concatenation of *s* and | \(6) |
686| | *t* | |
687+------------------+--------------------------------+----------+
688| ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
689| | concatenated | |
690+------------------+--------------------------------+----------+
691| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
692+------------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000693| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
Georg Brandl116aa622007-08-15 14:28:22 +0000694+------------------+--------------------------------+----------+
Christian Heimes043d6f62008-01-07 17:19:16 +0000695| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
Georg Brandl116aa622007-08-15 14:28:22 +0000696| | with step *k* | |
697+------------------+--------------------------------+----------+
698| ``len(s)`` | length of *s* | |
699+------------------+--------------------------------+----------+
700| ``min(s)`` | smallest item of *s* | |
701+------------------+--------------------------------+----------+
702| ``max(s)`` | largest item of *s* | |
703+------------------+--------------------------------+----------+
704
Georg Brandl7c676132007-10-23 18:17:00 +0000705Sequence types also support comparisons. In particular, tuples and lists are
706compared lexicographically by comparing corresponding elements. This means that
Georg Brandl4b491312007-08-31 09:22:56 +0000707to compare equal, every element must compare equal and the two sequences must be
Georg Brandl7c676132007-10-23 18:17:00 +0000708of the same type and have the same length. (For full details see
Georg Brandl4b491312007-08-31 09:22:56 +0000709:ref:`comparisons` in the language reference.)
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711.. index::
712 triple: operations on; sequence; types
713 builtin: len
714 builtin: min
715 builtin: max
716 pair: concatenation; operation
717 pair: repetition; operation
718 pair: subscript; operation
719 pair: slice; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000720 operator: in
721 operator: not in
722
723Notes:
724
725(1)
Georg Brandl4b491312007-08-31 09:22:56 +0000726 When *s* is a string object, the ``in`` and ``not in`` operations act like a
727 substring test.
Georg Brandl116aa622007-08-15 14:28:22 +0000728
729(2)
730 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
731 sequence of the same type as *s*). Note also that the copies are shallow;
732 nested structures are not copied. This often haunts new Python programmers;
Christian Heimesfe337bf2008-03-23 21:54:12 +0000733 consider:
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735 >>> lists = [[]] * 3
736 >>> lists
737 [[], [], []]
738 >>> lists[0].append(3)
739 >>> lists
740 [[3], [3], [3]]
741
742 What has happened is that ``[[]]`` is a one-element list containing an empty
Christian Heimesfe337bf2008-03-23 21:54:12 +0000743 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
744 list. Modifying any of the elements of ``lists`` modifies this single list.
745 You can create a list of different lists this way:
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747 >>> lists = [[] for i in range(3)]
748 >>> lists[0].append(3)
749 >>> lists[1].append(5)
750 >>> lists[2].append(7)
751 >>> lists
752 [[3], [5], [7]]
753
754(3)
755 If *i* or *j* is negative, the index is relative to the end of the string:
Georg Brandl7c676132007-10-23 18:17:00 +0000756 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
757 still ``0``.
Georg Brandl116aa622007-08-15 14:28:22 +0000758
759(4)
760 The slice of *s* from *i* to *j* is defined as the sequence of items with index
761 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
762 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
763 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
764 empty.
765
766(5)
767 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
Christian Heimes2c181612007-12-17 20:04:13 +0000768 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
Georg Brandl116aa622007-08-15 14:28:22 +0000769 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
770 *j* is reached (but never including *j*). If *i* or *j* is greater than
771 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
772 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
773 If *k* is ``None``, it is treated like ``1``.
774
775(6)
Georg Brandl628e6f92009-10-27 20:24:45 +0000776 .. impl-detail::
777
778 If *s* and *t* are both strings, some Python implementations such as
779 CPython can usually perform an in-place optimization for assignments of
780 the form ``s = s + t`` or ``s += t``. When applicable, this optimization
781 makes quadratic run-time much less likely. This optimization is both
782 version and implementation dependent. For performance sensitive code, it
783 is preferable to use the :meth:`str.join` method which assures consistent
784 linear concatenation performance across versions and implementations.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Georg Brandl116aa622007-08-15 14:28:22 +0000786
787.. _string-methods:
788
789String Methods
790--------------
791
792.. index:: pair: string; methods
793
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000794String objects support the methods listed below. Note that none of these
795methods take keyword arguments.
796
797In addition, Python's strings support the sequence type methods described in
798the :ref:`typesseq` section. To output formatted strings, see the
799:ref:`string-formatting` section. Also, see the :mod:`re` module for string
800functions based on regular expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000801
802.. method:: str.capitalize()
803
Senthil Kumaran3592a462010-07-05 11:44:49 +0000804 Return a copy of the string with its first character capitalized and the
Senthil Kumaran317ac612010-07-06 03:03:34 +0000805 rest lowercased.
Georg Brandl116aa622007-08-15 14:28:22 +0000806
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808.. method:: str.center(width[, fillchar])
809
810 Return centered in a string of length *width*. Padding is done using the
811 specified *fillchar* (default is a space).
812
Georg Brandl116aa622007-08-15 14:28:22 +0000813
814.. method:: str.count(sub[, start[, end]])
815
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000816 Return the number of non-overlapping occurrences of substring *sub* in the
817 range [*start*, *end*]. Optional arguments *start* and *end* are
818 interpreted as in slice notation.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820
Georg Brandl226878c2007-08-31 10:15:37 +0000821.. method:: str.encode([encoding[, errors]])
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Georg Brandl4f5f98d2009-05-04 21:01:20 +0000823 Return an encoded version of the string as a bytes object. Default encoding
824 is the current default string encoding. *errors* may be given to set a
825 different error handling scheme. The default for *errors* is ``'strict'``,
826 meaning that encoding errors raise a :exc:`UnicodeError`. Other possible
827 values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``,
828 ``'backslashreplace'`` and any other name registered via
829 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
830 list of possible encodings, see section :ref:`standard-encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833.. method:: str.endswith(suffix[, start[, end]])
834
835 Return ``True`` if the string ends with the specified *suffix*, otherwise return
836 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
837 *start*, test beginning at that position. With optional *end*, stop comparing
838 at that position.
839
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841.. method:: str.expandtabs([tabsize])
842
Georg Brandl9afde1c2007-11-01 20:32:30 +0000843 Return a copy of the string where all tab characters are replaced by one or
844 more spaces, depending on the current column and the given tab size. The
845 column number is reset to zero after each newline occurring in the string.
846 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
847 doesn't understand other non-printing characters or escape sequences.
Georg Brandl116aa622007-08-15 14:28:22 +0000848
849
850.. method:: str.find(sub[, start[, end]])
851
Benjamin Peterson480269e2010-04-27 23:04:53 +0000852 Return the lowest index in the string where substring *sub* is found, such
853 that *sub* is contained in the slice ``s[start:end]``. Optional arguments
854 *start* and *end* are interpreted as in slice notation. Return ``-1`` if
855 *sub* is not found.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000858.. method:: str.format(*args, **kwargs)
Georg Brandl4b491312007-08-31 09:22:56 +0000859
860 Perform a string formatting operation. The *format_string* argument can
861 contain literal text or replacement fields delimited by braces ``{}``. Each
862 replacement field contains either the numeric index of a positional argument,
863 or the name of a keyword argument. Returns a copy of *format_string* where
864 each replacement field is replaced with the string value of the corresponding
865 argument.
866
867 >>> "The sum of 1 + 2 is {0}".format(1+2)
868 'The sum of 1 + 2 is 3'
869
870 See :ref:`formatstrings` for a description of the various formatting options
871 that can be specified in format strings.
872
Georg Brandl4b491312007-08-31 09:22:56 +0000873
Georg Brandl116aa622007-08-15 14:28:22 +0000874.. method:: str.index(sub[, start[, end]])
875
876 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
877
878
879.. method:: str.isalnum()
880
881 Return true if all characters in the string are alphanumeric and there is at
882 least one character, false otherwise.
883
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885.. method:: str.isalpha()
886
887 Return true if all characters in the string are alphabetic and there is at least
888 one character, false otherwise.
889
Georg Brandl116aa622007-08-15 14:28:22 +0000890
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000891.. method:: str.isdecimal()
892
893 Return true if all characters in the string are decimal
894 characters and there is at least one character, false
895 otherwise. Decimal characters include digit characters, and all characters
896 that that can be used to form decimal-radix numbers, e.g. U+0660,
897 ARABIC-INDIC DIGIT ZERO.
Georg Brandl48310cd2009-01-03 21:18:54 +0000898
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000899
Georg Brandl116aa622007-08-15 14:28:22 +0000900.. method:: str.isdigit()
901
902 Return true if all characters in the string are digits and there is at least one
903 character, false otherwise.
904
Georg Brandl116aa622007-08-15 14:28:22 +0000905
906.. method:: str.isidentifier()
907
908 Return true if the string is a valid identifier according to the language
Georg Brandl4b491312007-08-31 09:22:56 +0000909 definition, section :ref:`identifiers`.
Georg Brandl116aa622007-08-15 14:28:22 +0000910
911
912.. method:: str.islower()
913
914 Return true if all cased characters in the string are lowercase and there is at
915 least one cased character, false otherwise.
916
Georg Brandl116aa622007-08-15 14:28:22 +0000917
Mark Summerfieldbbfd71d2008-07-01 15:50:04 +0000918.. method:: str.isnumeric()
919
920 Return true if all characters in the string are numeric
921 characters, and there is at least one character, false
922 otherwise. Numeric characters include digit characters, and all characters
923 that have the Unicode numeric value property, e.g. U+2155,
924 VULGAR FRACTION ONE FIFTH.
925
Georg Brandl48310cd2009-01-03 21:18:54 +0000926
Georg Brandl559e5d72008-06-11 18:37:52 +0000927.. method:: str.isprintable()
928
929 Return true if all characters in the string are printable or the string is
930 empty, false otherwise. Nonprintable characters are those characters defined
931 in the Unicode character database as "Other" or "Separator", excepting the
932 ASCII space (0x20) which is considered printable. (Note that printable
933 characters in this context are those which should not be escaped when
934 :func:`repr` is invoked on a string. It has no bearing on the handling of
935 strings written to :data:`sys.stdout` or :data:`sys.stderr`.)
936
937
Georg Brandl116aa622007-08-15 14:28:22 +0000938.. method:: str.isspace()
939
940 Return true if there are only whitespace characters in the string and there is
941 at least one character, false otherwise.
942
Georg Brandl116aa622007-08-15 14:28:22 +0000943
944.. method:: str.istitle()
945
946 Return true if the string is a titlecased string and there is at least one
947 character, for example uppercase characters may only follow uncased characters
948 and lowercase characters only cased ones. Return false otherwise.
949
Georg Brandl116aa622007-08-15 14:28:22 +0000950
951.. method:: str.isupper()
952
953 Return true if all cased characters in the string are uppercase and there is at
954 least one cased character, false otherwise.
955
Georg Brandl116aa622007-08-15 14:28:22 +0000956
Georg Brandl628e6f92009-10-27 20:24:45 +0000957.. method:: str.join(iterable)
Georg Brandl116aa622007-08-15 14:28:22 +0000958
Georg Brandl628e6f92009-10-27 20:24:45 +0000959 Return a string which is the concatenation of the strings in the
960 :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are
961 any non-string values in *seq*, including :class:`bytes` objects. The
962 separator between elements is the string providing this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964
965.. method:: str.ljust(width[, fillchar])
966
967 Return the string left justified in a string of length *width*. Padding is done
968 using the specified *fillchar* (default is a space). The original string is
969 returned if *width* is less than ``len(s)``.
970
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972.. method:: str.lower()
973
974 Return a copy of the string converted to lowercase.
975
Georg Brandl116aa622007-08-15 14:28:22 +0000976
977.. method:: str.lstrip([chars])
978
979 Return a copy of the string with leading characters removed. The *chars*
980 argument is a string specifying the set of characters to be removed. If omitted
981 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +0000982 argument is not a prefix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +0000983
984 >>> ' spacious '.lstrip()
985 'spacious '
986 >>> 'www.example.com'.lstrip('cmowz.')
987 'example.com'
988
Georg Brandl116aa622007-08-15 14:28:22 +0000989
Georg Brandlabc38772009-04-12 15:51:51 +0000990.. staticmethod:: str.maketrans(x[, y[, z]])
Georg Brandlceee0772007-11-27 23:48:05 +0000991
992 This static method returns a translation table usable for :meth:`str.translate`.
993
994 If there is only one argument, it must be a dictionary mapping Unicode
995 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
996 strings (of arbitrary lengths) or None. Character keys will then be
997 converted to ordinals.
998
999 If there are two arguments, they must be strings of equal length, and in the
1000 resulting dictionary, each character in x will be mapped to the character at
1001 the same position in y. If there is a third argument, it must be a string,
1002 whose characters will be mapped to None in the result.
1003
1004
Georg Brandl116aa622007-08-15 14:28:22 +00001005.. method:: str.partition(sep)
1006
1007 Split the string at the first occurrence of *sep*, and return a 3-tuple
1008 containing the part before the separator, the separator itself, and the part
1009 after the separator. If the separator is not found, return a 3-tuple containing
1010 the string itself, followed by two empty strings.
1011
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013.. method:: str.replace(old, new[, count])
1014
1015 Return a copy of the string with all occurrences of substring *old* replaced by
1016 *new*. If the optional argument *count* is given, only the first *count*
1017 occurrences are replaced.
1018
1019
Georg Brandl226878c2007-08-31 10:15:37 +00001020.. method:: str.rfind(sub[, start[, end]])
Georg Brandl116aa622007-08-15 14:28:22 +00001021
Benjamin Peterson480269e2010-04-27 23:04:53 +00001022 Return the highest index in the string where substring *sub* is found, such
1023 that *sub* is contained within ``s[start:end]``. Optional arguments *start*
1024 and *end* are interpreted as in slice notation. Return ``-1`` on failure.
Georg Brandl116aa622007-08-15 14:28:22 +00001025
1026
1027.. method:: str.rindex(sub[, start[, end]])
1028
1029 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1030 found.
1031
1032
1033.. method:: str.rjust(width[, fillchar])
1034
1035 Return the string right justified in a string of length *width*. Padding is done
1036 using the specified *fillchar* (default is a space). The original string is
1037 returned if *width* is less than ``len(s)``.
1038
Georg Brandl116aa622007-08-15 14:28:22 +00001039
1040.. method:: str.rpartition(sep)
1041
1042 Split the string at the last occurrence of *sep*, and return a 3-tuple
1043 containing the part before the separator, the separator itself, and the part
1044 after the separator. If the separator is not found, return a 3-tuple containing
1045 two empty strings, followed by the string itself.
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandl226878c2007-08-31 10:15:37 +00001048.. method:: str.rsplit([sep[, maxsplit]])
Georg Brandl116aa622007-08-15 14:28:22 +00001049
1050 Return a list of the words in the string, using *sep* as the delimiter string.
1051 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1052 ones. If *sep* is not specified or ``None``, any whitespace string is a
1053 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1054 :meth:`split` which is described in detail below.
1055
Georg Brandl116aa622007-08-15 14:28:22 +00001056
1057.. method:: str.rstrip([chars])
1058
1059 Return a copy of the string with trailing characters removed. The *chars*
1060 argument is a string specifying the set of characters to be removed. If omitted
1061 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
Christian Heimesfe337bf2008-03-23 21:54:12 +00001062 argument is not a suffix; rather, all combinations of its values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001063
1064 >>> ' spacious '.rstrip()
1065 ' spacious'
1066 >>> 'mississippi'.rstrip('ipz')
1067 'mississ'
1068
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Georg Brandl226878c2007-08-31 10:15:37 +00001070.. method:: str.split([sep[, maxsplit]])
Georg Brandl116aa622007-08-15 14:28:22 +00001071
Georg Brandl226878c2007-08-31 10:15:37 +00001072 Return a list of the words in the string, using *sep* as the delimiter
1073 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1074 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1075 specified, then there is no limit on the number of splits (all possible
Georg Brandl9afde1c2007-11-01 20:32:30 +00001076 splits are made).
1077
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001078 If *sep* is given, consecutive delimiters are not grouped together and are
Georg Brandl226878c2007-08-31 10:15:37 +00001079 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1080 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
Georg Brandl9afde1c2007-11-01 20:32:30 +00001081 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
Georg Brandl226878c2007-08-31 10:15:37 +00001082 Splitting an empty string with a specified separator returns ``['']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084 If *sep* is not specified or is ``None``, a different splitting algorithm is
Georg Brandl9afde1c2007-11-01 20:32:30 +00001085 applied: runs of consecutive whitespace are regarded as a single separator,
1086 and the result will contain no empty strings at the start or end if the
1087 string has leading or trailing whitespace. Consequently, splitting an empty
1088 string or a string consisting of just whitespace with a ``None`` separator
1089 returns ``[]``.
1090
1091 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1092 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094
1095.. method:: str.splitlines([keepends])
1096
1097 Return a list of the lines in the string, breaking at line boundaries. Line
1098 breaks are not included in the resulting list unless *keepends* is given and
1099 true.
1100
1101
1102.. method:: str.startswith(prefix[, start[, end]])
1103
1104 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1105 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1106 test string beginning at that position. With optional *end*, stop comparing
1107 string at that position.
1108
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110.. method:: str.strip([chars])
1111
1112 Return a copy of the string with the leading and trailing characters removed.
1113 The *chars* argument is a string specifying the set of characters to be removed.
1114 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1115 The *chars* argument is not a prefix or suffix; rather, all combinations of its
Christian Heimesfe337bf2008-03-23 21:54:12 +00001116 values are stripped:
Georg Brandl116aa622007-08-15 14:28:22 +00001117
1118 >>> ' spacious '.strip()
1119 'spacious'
1120 >>> 'www.example.com'.strip('cmowz.')
1121 'example'
1122
Georg Brandl116aa622007-08-15 14:28:22 +00001123
1124.. method:: str.swapcase()
1125
1126 Return a copy of the string with uppercase characters converted to lowercase and
1127 vice versa.
1128
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130.. method:: str.title()
1131
Raymond Hettinger941071e2009-09-29 18:56:36 +00001132 Return a titlecased version of the string where words start with an uppercase
1133 character and the remaining characters are lowercase.
1134
1135 The algorithm uses a simple language-independent definition of a word as
1136 groups of consecutive letters. The definition works in many contexts but
1137 it means that apostrophes in contractions and possessives form word
1138 boundaries, which may not be the desired result::
1139
1140 >>> "they're bill's friends from the UK".title()
1141 "They'Re Bill'S Friends From The Uk"
1142
1143 A workaround for apostrophes can be constructed using regular expressions::
1144
1145 >>> import re
1146 >>> def titlecase(s):
1147 return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
1148 lambda mo: mo.group(0)[0].upper() +
1149 mo.group(0)[1:].lower(),
1150 s)
1151
1152 >>> titlecase("they're bill's friends.")
1153 "They're Bill's Friends."
Georg Brandl116aa622007-08-15 14:28:22 +00001154
Georg Brandl116aa622007-08-15 14:28:22 +00001155
Georg Brandl4b491312007-08-31 09:22:56 +00001156.. method:: str.translate(map)
Georg Brandl116aa622007-08-15 14:28:22 +00001157
Georg Brandl226878c2007-08-31 10:15:37 +00001158 Return a copy of the *s* where all characters have been mapped through the
Georg Brandl454636f2008-12-27 23:33:20 +00001159 *map* which must be a dictionary of Unicode ordinals (integers) to Unicode
Georg Brandlceee0772007-11-27 23:48:05 +00001160 ordinals, strings or ``None``. Unmapped characters are left untouched.
1161 Characters mapped to ``None`` are deleted.
1162
Georg Brandl454636f2008-12-27 23:33:20 +00001163 You can use :meth:`str.maketrans` to create a translation map from
1164 character-to-character mappings in different formats.
Christian Heimesfe337bf2008-03-23 21:54:12 +00001165
Georg Brandl4b491312007-08-31 09:22:56 +00001166 .. note::
Georg Brandl116aa622007-08-15 14:28:22 +00001167
Georg Brandlceee0772007-11-27 23:48:05 +00001168 An even more flexible approach is to create a custom character mapping
1169 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
Georg Brandl4b491312007-08-31 09:22:56 +00001170 example).
Georg Brandl116aa622007-08-15 14:28:22 +00001171
1172
1173.. method:: str.upper()
1174
1175 Return a copy of the string converted to uppercase.
1176
Georg Brandl116aa622007-08-15 14:28:22 +00001177
1178.. method:: str.zfill(width)
1179
Georg Brandl9afde1c2007-11-01 20:32:30 +00001180 Return the numeric string left filled with zeros in a string of length
1181 *width*. A sign prefix is handled correctly. The original string is
1182 returned if *width* is less than ``len(s)``.
Christian Heimesb186d002008-03-18 15:15:01 +00001183
1184
Georg Brandl116aa622007-08-15 14:28:22 +00001185
Georg Brandl4b491312007-08-31 09:22:56 +00001186.. _old-string-formatting:
Georg Brandl116aa622007-08-15 14:28:22 +00001187
Georg Brandl4b491312007-08-31 09:22:56 +00001188Old String Formatting Operations
1189--------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +00001190
1191.. index::
1192 single: formatting, string (%)
1193 single: interpolation, string (%)
1194 single: string; formatting
1195 single: string; interpolation
1196 single: printf-style formatting
1197 single: sprintf-style formatting
1198 single: % formatting
1199 single: % interpolation
1200
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001201.. XXX is the note enough?
Georg Brandl4b491312007-08-31 09:22:56 +00001202
1203.. note::
1204
Georg Brandl226878c2007-08-31 10:15:37 +00001205 The formatting operations described here are obsolete and may go away in future
Georg Brandl4b491312007-08-31 09:22:56 +00001206 versions of Python. Use the new :ref:`string-formatting` in new code.
1207
1208String objects have one unique built-in operation: the ``%`` operator (modulo).
1209This is also known as the string *formatting* or *interpolation* operator.
1210Given ``format % values`` (where *format* is a string), ``%`` conversion
1211specifications in *format* are replaced with zero or more elements of *values*.
1212The effect is similar to the using :cfunc:`sprintf` in the C language.
Georg Brandl116aa622007-08-15 14:28:22 +00001213
1214If *format* requires a single argument, *values* may be a single non-tuple
1215object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1216items specified by the format string, or a single mapping object (for example, a
1217dictionary).
1218
1219A conversion specifier contains two or more characters and has the following
1220components, which must occur in this order:
1221
1222#. The ``'%'`` character, which marks the start of the specifier.
1223
1224#. Mapping key (optional), consisting of a parenthesised sequence of characters
1225 (for example, ``(somename)``).
1226
1227#. Conversion flags (optional), which affect the result of some conversion
1228 types.
1229
1230#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1231 actual width is read from the next element of the tuple in *values*, and the
1232 object to convert comes after the minimum field width and optional precision.
1233
1234#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1235 specified as ``'*'`` (an asterisk), the actual width is read from the next
1236 element of the tuple in *values*, and the value to convert comes after the
1237 precision.
1238
1239#. Length modifier (optional).
1240
1241#. Conversion type.
1242
1243When the right argument is a dictionary (or other mapping type), then the
1244formats in the string *must* include a parenthesised mapping key into that
1245dictionary inserted immediately after the ``'%'`` character. The mapping key
Christian Heimesfe337bf2008-03-23 21:54:12 +00001246selects the value to be formatted from the mapping. For example:
Georg Brandl116aa622007-08-15 14:28:22 +00001247
Christian Heimesfe337bf2008-03-23 21:54:12 +00001248
1249 >>> print('%(language)s has %(#)03d quote types.' % \
1250 ... {'language': "Python", "#": 2})
Georg Brandl116aa622007-08-15 14:28:22 +00001251 Python has 002 quote types.
1252
1253In this case no ``*`` specifiers may occur in a format (since they require a
1254sequential parameter list).
1255
1256The conversion flag characters are:
1257
1258+---------+---------------------------------------------------------------------+
1259| Flag | Meaning |
1260+=========+=====================================================================+
1261| ``'#'`` | The value conversion will use the "alternate form" (where defined |
1262| | below). |
1263+---------+---------------------------------------------------------------------+
1264| ``'0'`` | The conversion will be zero padded for numeric values. |
1265+---------+---------------------------------------------------------------------+
1266| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1267| | conversion if both are given). |
1268+---------+---------------------------------------------------------------------+
1269| ``' '`` | (a space) A blank should be left before a positive number (or empty |
1270| | string) produced by a signed conversion. |
1271+---------+---------------------------------------------------------------------+
1272| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1273| | (overrides a "space" flag). |
1274+---------+---------------------------------------------------------------------+
1275
1276A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001277is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
Georg Brandl116aa622007-08-15 14:28:22 +00001278
1279The conversion types are:
1280
1281+------------+-----------------------------------------------------+-------+
1282| Conversion | Meaning | Notes |
1283+============+=====================================================+=======+
1284| ``'d'`` | Signed integer decimal. | |
1285+------------+-----------------------------------------------------+-------+
1286| ``'i'`` | Signed integer decimal. | |
1287+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001288| ``'o'`` | Signed octal value. | \(1) |
Georg Brandl116aa622007-08-15 14:28:22 +00001289+------------+-----------------------------------------------------+-------+
Benjamin Petersone0124bd2009-03-09 21:04:33 +00001290| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
Georg Brandl116aa622007-08-15 14:28:22 +00001291+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001292| ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001293+------------+-----------------------------------------------------+-------+
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001294| ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001295+------------+-----------------------------------------------------+-------+
1296| ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1297+------------+-----------------------------------------------------+-------+
1298| ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1299+------------+-----------------------------------------------------+-------+
Eric Smith22b85b32008-07-17 19:18:29 +00001300| ``'f'`` | Floating point decimal format. | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001301+------------+-----------------------------------------------------+-------+
Eric Smith22b85b32008-07-17 19:18:29 +00001302| ``'F'`` | Floating point decimal format. | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001303+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001304| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1305| | format if exponent is less than -4 or not less than | |
1306| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001307+------------+-----------------------------------------------------+-------+
Christian Heimes8dc226f2008-05-06 23:45:46 +00001308| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1309| | format if exponent is less than -4 or not less than | |
1310| | precision, decimal format otherwise. | |
Georg Brandl116aa622007-08-15 14:28:22 +00001311+------------+-----------------------------------------------------+-------+
1312| ``'c'`` | Single character (accepts integer or single | |
1313| | character string). | |
1314+------------+-----------------------------------------------------+-------+
Ezio Melotti890c1932009-12-19 23:33:46 +00001315| ``'r'`` | String (converts any Python object using | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001316| | :func:`repr`). | |
1317+------------+-----------------------------------------------------+-------+
Ezio Melotti890c1932009-12-19 23:33:46 +00001318| ``'s'`` | String (converts any Python object using | |
Georg Brandl116aa622007-08-15 14:28:22 +00001319| | :func:`str`). | |
1320+------------+-----------------------------------------------------+-------+
1321| ``'%'`` | No argument is converted, results in a ``'%'`` | |
1322| | character in the result. | |
1323+------------+-----------------------------------------------------+-------+
1324
1325Notes:
1326
1327(1)
1328 The alternate form causes a leading zero (``'0'``) to be inserted between
1329 left-hand padding and the formatting of the number if the leading character
1330 of the result is not already a zero.
1331
1332(2)
1333 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1334 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1335 and the formatting of the number if the leading character of the result is not
1336 already a zero.
1337
1338(3)
1339 The alternate form causes the result to always contain a decimal point, even if
1340 no digits follow it.
1341
1342 The precision determines the number of digits after the decimal point and
1343 defaults to 6.
1344
1345(4)
1346 The alternate form causes the result to always contain a decimal point, and
1347 trailing zeroes are not removed as they would otherwise be.
1348
1349 The precision determines the number of significant digits before and after the
1350 decimal point and defaults to 6.
1351
1352(5)
Georg Brandl116aa622007-08-15 14:28:22 +00001353 The precision determines the maximal number of characters used.
1354
Georg Brandl116aa622007-08-15 14:28:22 +00001355
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +00001356(7)
1357 See :pep:`237`.
1358
Georg Brandl116aa622007-08-15 14:28:22 +00001359Since Python strings have an explicit length, ``%s`` conversions do not assume
1360that ``'\0'`` is the end of the string.
1361
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001362.. XXX Examples?
1363
Mark Dickinson33841c32009-05-01 15:37:04 +00001364.. versionchanged:: 3.1
1365 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1366 longer replaced by ``%g`` conversions.
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368.. index::
1369 module: string
1370 module: re
1371
1372Additional string operations are defined in standard modules :mod:`string` and
1373:mod:`re`.
1374
1375
1376.. _typesseq-range:
1377
Georg Brandl905ec322007-09-28 13:39:25 +00001378Range Type
1379----------
Georg Brandl116aa622007-08-15 14:28:22 +00001380
1381.. index:: object: range
1382
1383The :class:`range` type is an immutable sequence which is commonly used for
1384looping. The advantage of the :class:`range` type is that an :class:`range`
1385object will always take the same amount of memory, no matter the size of the
1386range it represents. There are no consistent performance advantages.
1387
Georg Brandl905ec322007-09-28 13:39:25 +00001388Range objects have very little behavior: they only support indexing, iteration,
Georg Brandl116aa622007-08-15 14:28:22 +00001389and the :func:`len` function.
1390
1391
1392.. _typesseq-mutable:
1393
1394Mutable Sequence Types
1395----------------------
1396
1397.. index::
1398 triple: mutable; sequence; types
1399 object: list
Georg Brandl95414632007-11-22 11:00:28 +00001400 object: bytearray
Georg Brandl116aa622007-08-15 14:28:22 +00001401
Georg Brandl95414632007-11-22 11:00:28 +00001402List and bytearray objects support additional operations that allow in-place
Georg Brandl226878c2007-08-31 10:15:37 +00001403modification of the object. Other mutable sequence types (when added to the
1404language) should also support these operations. Strings and tuples are
1405immutable sequence types: such objects cannot be modified once created. The
1406following operations are defined on mutable sequence types (where *x* is an
1407arbitrary object).
1408
Georg Brandl95414632007-11-22 11:00:28 +00001409Note that while lists allow their items to be of any type, bytearray object
Georg Brandl226878c2007-08-31 10:15:37 +00001410"items" are all integers in the range 0 <= x < 256.
Georg Brandl116aa622007-08-15 14:28:22 +00001411
Senthil Kumarand8d1cea2010-10-02 03:25:12 +00001412.. index::
1413 triple: operations on; sequence; types
1414 triple: operations on; list; type
1415 pair: subscript; assignment
1416 pair: slice; assignment
1417 statement: del
1418 single: append() (sequence method)
1419 single: extend() (sequence method)
1420 single: count() (sequence method)
1421 single: index() (sequence method)
1422 single: insert() (sequence method)
1423 single: pop() (sequence method)
1424 single: remove() (sequence method)
1425 single: reverse() (sequence method)
1426 single: sort() (sequence method)
1427
Georg Brandl116aa622007-08-15 14:28:22 +00001428+------------------------------+--------------------------------+---------------------+
1429| Operation | Result | Notes |
1430+==============================+================================+=====================+
1431| ``s[i] = x`` | item *i* of *s* is replaced by | |
1432| | *x* | |
1433+------------------------------+--------------------------------+---------------------+
1434| ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1435| | is replaced by the contents of | |
1436| | the iterable *t* | |
1437+------------------------------+--------------------------------+---------------------+
1438| ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1439+------------------------------+--------------------------------+---------------------+
1440| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1441| | are replaced by those of *t* | |
1442+------------------------------+--------------------------------+---------------------+
1443| ``del s[i:j:k]`` | removes the elements of | |
1444| | ``s[i:j:k]`` from the list | |
1445+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001446| ``s.append(x)`` | same as ``s[len(s):len(s)] = | |
Georg Brandl116aa622007-08-15 14:28:22 +00001447| | [x]`` | |
1448+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001449| ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) |
Georg Brandl116aa622007-08-15 14:28:22 +00001450| | x`` | |
1451+------------------------------+--------------------------------+---------------------+
1452| ``s.count(x)`` | return number of *i*'s for | |
1453| | which ``s[i] == x`` | |
1454+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001455| ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001456| | ``s[k] == x`` and ``i <= k < | |
1457| | j`` | |
1458+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001459| ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) |
Georg Brandl116aa622007-08-15 14:28:22 +00001460+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001461| ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) |
Georg Brandl116aa622007-08-15 14:28:22 +00001462| | return x`` | |
1463+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001464| ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) |
Georg Brandl116aa622007-08-15 14:28:22 +00001465+------------------------------+--------------------------------+---------------------+
Georg Brandl226878c2007-08-31 10:15:37 +00001466| ``s.reverse()`` | reverses the items of *s* in | \(6) |
Georg Brandl116aa622007-08-15 14:28:22 +00001467| | place | |
1468+------------------------------+--------------------------------+---------------------+
Raymond Hettinger7f732952008-02-14 13:34:38 +00001469| ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) |
Georg Brandl116aa622007-08-15 14:28:22 +00001470+------------------------------+--------------------------------+---------------------+
1471
Georg Brandl116aa622007-08-15 14:28:22 +00001472
1473Notes:
1474
1475(1)
Georg Brandl226878c2007-08-31 10:15:37 +00001476 *t* must have the same length as the slice it is replacing.
Georg Brandl116aa622007-08-15 14:28:22 +00001477
1478(2)
Georg Brandl116aa622007-08-15 14:28:22 +00001479 *x* can be any iterable object.
1480
Georg Brandl226878c2007-08-31 10:15:37 +00001481(3)
Georg Brandl116aa622007-08-15 14:28:22 +00001482 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
Georg Brandl226878c2007-08-31 10:15:37 +00001483 passed as the second or third parameter to the :meth:`index` method, the sequence
Georg Brandl116aa622007-08-15 14:28:22 +00001484 length is added, as for slice indices. If it is still negative, it is truncated
1485 to zero, as for slice indices.
1486
Georg Brandl226878c2007-08-31 10:15:37 +00001487(4)
Georg Brandl116aa622007-08-15 14:28:22 +00001488 When a negative index is passed as the first parameter to the :meth:`insert`
Georg Brandl226878c2007-08-31 10:15:37 +00001489 method, the sequence length is added, as for slice indices. If it is still
Georg Brandl116aa622007-08-15 14:28:22 +00001490 negative, it is truncated to zero, as for slice indices.
1491
Georg Brandl226878c2007-08-31 10:15:37 +00001492(5)
1493 The optional argument *i* defaults to ``-1``, so that by default the last
1494 item is removed and returned.
1495
Georg Brandl116aa622007-08-15 14:28:22 +00001496(6)
Georg Brandl226878c2007-08-31 10:15:37 +00001497 The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for
1498 economy of space when sorting or reversing a large sequence. To remind you
1499 that they operate by side effect, they don't return the sorted or reversed
1500 sequence.
Georg Brandl116aa622007-08-15 14:28:22 +00001501
1502(7)
Georg Brandl116aa622007-08-15 14:28:22 +00001503 The :meth:`sort` method takes optional arguments for controlling the
Raymond Hettinger7f732952008-02-14 13:34:38 +00001504 comparisons. Each must be specified as a keyword argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001505
Georg Brandl116aa622007-08-15 14:28:22 +00001506 *key* specifies a function of one argument that is used to extract a comparison
Christian Heimesfaf2f632008-01-06 16:59:19 +00001507 key from each list element: ``key=str.lower``. The default value is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001508
1509 *reverse* is a boolean value. If set to ``True``, then the list elements are
1510 sorted as if each comparison were reversed.
1511
Raymond Hettinger71161862008-02-14 13:32:18 +00001512 The :meth:`sort` method is guaranteed to be stable. A
Georg Brandl116aa622007-08-15 14:28:22 +00001513 sort is stable if it guarantees not to change the relative order of elements
1514 that compare equal --- this is helpful for sorting in multiple passes (for
1515 example, sort by department, then by salary grade).
1516
Georg Brandl628e6f92009-10-27 20:24:45 +00001517 .. impl-detail::
1518
1519 While a list is being sorted, the effect of attempting to mutate, or even
1520 inspect, the list is undefined. The C implementation of Python makes the
1521 list appear empty for the duration, and raises :exc:`ValueError` if it can
1522 detect that the list has been mutated during a sort.
Georg Brandl116aa622007-08-15 14:28:22 +00001523
Raymond Hettinger7f732952008-02-14 13:34:38 +00001524(8)
1525 :meth:`sort` is not supported by :class:`bytearray` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Georg Brandl628e6f92009-10-27 20:24:45 +00001527
Georg Brandl226878c2007-08-31 10:15:37 +00001528.. _bytes-methods:
1529
Georg Brandl95414632007-11-22 11:00:28 +00001530Bytes and Byte Array Methods
1531----------------------------
Georg Brandl226878c2007-08-31 10:15:37 +00001532
1533.. index:: pair: bytes; methods
Georg Brandl95414632007-11-22 11:00:28 +00001534 pair: bytearray; methods
Georg Brandl226878c2007-08-31 10:15:37 +00001535
Georg Brandl95414632007-11-22 11:00:28 +00001536Bytes and bytearray objects, being "strings of bytes", have all methods found on
Georg Brandl7c676132007-10-23 18:17:00 +00001537strings, with the exception of :func:`encode`, :func:`format` and
Guido van Rossum98297ee2007-11-06 21:34:58 +00001538:func:`isidentifier`, which do not make sense with these types. For converting
1539the objects to strings, they have a :func:`decode` method.
1540
1541Wherever one of these methods needs to interpret the bytes as characters
1542(e.g. the :func:`is...` methods), the ASCII character set is assumed.
Georg Brandl226878c2007-08-31 10:15:37 +00001543
Georg Brandl7c676132007-10-23 18:17:00 +00001544.. note::
Georg Brandl226878c2007-08-31 10:15:37 +00001545
Georg Brandl95414632007-11-22 11:00:28 +00001546 The methods on bytes and bytearray objects don't accept strings as their
Georg Brandl7c676132007-10-23 18:17:00 +00001547 arguments, just as the methods on strings don't accept bytes as their
1548 arguments. For example, you have to write ::
Georg Brandl226878c2007-08-31 10:15:37 +00001549
Georg Brandl7c676132007-10-23 18:17:00 +00001550 a = "abc"
1551 b = a.replace("a", "f")
1552
1553 and ::
1554
1555 a = b"abc"
1556 b = a.replace(b"a", b"f")
Georg Brandl226878c2007-08-31 10:15:37 +00001557
1558
Georg Brandl4f5f98d2009-05-04 21:01:20 +00001559.. method:: bytes.decode([encoding[, errors]])
1560 bytearray.decode([encoding[, errors]])
1561
1562 Return a string decoded from the given bytes. Default encoding is the
1563 current default string encoding. *errors* may be given to set a different
1564 error handling scheme. The default for *errors* is ``'strict'``, meaning
1565 that encoding errors raise a :exc:`UnicodeError`. Other possible values are
1566 ``'ignore'``, ``'replace'`` and any other name registered via
1567 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
1568 list of possible encodings, see section :ref:`standard-encodings`.
1569
1570
Georg Brandl95414632007-11-22 11:00:28 +00001571The bytes and bytearray types have an additional class method:
Georg Brandl226878c2007-08-31 10:15:37 +00001572
Georg Brandlabc38772009-04-12 15:51:51 +00001573.. classmethod:: bytes.fromhex(string)
1574 bytearray.fromhex(string)
Georg Brandl226878c2007-08-31 10:15:37 +00001575
Georg Brandl18da8f02008-07-01 20:08:02 +00001576 This :class:`bytes` class method returns a bytes or bytearray object,
1577 decoding the given string object. The string must contain two hexadecimal
1578 digits per byte, spaces are ignored.
Georg Brandl226878c2007-08-31 10:15:37 +00001579
Georg Brandl18da8f02008-07-01 20:08:02 +00001580 >>> bytes.fromhex('f0 f1f2 ')
1581 b'\xf0\xf1\xf2'
Georg Brandl226878c2007-08-31 10:15:37 +00001582
Georg Brandlabc38772009-04-12 15:51:51 +00001583
1584The maketrans and translate methods differ in semantics from the versions
1585available on strings:
Georg Brandl48310cd2009-01-03 21:18:54 +00001586
Georg Brandl454636f2008-12-27 23:33:20 +00001587.. method:: bytes.translate(table[, delete])
Georg Brandl751771b2009-05-31 21:38:37 +00001588 bytearray.translate(table[, delete])
Georg Brandl226878c2007-08-31 10:15:37 +00001589
Georg Brandl454636f2008-12-27 23:33:20 +00001590 Return a copy of the bytes or bytearray object where all bytes occurring in
1591 the optional argument *delete* are removed, and the remaining bytes have been
1592 mapped through the given translation table, which must be a bytes object of
1593 length 256.
Georg Brandl226878c2007-08-31 10:15:37 +00001594
Georg Brandlabc38772009-04-12 15:51:51 +00001595 You can use the :func:`bytes.maketrans` method to create a translation table.
Georg Brandl226878c2007-08-31 10:15:37 +00001596
Georg Brandl454636f2008-12-27 23:33:20 +00001597 Set the *table* argument to ``None`` for translations that only delete
1598 characters::
Georg Brandl226878c2007-08-31 10:15:37 +00001599
Georg Brandl454636f2008-12-27 23:33:20 +00001600 >>> b'read this short text'.translate(None, b'aeiou')
1601 b'rd ths shrt txt'
Georg Brandl226878c2007-08-31 10:15:37 +00001602
1603
Georg Brandlabc38772009-04-12 15:51:51 +00001604.. staticmethod:: bytes.maketrans(from, to)
Georg Brandl751771b2009-05-31 21:38:37 +00001605 bytearray.maketrans(from, to)
Georg Brandlabc38772009-04-12 15:51:51 +00001606
1607 This static method returns a translation table usable for
1608 :meth:`bytes.translate` that will map each character in *from* into the
1609 character at the same position in *to*; *from* and *to* must be bytes objects
1610 and have the same length.
1611
1612 .. versionadded:: 3.1
1613
1614
Georg Brandl116aa622007-08-15 14:28:22 +00001615.. _types-set:
1616
1617Set Types --- :class:`set`, :class:`frozenset`
1618==============================================
1619
1620.. index:: object: set
1621
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001622A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001623Common uses include membership testing, removing duplicates from a sequence, and
1624computing mathematical operations such as intersection, union, difference, and
1625symmetric difference.
1626(For other containers see the built in :class:`dict`, :class:`list`,
1627and :class:`tuple` classes, and the :mod:`collections` module.)
1628
Georg Brandl116aa622007-08-15 14:28:22 +00001629Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1630set``. Being an unordered collection, sets do not record element position or
1631order of insertion. Accordingly, sets do not support indexing, slicing, or
1632other sequence-like behavior.
1633
Georg Brandlc5605df2009-08-13 08:26:44 +00001634There are currently two built-in set types, :class:`set` and :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00001635The :class:`set` type is mutable --- the contents can be changed using methods
1636like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1637and cannot be used as either a dictionary key or as an element of another set.
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001638The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
Georg Brandl116aa622007-08-15 14:28:22 +00001639altered after it is created; it can therefore be used as a dictionary key or as
1640an element of another set.
1641
1642The constructors for both classes work the same:
1643
1644.. class:: set([iterable])
1645 frozenset([iterable])
1646
1647 Return a new set or frozenset object whose elements are taken from
1648 *iterable*. The elements of a set must be hashable. To represent sets of
1649 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1650 not specified, a new empty set is returned.
1651
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001652 Instances of :class:`set` and :class:`frozenset` provide the following
1653 operations:
Georg Brandl116aa622007-08-15 14:28:22 +00001654
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001655 .. describe:: len(s)
Georg Brandl116aa622007-08-15 14:28:22 +00001656
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001657 Return the cardinality of set *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001658
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001659 .. describe:: x in s
Georg Brandl116aa622007-08-15 14:28:22 +00001660
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001661 Test *x* for membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001663 .. describe:: x not in s
Georg Brandl116aa622007-08-15 14:28:22 +00001664
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001665 Test *x* for non-membership in *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001666
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001667 .. method:: isdisjoint(other)
Guido van Rossum58da9312007-11-10 23:39:45 +00001668
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001669 Return True if the set has no elements in common with *other*. Sets are
Georg Brandl2ee470f2008-07-16 12:55:28 +00001670 disjoint if and only if their intersection is the empty set.
Guido van Rossum58da9312007-11-10 23:39:45 +00001671
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001672 .. method:: issubset(other)
1673 set <= other
Georg Brandl116aa622007-08-15 14:28:22 +00001674
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001675 Test whether every element in the set is in *other*.
Georg Brandl116aa622007-08-15 14:28:22 +00001676
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001677 .. method:: set < other
Georg Brandla6f52782007-09-01 15:49:30 +00001678
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001679 Test whether the set is a true subset of *other*, that is,
1680 ``set <= other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00001681
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001682 .. method:: issuperset(other)
1683 set >= other
Georg Brandl116aa622007-08-15 14:28:22 +00001684
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001685 Test whether every element in *other* is in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001686
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001687 .. method:: set > other
Georg Brandla6f52782007-09-01 15:49:30 +00001688
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001689 Test whether the set is a true superset of *other*, that is, ``set >=
1690 other and set != other``.
Georg Brandla6f52782007-09-01 15:49:30 +00001691
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001692 .. method:: union(other, ...)
1693 set | other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001694
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001695 Return a new set with elements from the set and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00001696
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001697 .. method:: intersection(other, ...)
1698 set & other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00001699
Benjamin Petersonb58dda72009-01-18 22:27:04 +00001700 Return a new set with elements common to the set and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00001701
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001702 .. method:: difference(other, ...)
1703 set - other - ...
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001704
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001705 Return a new set with elements in the set that are not in the others.
Georg Brandl116aa622007-08-15 14:28:22 +00001706
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001707 .. method:: symmetric_difference(other)
1708 set ^ other
Georg Brandl116aa622007-08-15 14:28:22 +00001709
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001710 Return a new set with elements in either the set or *other* but not both.
Georg Brandl116aa622007-08-15 14:28:22 +00001711
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001712 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00001713
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001714 Return a new set with a shallow copy of *s*.
Georg Brandl116aa622007-08-15 14:28:22 +00001715
1716
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001717 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1718 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1719 :meth:`issuperset` methods will accept any iterable as an argument. In
1720 contrast, their operator based counterparts require their arguments to be
1721 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1722 in favor of the more readable ``set('abc').intersection('cbs')``.
Georg Brandl116aa622007-08-15 14:28:22 +00001723
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001724 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1725 sets are equal if and only if every element of each set is contained in the
1726 other (each is a subset of the other). A set is less than another set if and
1727 only if the first set is a proper subset of the second set (is a subset, but
1728 is not equal). A set is greater than another set if and only if the first set
1729 is a proper superset of the second set (is a superset, but is not equal).
Georg Brandl116aa622007-08-15 14:28:22 +00001730
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001731 Instances of :class:`set` are compared to instances of :class:`frozenset`
1732 based on their members. For example, ``set('abc') == frozenset('abc')``
1733 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
Georg Brandl116aa622007-08-15 14:28:22 +00001734
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001735 The subset and equality comparisons do not generalize to a complete ordering
1736 function. For example, any two disjoint sets are not equal and are not
1737 subsets of each other, so *all* of the following return ``False``: ``a<b``,
Georg Brandl05f5ab72008-09-24 09:11:47 +00001738 ``a==b``, or ``a>b``.
Georg Brandl116aa622007-08-15 14:28:22 +00001739
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001740 Since sets only define partial ordering (subset relationships), the output of
1741 the :meth:`list.sort` method is undefined for lists of sets.
Georg Brandl116aa622007-08-15 14:28:22 +00001742
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001743 Set elements, like dictionary keys, must be :term:`hashable`.
Georg Brandl116aa622007-08-15 14:28:22 +00001744
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001745 Binary operations that mix :class:`set` instances with :class:`frozenset`
1746 return the type of the first operand. For example: ``frozenset('ab') |
1747 set('bc')`` returns an instance of :class:`frozenset`.
Georg Brandl116aa622007-08-15 14:28:22 +00001748
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001749 The following table lists operations available for :class:`set` that do not
1750 apply to immutable instances of :class:`frozenset`:
Georg Brandl116aa622007-08-15 14:28:22 +00001751
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001752 .. method:: update(other, ...)
1753 set |= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001754
Georg Brandl7baf6252009-09-01 08:13:16 +00001755 Update the set, adding elements from all others.
Georg Brandl116aa622007-08-15 14:28:22 +00001756
Georg Brandlc28e1fa2008-06-10 19:20:26 +00001757 .. method:: intersection_update(other, ...)
1758 set &= other & ...
Georg Brandl116aa622007-08-15 14:28:22 +00001759
Georg Brandl7baf6252009-09-01 08:13:16 +00001760 Update the set, keeping only elements found in it and all others.
Georg Brandl116aa622007-08-15 14:28:22 +00001761
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001762 .. method:: difference_update(other, ...)
1763 set -= other | ...
Georg Brandl116aa622007-08-15 14:28:22 +00001764
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +00001765 Update the set, removing elements found in others.
1766
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001767 .. method:: symmetric_difference_update(other)
1768 set ^= other
Georg Brandl116aa622007-08-15 14:28:22 +00001769
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001770 Update the set, keeping only elements found in either set, but not in both.
Georg Brandl116aa622007-08-15 14:28:22 +00001771
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001772 .. method:: add(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00001773
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001774 Add element *elem* to the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001775
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001776 .. method:: remove(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00001777
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001778 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1779 not contained in the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001780
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001781 .. method:: discard(elem)
Georg Brandl116aa622007-08-15 14:28:22 +00001782
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001783 Remove element *elem* from the set if it is present.
Georg Brandl116aa622007-08-15 14:28:22 +00001784
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001785 .. method:: pop()
Georg Brandl116aa622007-08-15 14:28:22 +00001786
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001787 Remove and return an arbitrary element from the set. Raises
1788 :exc:`KeyError` if the set is empty.
Georg Brandl116aa622007-08-15 14:28:22 +00001789
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001790 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00001791
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001792 Remove all elements from the set.
Georg Brandl116aa622007-08-15 14:28:22 +00001793
1794
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001795 Note, the non-operator versions of the :meth:`update`,
1796 :meth:`intersection_update`, :meth:`difference_update`, and
1797 :meth:`symmetric_difference_update` methods will accept any iterable as an
1798 argument.
Georg Brandl116aa622007-08-15 14:28:22 +00001799
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001800 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1801 :meth:`discard` methods may be a set. To support searching for an equivalent
1802 frozenset, the *elem* set is temporarily mutated during the search and then
1803 restored. During the search, the *elem* set should not be read or mutated
1804 since it does not have a meaningful value.
Benjamin Peterson699adb92008-05-08 22:27:58 +00001805
Georg Brandl116aa622007-08-15 14:28:22 +00001806
1807.. _typesmapping:
1808
1809Mapping Types --- :class:`dict`
1810===============================
1811
1812.. index::
1813 object: mapping
1814 object: dictionary
1815 triple: operations on; mapping; types
1816 triple: operations on; dictionary; type
1817 statement: del
1818 builtin: len
1819
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001820A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1821Mappings are mutable objects. There is currently only one standard mapping
1822type, the :dfn:`dictionary`. (For other containers see the built in
1823:class:`list`, :class:`set`, and :class:`tuple` classes, and the
1824:mod:`collections` module.)
Georg Brandl116aa622007-08-15 14:28:22 +00001825
Guido van Rossum2cc30da2007-11-02 23:46:40 +00001826A dictionary's keys are *almost* arbitrary values. Values that are not
1827:term:`hashable`, that is, values containing lists, dictionaries or other
1828mutable types (that are compared by value rather than by object identity) may
1829not be used as keys. Numeric types used for keys obey the normal rules for
1830numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1831then they can be used interchangeably to index the same dictionary entry. (Note
1832however, that since computers store floating-point numbers as approximations it
1833is usually unwise to use them as dictionary keys.)
Georg Brandl116aa622007-08-15 14:28:22 +00001834
1835Dictionaries can be created by placing a comma-separated list of ``key: value``
1836pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1837'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1838
1839.. class:: dict([arg])
1840
Georg Brandld22a8152007-09-04 17:43:37 +00001841 Return a new dictionary initialized from an optional positional argument or
1842 from a set of keyword arguments. If no arguments are given, return a new
1843 empty dictionary. If the positional argument *arg* is a mapping object,
1844 return a dictionary mapping the same keys to the same values as does the
1845 mapping object. Otherwise the positional argument must be a sequence, a
1846 container that supports iteration, or an iterator object. The elements of
1847 the argument must each also be of one of those kinds, and each must in turn
1848 contain exactly two objects. The first is used as a key in the new
1849 dictionary, and the second as the key's value. If a given key is seen more
1850 than once, the last value associated with it is retained in the new
1851 dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001852
1853 If keyword arguments are given, the keywords themselves with their associated
Georg Brandld22a8152007-09-04 17:43:37 +00001854 values are added as items to the dictionary. If a key is specified both in
1855 the positional argument and as a keyword argument, the value associated with
1856 the keyword is retained in the dictionary. For example, these all return a
Georg Brandl116aa622007-08-15 14:28:22 +00001857 dictionary equal to ``{"one": 2, "two": 3}``:
1858
1859 * ``dict(one=2, two=3)``
Georg Brandl116aa622007-08-15 14:28:22 +00001860 * ``dict({'one': 2, 'two': 3})``
Georg Brandl116aa622007-08-15 14:28:22 +00001861 * ``dict(zip(('one', 'two'), (2, 3)))``
Georg Brandl116aa622007-08-15 14:28:22 +00001862 * ``dict([['two', 3], ['one', 2]])``
1863
Georg Brandld22a8152007-09-04 17:43:37 +00001864 The first example only works for keys that are valid Python identifiers; the
1865 others work with any valid keys.
Georg Brandl116aa622007-08-15 14:28:22 +00001866
Georg Brandl116aa622007-08-15 14:28:22 +00001867
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001868 These are the operations that dictionaries support (and therefore, custom
1869 mapping types should support too):
Georg Brandl116aa622007-08-15 14:28:22 +00001870
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001871 .. describe:: len(d)
Georg Brandl116aa622007-08-15 14:28:22 +00001872
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001873 Return the number of items in the dictionary *d*.
Georg Brandl116aa622007-08-15 14:28:22 +00001874
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001875 .. describe:: d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00001876
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001877 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
1878 not in the map.
Georg Brandl48310cd2009-01-03 21:18:54 +00001879
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001880 If a subclass of dict defines a method :meth:`__missing__`, if the key *key*
1881 is not present, the ``d[key]`` operation calls that method with the key *key*
1882 as argument. The ``d[key]`` operation then returns or raises whatever is
1883 returned or raised by the ``__missing__(key)`` call if the key is not
1884 present. No other operations or methods invoke :meth:`__missing__`. If
1885 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
1886 :meth:`__missing__` must be a method; it cannot be an instance variable. For
1887 an example, see :class:`collections.defaultdict`.
Georg Brandl116aa622007-08-15 14:28:22 +00001888
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001889 .. describe:: d[key] = value
Georg Brandl116aa622007-08-15 14:28:22 +00001890
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001891 Set ``d[key]`` to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00001892
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001893 .. describe:: del d[key]
Georg Brandl116aa622007-08-15 14:28:22 +00001894
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001895 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1896 map.
Georg Brandl116aa622007-08-15 14:28:22 +00001897
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001898 .. describe:: key in d
Georg Brandl116aa622007-08-15 14:28:22 +00001899
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001900 Return ``True`` if *d* has a key *key*, else ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +00001901
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001902 .. describe:: key not in d
Georg Brandl116aa622007-08-15 14:28:22 +00001903
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001904 Equivalent to ``not key in d``.
Georg Brandl116aa622007-08-15 14:28:22 +00001905
Benjamin Petersond23f8222009-04-05 19:13:16 +00001906 .. describe:: iter(d)
1907
1908 Return an iterator over the keys of the dictionary. This is a shortcut
Georg Brandl31a0f862010-07-04 17:33:33 +00001909 for ``iter(d.keys())``.
Benjamin Petersond23f8222009-04-05 19:13:16 +00001910
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001911 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +00001912
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001913 Remove all items from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001914
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001915 .. method:: copy()
Georg Brandl116aa622007-08-15 14:28:22 +00001916
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001917 Return a shallow copy of the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001918
Georg Brandlabc38772009-04-12 15:51:51 +00001919 .. classmethod:: fromkeys(seq[, value])
Georg Brandl116aa622007-08-15 14:28:22 +00001920
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001921 Create a new dictionary with keys from *seq* and values set to *value*.
Georg Brandl116aa622007-08-15 14:28:22 +00001922
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001923 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
1924 defaults to ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001925
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001926 .. method:: get(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00001927
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001928 Return the value for *key* if *key* is in the dictionary, else *default*.
1929 If *default* is not given, it defaults to ``None``, so that this method
1930 never raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001931
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001932 .. method:: items()
Georg Brandl116aa622007-08-15 14:28:22 +00001933
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001934 Return a new view of the dictionary's items (``(key, value)`` pairs). See
1935 below for documentation of view objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001936
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001937 .. method:: keys()
Georg Brandl116aa622007-08-15 14:28:22 +00001938
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001939 Return a new view of the dictionary's keys. See below for documentation of
1940 view objects.
Georg Brandl116aa622007-08-15 14:28:22 +00001941
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001942 .. method:: pop(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00001943
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001944 If *key* is in the dictionary, remove it and return its value, else return
1945 *default*. If *default* is not given and *key* is not in the dictionary,
1946 a :exc:`KeyError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001947
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001948 .. method:: popitem()
Georg Brandl116aa622007-08-15 14:28:22 +00001949
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001950 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00001951
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001952 :meth:`popitem` is useful to destructively iterate over a dictionary, as
1953 often used in set algorithms. If the dictionary is empty, calling
1954 :meth:`popitem` raises a :exc:`KeyError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001955
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001956 .. method:: setdefault(key[, default])
Georg Brandl116aa622007-08-15 14:28:22 +00001957
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001958 If *key* is in the dictionary, return its value. If not, insert *key*
1959 with a value of *default* and return *default*. *default* defaults to
1960 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001961
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001962 .. method:: update([other])
Georg Brandl116aa622007-08-15 14:28:22 +00001963
Éric Araujo790c9af2010-08-18 22:42:07 +00001964 Update the dictionary with the key/value pairs from *other*, overwriting
1965 existing keys. Return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +00001966
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001967 :meth:`update` accepts either another dictionary object or an iterable of
1968 key/value pairs (as a tuple or other iterable of length two). If keyword
Benjamin Petersona8332062009-09-11 22:36:27 +00001969 arguments are specified, the dictionary is then updated with those
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001970 key/value pairs: ``d.update(red=1, blue=2)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001971
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001972 .. method:: values()
Georg Brandl116aa622007-08-15 14:28:22 +00001973
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +00001974 Return a new view of the dictionary's values. See below for documentation of
1975 view objects.
Georg Brandld22a8152007-09-04 17:43:37 +00001976
1977
Benjamin Peterson44309e62008-11-22 00:41:45 +00001978.. _dict-views:
1979
Georg Brandld22a8152007-09-04 17:43:37 +00001980Dictionary view objects
1981-----------------------
1982
1983The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
1984:meth:`dict.items` are *view objects*. They provide a dynamic view on the
1985dictionary's entries, which means that when the dictionary changes, the view
Benjamin Petersonce0506c2008-11-17 21:47:41 +00001986reflects these changes.
Georg Brandld22a8152007-09-04 17:43:37 +00001987
1988Dictionary views can be iterated over to yield their respective data, and
1989support membership tests:
1990
1991.. describe:: len(dictview)
1992
1993 Return the number of entries in the dictionary.
1994
1995.. describe:: iter(dictview)
1996
1997 Return an iterator over the keys, values or items (represented as tuples of
1998 ``(key, value)``) in the dictionary.
1999
2000 Keys and values are iterated over in an arbitrary order which is non-random,
2001 varies across Python implementations, and depends on the dictionary's history
2002 of insertions and deletions. If keys, values and items views are iterated
2003 over with no intervening modifications to the dictionary, the order of items
2004 will directly correspond. This allows the creation of ``(value, key)`` pairs
2005 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
2006 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
2007
Georg Brandl81269142009-05-17 08:31:29 +00002008 Iterating views while adding or deleting entries in the dictionary may raise
2009 a :exc:`RuntimeError` or fail to iterate over all entries.
Benjamin Petersond23f8222009-04-05 19:13:16 +00002010
Georg Brandld22a8152007-09-04 17:43:37 +00002011.. describe:: x in dictview
2012
2013 Return ``True`` if *x* is in the underlying dictionary's keys, values or
2014 items (in the latter case, *x* should be a ``(key, value)`` tuple).
2015
2016
Benjamin Petersonce0506c2008-11-17 21:47:41 +00002017Keys views are set-like since their entries are unique and hashable. If all
2018values are hashable, so that (key, value) pairs are unique and hashable, then
2019the items view is also set-like. (Values views are not treated as set-like
2020since the entries are generally not unique.) Then these set operations are
2021available ("other" refers either to another view or a set):
Georg Brandld22a8152007-09-04 17:43:37 +00002022
2023.. describe:: dictview & other
2024
2025 Return the intersection of the dictview and the other object as a new set.
2026
2027.. describe:: dictview | other
2028
2029 Return the union of the dictview and the other object as a new set.
2030
2031.. describe:: dictview - other
2032
2033 Return the difference between the dictview and the other object (all elements
2034 in *dictview* that aren't in *other*) as a new set.
2035
2036.. describe:: dictview ^ other
2037
2038 Return the symmetric difference (all elements either in *dictview* or
2039 *other*, but not in both) of the dictview and the other object as a new set.
2040
Georg Brandl116aa622007-08-15 14:28:22 +00002041
Georg Brandlc53c9662007-09-04 17:58:02 +00002042An example of dictionary view usage::
2043
2044 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
2045 >>> keys = dishes.keys()
2046 >>> values = dishes.values()
2047
2048 >>> # iteration
2049 >>> n = 0
2050 >>> for val in values:
2051 ... n += val
2052 >>> print(n)
2053 504
2054
2055 >>> # keys and values are iterated over in the same order
2056 >>> list(keys)
2057 ['eggs', 'bacon', 'sausage', 'spam']
2058 >>> list(values)
2059 [2, 1, 1, 500]
2060
2061 >>> # view objects are dynamic and reflect dict changes
2062 >>> del dishes['eggs']
2063 >>> del dishes['sausage']
2064 >>> list(keys)
2065 ['spam', 'bacon']
2066
2067 >>> # set operations
2068 >>> keys & {'eggs', 'bacon', 'salad'}
Gregory P. Smithe8388122008-09-04 04:18:09 +00002069 {'bacon'}
Georg Brandlc53c9662007-09-04 17:58:02 +00002070
2071
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002072.. _typememoryview:
2073
2074memoryview Types
2075================
2076
2077:class:`memoryview`\s allow Python code to access the internal data of an object
Georg Brandl1009d392008-09-10 07:14:18 +00002078that supports the buffer protocol without copying. Memory can be interpreted as
2079simple bytes or complex data structures.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002080
2081.. class:: memoryview(obj)
2082
Georg Brandl1009d392008-09-10 07:14:18 +00002083 Create a :class:`memoryview` that references *obj*. *obj* must support the
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002084 buffer protocol. Builtin objects that support the buffer protocol include
2085 :class:`bytes` and :class:`bytearray`.
2086
Antoine Pitroudac55ea2010-07-12 20:04:01 +00002087 A :class:`memoryview` has the notion of an *element*, which is the
2088 atomic memory unit handled by the originating object *obj*. For many
2089 simple types such as :class:`bytes` and :class:`bytearray`, an element
2090 is a single byte, but other types such as :class:`array.array` may have
2091 bigger elements.
2092
2093 ``len(view)`` returns the total number of elements in the memoryview,
2094 *view*. The :class:`~memoryview.itemsize` attribute will give you the
2095 number of bytes in a single element.
Benjamin Peterson5e19e442008-09-10 21:47:03 +00002096
Georg Brandl1009d392008-09-10 07:14:18 +00002097 A :class:`memoryview` supports slicing to expose its data. Taking a single
Antoine Pitroudac55ea2010-07-12 20:04:01 +00002098 index will return a single element as a :class:`bytes` object. Full
2099 slicing will result in a subview::
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002100
2101 >>> v = memoryview(b'abcefg')
2102 >>> v[1]
2103 b'b'
2104 >>> v[-1]
2105 b'g'
2106 >>> v[1:4]
2107 <memory at 0x77ab28>
2108 >>> bytes(v[1:4])
2109 b'bce'
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002110
Antoine Pitroudac55ea2010-07-12 20:04:01 +00002111 If the object the memoryview is over supports changing its data, the
Georg Brandl1009d392008-09-10 07:14:18 +00002112 memoryview supports slice assignment::
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002113
2114 >>> data = bytearray(b'abcefg')
2115 >>> v = memoryview(data)
2116 >>> v.readonly
2117 False
Benjamin Peterson52504012009-06-23 03:09:33 +00002118 >>> v[0] = b'z'
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002119 >>> data
2120 bytearray(b'zbcefg')
2121 >>> v[1:4] = b'123'
2122 >>> data
2123 bytearray(b'a123fg')
2124 >>> v[2] = b'spam'
2125 Traceback (most recent call last):
2126 File "<stdin>", line 1, in <module>
2127 ValueError: cannot modify size of memoryview object
2128
Georg Brandlc62efa82010-07-11 10:41:07 +00002129 Notice how the size of the memoryview object cannot be changed.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002130
Benjamin Peterson0c804652008-09-10 21:31:58 +00002131 :class:`memoryview` has two methods:
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002132
2133 .. method:: tobytes()
2134
Antoine Pitroudac55ea2010-07-12 20:04:01 +00002135 Return the data in the buffer as a bytestring. This is equivalent to
2136 calling the :class:`bytes` constructor on the memoryview. ::
2137
2138 >>> m = memoryview(b"abc")
2139 >>> m.tobytes()
2140 b'abc'
2141 >>> bytes(m)
2142 b'abc'
Benjamin Peterson0c804652008-09-10 21:31:58 +00002143
2144 .. method:: tolist()
2145
2146 Return the data in the buffer as a list of integers. ::
2147
2148 >>> memoryview(b'abc').tolist()
2149 [97, 98, 99]
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002150
2151 There are also several readonly attributes available:
2152
2153 .. attribute:: format
2154
2155 A string containing the format (in :mod:`struct` module style) for each
2156 element in the view. This defaults to ``'B'``, a simple bytestring.
2157
2158 .. attribute:: itemsize
2159
Antoine Pitroudac55ea2010-07-12 20:04:01 +00002160 The size in bytes of each element of the memoryview::
2161
2162 >>> m = memoryview(array.array('H', [1,2,3]))
2163 >>> m.itemsize
2164 2
2165 >>> m[0]
2166 b'\x01\x00'
2167 >>> len(m[0]) == m.itemsize
2168 True
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002169
2170 .. attribute:: shape
2171
Georg Brandl1009d392008-09-10 07:14:18 +00002172 A tuple of integers the length of :attr:`ndim` giving the shape of the
2173 memory as a N-dimensional array.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002174
2175 .. attribute:: ndim
2176
2177 An integer indicating how many dimensions of a multi-dimensional array the
2178 memory represents.
2179
2180 .. attribute:: strides
2181
Benjamin Peterson2409dc72008-09-10 21:38:31 +00002182 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2183 access each element for each dimension of the array.
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002184
Benjamin Peterson1b25b922008-09-09 22:15:27 +00002185 .. memoryview.suboffsets isn't documented because it only seems useful for C
2186
2187
Georg Brandl116aa622007-08-15 14:28:22 +00002188.. _typecontextmanager:
2189
2190Context Manager Types
2191=====================
2192
Georg Brandl116aa622007-08-15 14:28:22 +00002193.. index::
2194 single: context manager
2195 single: context management protocol
2196 single: protocol; context management
2197
2198Python's :keyword:`with` statement supports the concept of a runtime context
2199defined by a context manager. This is implemented using two separate methods
2200that allow user-defined classes to define a runtime context that is entered
2201before the statement body is executed and exited when the statement ends.
2202
2203The :dfn:`context management protocol` consists of a pair of methods that need
2204to be provided for a context manager object to define a runtime context:
2205
2206
2207.. method:: contextmanager.__enter__()
2208
2209 Enter the runtime context and return either this object or another object
2210 related to the runtime context. The value returned by this method is bound to
2211 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2212 this context manager.
2213
Antoine Pitrou25d535e2010-09-15 11:25:11 +00002214 An example of a context manager that returns itself is a :term:`file object`.
2215 File objects return themselves from __enter__() to allow :func:`open` to be
2216 used as the context expression in a :keyword:`with` statement.
Georg Brandl116aa622007-08-15 14:28:22 +00002217
2218 An example of a context manager that returns a related object is the one
Christian Heimesfaf2f632008-01-06 16:59:19 +00002219 returned by :func:`decimal.localcontext`. These managers set the active
Georg Brandl116aa622007-08-15 14:28:22 +00002220 decimal context to a copy of the original decimal context and then return the
2221 copy. This allows changes to be made to the current decimal context in the body
2222 of the :keyword:`with` statement without affecting code outside the
2223 :keyword:`with` statement.
2224
2225
2226.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2227
Georg Brandl9afde1c2007-11-01 20:32:30 +00002228 Exit the runtime context and return a Boolean flag indicating if any exception
Georg Brandl116aa622007-08-15 14:28:22 +00002229 that occurred should be suppressed. If an exception occurred while executing the
2230 body of the :keyword:`with` statement, the arguments contain the exception type,
2231 value and traceback information. Otherwise, all three arguments are ``None``.
2232
2233 Returning a true value from this method will cause the :keyword:`with` statement
2234 to suppress the exception and continue execution with the statement immediately
2235 following the :keyword:`with` statement. Otherwise the exception continues
2236 propagating after this method has finished executing. Exceptions that occur
2237 during execution of this method will replace any exception that occurred in the
2238 body of the :keyword:`with` statement.
2239
2240 The exception passed in should never be reraised explicitly - instead, this
2241 method should return a false value to indicate that the method completed
2242 successfully and does not want to suppress the raised exception. This allows
2243 context management code (such as ``contextlib.nested``) to easily detect whether
2244 or not an :meth:`__exit__` method has actually failed.
2245
2246Python defines several context managers to support easy thread synchronisation,
2247prompt closure of files or other objects, and simpler manipulation of the active
2248decimal arithmetic context. The specific types are not treated specially beyond
2249their implementation of the context management protocol. See the
2250:mod:`contextlib` module for some examples.
2251
Georg Brandl7baf6252009-09-01 08:13:16 +00002252Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator`
Christian Heimesd8654cf2007-12-02 15:22:16 +00002253provide a convenient way to implement these protocols. If a generator function is
Georg Brandl7baf6252009-09-01 08:13:16 +00002254decorated with the ``contextlib.contextmanager`` decorator, it will return a
Georg Brandl116aa622007-08-15 14:28:22 +00002255context manager implementing the necessary :meth:`__enter__` and
2256:meth:`__exit__` methods, rather than the iterator produced by an undecorated
2257generator function.
2258
2259Note that there is no specific slot for any of these methods in the type
2260structure for Python objects in the Python/C API. Extension types wanting to
2261define these methods must provide them as a normal Python accessible method.
2262Compared to the overhead of setting up the runtime context, the overhead of a
2263single class dictionary lookup is negligible.
2264
2265
2266.. _typesother:
2267
2268Other Built-in Types
2269====================
2270
2271The interpreter supports several other kinds of objects. Most of these support
2272only one or two operations.
2273
2274
2275.. _typesmodules:
2276
2277Modules
2278-------
2279
2280The only special operation on a module is attribute access: ``m.name``, where
2281*m* is a module and *name* accesses a name defined in *m*'s symbol table.
2282Module attributes can be assigned to. (Note that the :keyword:`import`
2283statement is not, strictly speaking, an operation on a module object; ``import
2284foo`` does not require a module object named *foo* to exist, rather it requires
2285an (external) *definition* for a module named *foo* somewhere.)
2286
2287A special member of every module is :attr:`__dict__`. This is the dictionary
2288containing the module's symbol table. Modifying this dictionary will actually
2289change the module's symbol table, but direct assignment to the :attr:`__dict__`
2290attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2291``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2292:attr:`__dict__` directly is not recommended.
2293
2294Modules built into the interpreter are written like this: ``<module 'sys'
2295(built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2296'/usr/local/lib/pythonX.Y/os.pyc'>``.
2297
2298
2299.. _typesobjects:
2300
2301Classes and Class Instances
2302---------------------------
2303
2304See :ref:`objects` and :ref:`class` for these.
2305
2306
2307.. _typesfunctions:
2308
2309Functions
2310---------
2311
2312Function objects are created by function definitions. The only operation on a
2313function object is to call it: ``func(argument-list)``.
2314
2315There are really two flavors of function objects: built-in functions and
2316user-defined functions. Both support the same operation (to call the function),
2317but the implementation is different, hence the different object types.
2318
2319See :ref:`function` for more information.
2320
2321
2322.. _typesmethods:
2323
2324Methods
2325-------
2326
2327.. index:: object: method
2328
2329Methods are functions that are called using the attribute notation. There are
2330two flavors: built-in methods (such as :meth:`append` on lists) and class
2331instance methods. Built-in methods are described with the types that support
2332them.
2333
Georg Brandl2e0b7552007-11-27 12:43:08 +00002334If you access a method (a function defined in a class namespace) through an
2335instance, you get a special object: a :dfn:`bound method` (also called
2336:dfn:`instance method`) object. When called, it will add the ``self`` argument
2337to the argument list. Bound methods have two special read-only attributes:
2338``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
2339the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
2340is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
2341arg-n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00002342
Georg Brandl2e0b7552007-11-27 12:43:08 +00002343Like function objects, bound method objects support getting arbitrary
2344attributes. However, since method attributes are actually stored on the
2345underlying function object (``meth.__func__``), setting method attributes on
2346bound methods is disallowed. Attempting to set a method attribute results in a
Georg Brandl116aa622007-08-15 14:28:22 +00002347:exc:`TypeError` being raised. In order to set a method attribute, you need to
2348explicitly set it on the underlying function object::
2349
2350 class C:
2351 def method(self):
2352 pass
2353
2354 c = C()
Christian Heimesff737952007-11-27 10:40:20 +00002355 c.method.__func__.whoami = 'my name is c'
Georg Brandl116aa622007-08-15 14:28:22 +00002356
2357See :ref:`types` for more information.
2358
2359
2360.. _bltin-code-objects:
2361
2362Code Objects
2363------------
2364
2365.. index:: object: code
2366
2367.. index::
2368 builtin: compile
2369 single: __code__ (function object attribute)
2370
2371Code objects are used by the implementation to represent "pseudo-compiled"
2372executable Python code such as a function body. They differ from function
2373objects because they don't contain a reference to their global execution
2374environment. Code objects are returned by the built-in :func:`compile` function
2375and can be extracted from function objects through their :attr:`__code__`
2376attribute. See also the :mod:`code` module.
2377
2378.. index::
2379 builtin: exec
2380 builtin: eval
2381
2382A code object can be executed or evaluated by passing it (instead of a source
2383string) to the :func:`exec` or :func:`eval` built-in functions.
2384
2385See :ref:`types` for more information.
2386
2387
2388.. _bltin-type-objects:
2389
2390Type Objects
2391------------
2392
2393.. index::
2394 builtin: type
2395 module: types
2396
2397Type objects represent the various object types. An object's type is accessed
2398by the built-in function :func:`type`. There are no special operations on
2399types. The standard module :mod:`types` defines names for all standard built-in
2400types.
2401
Martin v. Löwis250ad612008-04-07 05:43:42 +00002402Types are written like this: ``<class 'int'>``.
Georg Brandl116aa622007-08-15 14:28:22 +00002403
2404
2405.. _bltin-null-object:
2406
2407The Null Object
2408---------------
2409
2410This object is returned by functions that don't explicitly return a value. It
2411supports no special operations. There is exactly one null object, named
2412``None`` (a built-in name).
2413
2414It is written as ``None``.
2415
2416
2417.. _bltin-ellipsis-object:
2418
2419The Ellipsis Object
2420-------------------
2421
Georg Brandlcb8ecb12007-09-04 06:35:14 +00002422This object is commonly used by slicing (see :ref:`slicings`). It supports no
2423special operations. There is exactly one ellipsis object, named
Georg Brandl116aa622007-08-15 14:28:22 +00002424:const:`Ellipsis` (a built-in name).
2425
2426It is written as ``Ellipsis`` or ``...``.
2427
2428
2429Boolean Values
2430--------------
2431
2432Boolean values are the two constant objects ``False`` and ``True``. They are
2433used to represent truth values (although other values can also be considered
2434false or true). In numeric contexts (for example when used as the argument to
2435an arithmetic operator), they behave like the integers 0 and 1, respectively.
2436The built-in function :func:`bool` can be used to cast any value to a Boolean,
2437if the value can be interpreted as a truth value (see section Truth Value
2438Testing above).
2439
2440.. index::
2441 single: False
2442 single: True
2443 pair: Boolean; values
2444
2445They are written as ``False`` and ``True``, respectively.
2446
2447
2448.. _typesinternal:
2449
2450Internal Objects
2451----------------
2452
2453See :ref:`types` for this information. It describes stack frame objects,
2454traceback objects, and slice objects.
2455
2456
2457.. _specialattrs:
2458
2459Special Attributes
2460==================
2461
2462The implementation adds a few special read-only attributes to several object
2463types, where they are relevant. Some of these are not reported by the
2464:func:`dir` built-in function.
2465
2466
2467.. attribute:: object.__dict__
2468
2469 A dictionary or other mapping object used to store an object's (writable)
2470 attributes.
2471
2472
2473.. attribute:: instance.__class__
2474
2475 The class to which a class instance belongs.
2476
2477
2478.. attribute:: class.__bases__
2479
Benjamin Peterson68dbebc2009-12-31 03:30:26 +00002480 The tuple of base classes of a class object.
Georg Brandl116aa622007-08-15 14:28:22 +00002481
2482
2483.. attribute:: class.__name__
2484
2485 The name of the class or type.
2486
Georg Brandl7a51e582009-03-28 19:13:21 +00002487
Benjamin Petersond23f8222009-04-05 19:13:16 +00002488The following attributes are only supported by :term:`new-style class`\ es.
2489
2490.. attribute:: class.__mro__
2491
2492 This attribute is a tuple of classes that are considered when looking for
2493 base classes during method resolution.
2494
2495
2496.. method:: class.mro()
2497
2498 This method can be overridden by a metaclass to customize the method
2499 resolution order for its instances. It is called at class instantiation, and
2500 its result is stored in :attr:`__mro__`.
2501
2502
Georg Brandl7a51e582009-03-28 19:13:21 +00002503.. method:: class.__subclasses__
2504
Benjamin Petersond23f8222009-04-05 19:13:16 +00002505 Each new-style class keeps a list of weak references to its immediate
2506 subclasses. This method returns a list of all those references still alive.
2507 Example::
Georg Brandl7a51e582009-03-28 19:13:21 +00002508
2509 >>> int.__subclasses__()
2510 [<type 'bool'>]
2511
2512
Georg Brandl116aa622007-08-15 14:28:22 +00002513.. rubric:: Footnotes
2514
2515.. [#] Additional information on these special methods may be found in the Python
2516 Reference Manual (:ref:`customization`).
2517
2518.. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2519 similarly for tuples.
2520
2521.. [#] They must have since the parser can't tell the type of the operands.
2522
2523.. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2524 element is the tuple to be formatted.