Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. XXX: reference/datamodel and this have quite a few overlaps! |
| 2 | |
| 3 | |
| 4 | .. _bltin-types: |
| 5 | |
| 6 | ************** |
| 7 | Built-in Types |
| 8 | ************** |
| 9 | |
| 10 | The following sections describe the standard types that are built into the |
| 11 | interpreter. |
| 12 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | .. index:: pair: built-in; types |
| 14 | |
Antoine Pitrou | e231e39 | 2009-12-19 18:22:15 +0000 | [diff] [blame] | 15 | The principal built-in types are numerics, sequences, mappings, classes, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | instances and exceptions. |
| 17 | |
Georg Brandl | 388349a | 2011-10-08 18:32:40 +0200 | [diff] [blame] | 18 | Some collection classes are mutable. The methods that add, subtract, or |
| 19 | rearrange their members in place, and don't return a specific item, never return |
| 20 | the collection instance itself but ``None``. |
| 21 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 22 | Some operations are supported by several object types; in particular, |
| 23 | practically all objects can be compared, tested for truth value, and converted |
| 24 | to a string (with the :func:`repr` function or the slightly different |
| 25 | :func:`str` function). The latter function is implicitly used when an object is |
| 26 | written by the :func:`print` function. |
| 27 | |
| 28 | |
| 29 | .. _truth: |
| 30 | |
| 31 | Truth Value Testing |
| 32 | =================== |
| 33 | |
| 34 | .. index:: |
| 35 | statement: if |
| 36 | statement: while |
| 37 | pair: truth; value |
| 38 | pair: Boolean; operations |
| 39 | single: false |
| 40 | |
| 41 | Any object can be tested for truth value, for use in an :keyword:`if` or |
| 42 | :keyword:`while` condition or as operand of the Boolean operations below. The |
| 43 | following values are considered false: |
| 44 | |
| 45 | .. index:: single: None (Built-in object) |
| 46 | |
| 47 | * ``None`` |
| 48 | |
| 49 | .. index:: single: False (Built-in object) |
| 50 | |
| 51 | * ``False`` |
| 52 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 53 | * zero of any numeric type, for example, ``0``, ``0.0``, ``0j``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 54 | |
| 55 | * any empty sequence, for example, ``''``, ``()``, ``[]``. |
| 56 | |
| 57 | * any empty mapping, for example, ``{}``. |
| 58 | |
| 59 | * instances of user-defined classes, if the class defines a :meth:`__bool__` or |
| 60 | :meth:`__len__` method, when that method returns the integer zero or |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 61 | :class:`bool` value ``False``. [1]_ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 62 | |
| 63 | .. index:: single: true |
| 64 | |
| 65 | All other values are considered true --- so objects of many types are always |
| 66 | true. |
| 67 | |
| 68 | .. index:: |
| 69 | operator: or |
| 70 | operator: and |
| 71 | single: False |
| 72 | single: True |
| 73 | |
| 74 | Operations and built-in functions that have a Boolean result always return ``0`` |
| 75 | or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated. |
| 76 | (Important exception: the Boolean operations ``or`` and ``and`` always return |
| 77 | one of their operands.) |
| 78 | |
| 79 | |
| 80 | .. _boolean: |
| 81 | |
| 82 | Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not` |
| 83 | ==================================================================== |
| 84 | |
| 85 | .. index:: pair: Boolean; operations |
| 86 | |
| 87 | These are the Boolean operations, ordered by ascending priority: |
| 88 | |
| 89 | +-------------+---------------------------------+-------+ |
| 90 | | Operation | Result | Notes | |
| 91 | +=============+=================================+=======+ |
| 92 | | ``x or y`` | if *x* is false, then *y*, else | \(1) | |
| 93 | | | *x* | | |
| 94 | +-------------+---------------------------------+-------+ |
| 95 | | ``x and y`` | if *x* is false, then *x*, else | \(2) | |
| 96 | | | *y* | | |
| 97 | +-------------+---------------------------------+-------+ |
| 98 | | ``not x`` | if *x* is false, then ``True``, | \(3) | |
| 99 | | | else ``False`` | | |
| 100 | +-------------+---------------------------------+-------+ |
| 101 | |
| 102 | .. index:: |
| 103 | operator: and |
| 104 | operator: or |
| 105 | operator: not |
| 106 | |
| 107 | Notes: |
| 108 | |
| 109 | (1) |
| 110 | This is a short-circuit operator, so it only evaluates the second |
| 111 | argument if the first one is :const:`False`. |
| 112 | |
| 113 | (2) |
| 114 | This is a short-circuit operator, so it only evaluates the second |
| 115 | argument if the first one is :const:`True`. |
| 116 | |
| 117 | (3) |
| 118 | ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is |
| 119 | interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error. |
| 120 | |
| 121 | |
| 122 | .. _stdcomparisons: |
| 123 | |
| 124 | Comparisons |
| 125 | =========== |
| 126 | |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 127 | .. index:: |
| 128 | pair: chaining; comparisons |
| 129 | pair: operator; comparison |
| 130 | operator: == |
| 131 | operator: < |
| 132 | operator: <= |
| 133 | operator: > |
| 134 | operator: >= |
| 135 | operator: != |
| 136 | operator: is |
| 137 | operator: is not |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 138 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 139 | There are eight comparison operations in Python. They all have the same |
| 140 | priority (which is higher than that of the Boolean operations). Comparisons can |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 141 | be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and |
| 142 | y <= z``, except that *y* is evaluated only once (but in both cases *z* is not |
| 143 | evaluated at all when ``x < y`` is found to be false). |
| 144 | |
| 145 | This table summarizes the comparison operations: |
| 146 | |
Georg Brandl | fd85516 | 2008-01-07 09:13:03 +0000 | [diff] [blame] | 147 | +------------+-------------------------+ |
| 148 | | Operation | Meaning | |
| 149 | +============+=========================+ |
| 150 | | ``<`` | strictly less than | |
| 151 | +------------+-------------------------+ |
| 152 | | ``<=`` | less than or equal | |
| 153 | +------------+-------------------------+ |
| 154 | | ``>`` | strictly greater than | |
| 155 | +------------+-------------------------+ |
| 156 | | ``>=`` | greater than or equal | |
| 157 | +------------+-------------------------+ |
| 158 | | ``==`` | equal | |
| 159 | +------------+-------------------------+ |
| 160 | | ``!=`` | not equal | |
| 161 | +------------+-------------------------+ |
| 162 | | ``is`` | object identity | |
| 163 | +------------+-------------------------+ |
| 164 | | ``is not`` | negated object identity | |
| 165 | +------------+-------------------------+ |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 166 | |
| 167 | .. index:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 168 | pair: object; numeric |
| 169 | pair: objects; comparing |
| 170 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 171 | Objects of different types, except different numeric types, never compare equal. |
Antoine Pitrou | e231e39 | 2009-12-19 18:22:15 +0000 | [diff] [blame] | 172 | Furthermore, some types (for example, function objects) support only a degenerate |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 173 | notion of comparison where any two objects of that type are unequal. The ``<``, |
| 174 | ``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when |
Mark Dickinson | f673f0c | 2010-03-13 09:48:39 +0000 | [diff] [blame] | 175 | comparing a complex number with another built-in numeric type, when the objects |
| 176 | are of different types that cannot be compared, or in other cases where there is |
| 177 | no defined ordering. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 178 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 179 | .. index:: |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 180 | single: __eq__() (instance method) |
| 181 | single: __ne__() (instance method) |
| 182 | single: __lt__() (instance method) |
| 183 | single: __le__() (instance method) |
| 184 | single: __gt__() (instance method) |
| 185 | single: __ge__() (instance method) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 186 | |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 187 | Non-identical instances of a class normally compare as non-equal unless the |
| 188 | class defines the :meth:`__eq__` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 189 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 190 | Instances of a class cannot be ordered with respect to other instances of the |
| 191 | same class, or other types of object, unless the class defines enough of the |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 192 | methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in |
| 193 | general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the |
| 194 | conventional meanings of the comparison operators). |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 195 | |
| 196 | The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be |
| 197 | customized; also they can be applied to any two objects and never raise an |
| 198 | exception. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 199 | |
| 200 | .. index:: |
| 201 | operator: in |
| 202 | operator: not in |
| 203 | |
Georg Brandl | 375aec2 | 2011-01-15 17:03:02 +0000 | [diff] [blame] | 204 | Two more operations with the same syntactic priority, :keyword:`in` and |
| 205 | :keyword:`not in`, are supported only by sequence types (below). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 206 | |
| 207 | |
| 208 | .. _typesnumeric: |
| 209 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 210 | Numeric Types --- :class:`int`, :class:`float`, :class:`complex` |
| 211 | ================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | |
| 213 | .. index:: |
| 214 | object: numeric |
| 215 | object: Boolean |
| 216 | object: integer |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 217 | object: floating point |
| 218 | object: complex number |
| 219 | pair: C; language |
| 220 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 221 | There are three distinct numeric types: :dfn:`integers`, :dfn:`floating |
| 222 | point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a |
| 223 | subtype of integers. Integers have unlimited precision. Floating point |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 224 | numbers are usually implemented using :c:type:`double` in C; information |
Mark Dickinson | 74f5902 | 2010-08-04 18:42:43 +0000 | [diff] [blame] | 225 | about the precision and internal representation of floating point |
| 226 | numbers for the machine on which your program is running is available |
| 227 | in :data:`sys.float_info`. Complex numbers have a real and imaginary |
| 228 | part, which are each a floating point number. To extract these parts |
| 229 | from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard |
| 230 | library includes additional numeric types, :mod:`fractions` that hold |
| 231 | rationals, and :mod:`decimal` that hold floating-point numbers with |
| 232 | user-definable precision.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 233 | |
| 234 | .. index:: |
| 235 | pair: numeric; literals |
| 236 | pair: integer; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 237 | pair: floating point; literals |
| 238 | pair: complex number; literals |
| 239 | pair: hexadecimal; literals |
| 240 | pair: octal; literals |
Neal Norwitz | 1d2aef5 | 2007-10-02 07:26:14 +0000 | [diff] [blame] | 241 | pair: binary; literals |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 242 | |
| 243 | Numbers are created by numeric literals or as the result of built-in functions |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 244 | and operators. Unadorned integer literals (including hex, octal and binary |
| 245 | numbers) yield integers. Numeric literals containing a decimal point or an |
| 246 | exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a |
| 247 | numeric literal yields an imaginary number (a complex number with a zero real |
| 248 | part) which you can add to an integer or float to get a complex number with real |
| 249 | and imaginary parts. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 250 | |
| 251 | .. index:: |
| 252 | single: arithmetic |
| 253 | builtin: int |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 254 | builtin: float |
| 255 | builtin: complex |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 256 | operator: + |
| 257 | operator: - |
| 258 | operator: * |
| 259 | operator: / |
| 260 | operator: // |
| 261 | operator: % |
| 262 | operator: ** |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 263 | |
| 264 | Python fully supports mixed arithmetic: when a binary arithmetic operator has |
| 265 | operands of different numeric types, the operand with the "narrower" type is |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 266 | widened to that of the other, where integer is narrower than floating point, |
| 267 | which is narrower than complex. Comparisons between numbers of mixed type use |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 268 | the same rule. [2]_ The constructors :func:`int`, :func:`float`, and |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 269 | :func:`complex` can be used to produce numbers of a specific type. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 270 | |
| 271 | All numeric types (except complex) support the following operations, sorted by |
| 272 | ascending priority (operations in the same box have the same priority; all |
| 273 | numeric operations have a higher priority than comparison operations): |
| 274 | |
Raymond Hettinger | c706dbf | 2011-03-22 17:33:17 -0700 | [diff] [blame] | 275 | +---------------------+---------------------------------+---------+--------------------+ |
| 276 | | Operation | Result | Notes | Full documentation | |
| 277 | +=====================+=================================+=========+====================+ |
| 278 | | ``x + y`` | sum of *x* and *y* | | | |
| 279 | +---------------------+---------------------------------+---------+--------------------+ |
| 280 | | ``x - y`` | difference of *x* and *y* | | | |
| 281 | +---------------------+---------------------------------+---------+--------------------+ |
| 282 | | ``x * y`` | product of *x* and *y* | | | |
| 283 | +---------------------+---------------------------------+---------+--------------------+ |
| 284 | | ``x / y`` | quotient of *x* and *y* | | | |
| 285 | +---------------------+---------------------------------+---------+--------------------+ |
| 286 | | ``x // y`` | floored quotient of *x* and | \(1) | | |
| 287 | | | *y* | | | |
| 288 | +---------------------+---------------------------------+---------+--------------------+ |
| 289 | | ``x % y`` | remainder of ``x / y`` | \(2) | | |
| 290 | +---------------------+---------------------------------+---------+--------------------+ |
| 291 | | ``-x`` | *x* negated | | | |
| 292 | +---------------------+---------------------------------+---------+--------------------+ |
| 293 | | ``+x`` | *x* unchanged | | | |
| 294 | +---------------------+---------------------------------+---------+--------------------+ |
| 295 | | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | |
| 296 | | | *x* | | | |
| 297 | +---------------------+---------------------------------+---------+--------------------+ |
| 298 | | ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` | |
| 299 | +---------------------+---------------------------------+---------+--------------------+ |
| 300 | | ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` | |
| 301 | +---------------------+---------------------------------+---------+--------------------+ |
| 302 | | ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` | |
| 303 | | | *re*, imaginary part *im*. | | | |
| 304 | | | *im* defaults to zero. | | | |
| 305 | +---------------------+---------------------------------+---------+--------------------+ |
| 306 | | ``c.conjugate()`` | conjugate of the complex number | | | |
| 307 | | | *c* | | | |
| 308 | +---------------------+---------------------------------+---------+--------------------+ |
| 309 | | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | |
| 310 | +---------------------+---------------------------------+---------+--------------------+ |
| 311 | | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` | |
| 312 | +---------------------+---------------------------------+---------+--------------------+ |
| 313 | | ``x ** y`` | *x* to the power *y* | \(5) | | |
| 314 | +---------------------+---------------------------------+---------+--------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 315 | |
| 316 | .. index:: |
| 317 | triple: operations on; numeric; types |
| 318 | single: conjugate() (complex number method) |
| 319 | |
| 320 | Notes: |
| 321 | |
| 322 | (1) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 323 | Also referred to as integer division. The resultant value is a whole |
| 324 | integer, though the result's type is not necessarily int. The result is |
| 325 | always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is |
| 326 | ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 327 | |
| 328 | (2) |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 329 | Not for complex numbers. Instead convert to floats using :func:`abs` if |
| 330 | appropriate. |
| 331 | |
| 332 | (3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 333 | .. index:: |
| 334 | module: math |
| 335 | single: floor() (in module math) |
| 336 | single: ceil() (in module math) |
Benjamin Peterson | 28d88b4 | 2009-01-09 03:03:23 +0000 | [diff] [blame] | 337 | single: trunc() (in module math) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 338 | pair: numeric; conversions |
| 339 | pair: C; language |
| 340 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 341 | Conversion from floating point to integer may round or truncate |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 342 | as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module |
| 343 | for well-defined conversions. |
| 344 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 345 | (4) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 346 | float also accepts the strings "nan" and "inf" with an optional prefix "+" |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 347 | or "-" for Not a Number (NaN) and positive or negative infinity. |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 348 | |
Georg Brandl | 74f3669 | 2008-01-06 17:39:49 +0000 | [diff] [blame] | 349 | (5) |
Christian Heimes | 7f04431 | 2008-01-06 17:05:40 +0000 | [diff] [blame] | 350 | Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for |
| 351 | programming languages. |
| 352 | |
Raymond Hettinger | c706dbf | 2011-03-22 17:33:17 -0700 | [diff] [blame] | 353 | (6) |
| 354 | The numeric literals accepted include the digits ``0`` to ``9`` or any |
| 355 | Unicode equivalent (code points with the ``Nd`` property). |
| 356 | |
| 357 | See http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedNumericType.txt |
| 358 | for a complete list of code points with the ``Nd`` property. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 359 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 360 | |
Benjamin Peterson | 10116d4 | 2011-05-01 17:38:17 -0500 | [diff] [blame] | 361 | All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include |
| 362 | the following operations: |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 363 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 364 | +--------------------+------------------------------------+--------+ |
| 365 | | Operation | Result | Notes | |
| 366 | +====================+====================================+========+ |
| 367 | | ``math.trunc(x)`` | *x* truncated to Integral | | |
| 368 | +--------------------+------------------------------------+--------+ |
| 369 | | ``round(x[, n])`` | *x* rounded to n digits, | | |
| 370 | | | rounding half to even. If n is | | |
| 371 | | | omitted, it defaults to 0. | | |
| 372 | +--------------------+------------------------------------+--------+ |
| 373 | | ``math.floor(x)`` | the greatest integral float <= *x* | | |
| 374 | +--------------------+------------------------------------+--------+ |
| 375 | | ``math.ceil(x)`` | the least integral float >= *x* | | |
| 376 | +--------------------+------------------------------------+--------+ |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 377 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 378 | For additional numeric operations see the :mod:`math` and :mod:`cmath` |
| 379 | modules. |
| 380 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 381 | .. XXXJH exceptions: overflow (when? what operations?) zerodivision |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 382 | |
| 383 | |
| 384 | .. _bitstring-ops: |
| 385 | |
Benjamin Peterson | e9fca25 | 2012-01-25 16:29:03 -0500 | [diff] [blame] | 386 | Bitwise Operations on Integer Types |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 387 | -------------------------------------- |
| 388 | |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 389 | .. index:: |
| 390 | triple: operations on; integer; types |
Benjamin Peterson | e9fca25 | 2012-01-25 16:29:03 -0500 | [diff] [blame] | 391 | pair: bitwise; operations |
Alexandre Vassalotti | 6d3dfc3 | 2009-07-29 19:54:39 +0000 | [diff] [blame] | 392 | pair: shifting; operations |
| 393 | pair: masking; operations |
| 394 | operator: ^ |
| 395 | operator: & |
| 396 | operator: << |
| 397 | operator: >> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | |
Benjamin Peterson | b4b0b35 | 2012-01-25 16:30:18 -0500 | [diff] [blame] | 399 | Bitwise operations only make sense for integers. Negative numbers are treated |
| 400 | as their 2's complement value (this assumes a sufficiently large number of bits |
| 401 | that no overflow occurs during the operation). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 402 | |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 403 | The priorities of the binary bitwise operations are all lower than the numeric |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 404 | operations and higher than the comparisons; the unary operation ``~`` has the |
| 405 | same priority as the other unary numeric operations (``+`` and ``-``). |
| 406 | |
Benjamin Peterson | e9fca25 | 2012-01-25 16:29:03 -0500 | [diff] [blame] | 407 | This table lists the bitwise operations sorted in ascending priority |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 408 | (operations in the same box have the same priority): |
| 409 | |
| 410 | +------------+--------------------------------+----------+ |
| 411 | | Operation | Result | Notes | |
| 412 | +============+================================+==========+ |
| 413 | | ``x | y`` | bitwise :dfn:`or` of *x* and | | |
| 414 | | | *y* | | |
| 415 | +------------+--------------------------------+----------+ |
| 416 | | ``x ^ y`` | bitwise :dfn:`exclusive or` of | | |
| 417 | | | *x* and *y* | | |
| 418 | +------------+--------------------------------+----------+ |
| 419 | | ``x & y`` | bitwise :dfn:`and` of *x* and | | |
| 420 | | | *y* | | |
| 421 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 422 | | ``x << n`` | *x* shifted left by *n* bits | (1)(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 423 | +------------+--------------------------------+----------+ |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 424 | | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 425 | +------------+--------------------------------+----------+ |
| 426 | | ``~x`` | the bits of *x* inverted | | |
| 427 | +------------+--------------------------------+----------+ |
| 428 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 429 | Notes: |
| 430 | |
| 431 | (1) |
| 432 | Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. |
| 433 | |
| 434 | (2) |
| 435 | A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)`` |
| 436 | without overflow check. |
| 437 | |
| 438 | (3) |
| 439 | A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without |
| 440 | overflow check. |
| 441 | |
| 442 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 443 | Additional Methods on Integer Types |
| 444 | ----------------------------------- |
| 445 | |
Raymond Hettinger | 9b2fd32 | 2011-05-01 18:14:49 -0700 | [diff] [blame] | 446 | The int type implements the :class:`numbers.Integral` :term:`abstract base |
Éric Araujo | b79c234 | 2011-05-02 13:10:18 +0200 | [diff] [blame] | 447 | class`. In addition, it provides one more method: |
Benjamin Peterson | 10116d4 | 2011-05-01 17:38:17 -0500 | [diff] [blame] | 448 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 449 | .. method:: int.bit_length() |
| 450 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 451 | Return the number of bits necessary to represent an integer in binary, |
| 452 | excluding the sign and leading zeros:: |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 453 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 454 | >>> n = -37 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 455 | >>> bin(n) |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 456 | '-0b100101' |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 457 | >>> n.bit_length() |
| 458 | 6 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 459 | |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 460 | More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the |
| 461 | unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``. |
| 462 | Equivalently, when ``abs(x)`` is small enough to have a correctly |
| 463 | rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``. |
| 464 | If ``x`` is zero, then ``x.bit_length()`` returns ``0``. |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 465 | |
| 466 | Equivalent to:: |
| 467 | |
| 468 | def bit_length(self): |
Senthil Kumaran | 0aae6dc | 2010-06-22 02:57:23 +0000 | [diff] [blame] | 469 | s = bin(self) # binary representation: bin(-37) --> '-0b100101' |
Raymond Hettinger | d3e18b7 | 2008-12-19 09:11:49 +0000 | [diff] [blame] | 470 | s = s.lstrip('-0b') # remove leading zeros and minus sign |
| 471 | return len(s) # len('100101') --> 6 |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 472 | |
| 473 | .. versionadded:: 3.1 |
| 474 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 475 | .. method:: int.to_bytes(length, byteorder, \*, signed=False) |
Alexandre Vassalotti | c36c378 | 2010-01-09 20:35:09 +0000 | [diff] [blame] | 476 | |
| 477 | Return an array of bytes representing an integer. |
| 478 | |
| 479 | >>> (1024).to_bytes(2, byteorder='big') |
| 480 | b'\x04\x00' |
| 481 | >>> (1024).to_bytes(10, byteorder='big') |
| 482 | b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' |
| 483 | >>> (-1024).to_bytes(10, byteorder='big', signed=True) |
| 484 | b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' |
| 485 | >>> x = 1000 |
| 486 | >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little') |
| 487 | b'\xe8\x03' |
| 488 | |
| 489 | The integer is represented using *length* bytes. An :exc:`OverflowError` |
| 490 | is raised if the integer is not representable with the given number of |
| 491 | bytes. |
| 492 | |
| 493 | The *byteorder* argument determines the byte order used to represent the |
| 494 | integer. If *byteorder* is ``"big"``, the most significant byte is at the |
| 495 | beginning of the byte array. If *byteorder* is ``"little"``, the most |
| 496 | significant byte is at the end of the byte array. To request the native |
| 497 | byte order of the host system, use :data:`sys.byteorder` as the byte order |
| 498 | value. |
| 499 | |
| 500 | The *signed* argument determines whether two's complement is used to |
| 501 | represent the integer. If *signed* is ``False`` and a negative integer is |
| 502 | given, an :exc:`OverflowError` is raised. The default value for *signed* |
| 503 | is ``False``. |
| 504 | |
| 505 | .. versionadded:: 3.2 |
| 506 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 507 | .. classmethod:: int.from_bytes(bytes, byteorder, \*, signed=False) |
Alexandre Vassalotti | c36c378 | 2010-01-09 20:35:09 +0000 | [diff] [blame] | 508 | |
| 509 | Return the integer represented by the given array of bytes. |
| 510 | |
| 511 | >>> int.from_bytes(b'\x00\x10', byteorder='big') |
| 512 | 16 |
| 513 | >>> int.from_bytes(b'\x00\x10', byteorder='little') |
| 514 | 4096 |
| 515 | >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) |
| 516 | -1024 |
| 517 | >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) |
| 518 | 64512 |
| 519 | >>> int.from_bytes([255, 0, 0], byteorder='big') |
| 520 | 16711680 |
| 521 | |
| 522 | The argument *bytes* must either support the buffer protocol or be an |
| 523 | iterable producing bytes. :class:`bytes` and :class:`bytearray` are |
| 524 | examples of built-in objects that support the buffer protocol. |
| 525 | |
| 526 | The *byteorder* argument determines the byte order used to represent the |
| 527 | integer. If *byteorder* is ``"big"``, the most significant byte is at the |
| 528 | beginning of the byte array. If *byteorder* is ``"little"``, the most |
| 529 | significant byte is at the end of the byte array. To request the native |
| 530 | byte order of the host system, use :data:`sys.byteorder` as the byte order |
| 531 | value. |
| 532 | |
| 533 | The *signed* argument indicates whether two's complement is used to |
| 534 | represent the integer. |
| 535 | |
| 536 | .. versionadded:: 3.2 |
| 537 | |
Mark Dickinson | 54bc1ec | 2008-12-17 16:19:07 +0000 | [diff] [blame] | 538 | |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 539 | Additional Methods on Float |
| 540 | --------------------------- |
| 541 | |
Benjamin Peterson | 10116d4 | 2011-05-01 17:38:17 -0500 | [diff] [blame] | 542 | The float type implements the :class:`numbers.Real` :term:`abstract base |
| 543 | class`. float also has the following additional methods. |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 544 | |
| 545 | .. method:: float.as_integer_ratio() |
| 546 | |
Mark Dickinson | 4a3c7c4 | 2010-11-07 12:48:18 +0000 | [diff] [blame] | 547 | Return a pair of integers whose ratio is exactly equal to the |
| 548 | original float and with a positive denominator. Raises |
| 549 | :exc:`OverflowError` on infinities and a :exc:`ValueError` on |
| 550 | NaNs. |
| 551 | |
| 552 | .. method:: float.is_integer() |
| 553 | |
| 554 | Return ``True`` if the float instance is finite with integral |
| 555 | value, and ``False`` otherwise:: |
| 556 | |
| 557 | >>> (-2.0).is_integer() |
| 558 | True |
| 559 | >>> (3.2).is_integer() |
| 560 | False |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 561 | |
Benjamin Peterson | d7b0328 | 2008-09-13 15:58:53 +0000 | [diff] [blame] | 562 | Two methods support conversion to |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 563 | and from hexadecimal strings. Since Python's floats are stored |
| 564 | internally as binary numbers, converting a float to or from a |
| 565 | *decimal* string usually involves a small rounding error. In |
| 566 | contrast, hexadecimal strings allow exact representation and |
| 567 | specification of floating-point numbers. This can be useful when |
| 568 | debugging, and in numerical work. |
| 569 | |
| 570 | |
| 571 | .. method:: float.hex() |
| 572 | |
| 573 | Return a representation of a floating-point number as a hexadecimal |
| 574 | string. For finite floating-point numbers, this representation |
| 575 | will always include a leading ``0x`` and a trailing ``p`` and |
| 576 | exponent. |
| 577 | |
| 578 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 579 | .. classmethod:: float.fromhex(s) |
Mark Dickinson | 65fe25e | 2008-07-16 11:30:51 +0000 | [diff] [blame] | 580 | |
| 581 | Class method to return the float represented by a hexadecimal |
| 582 | string *s*. The string *s* may have leading and trailing |
| 583 | whitespace. |
| 584 | |
| 585 | |
| 586 | Note that :meth:`float.hex` is an instance method, while |
| 587 | :meth:`float.fromhex` is a class method. |
| 588 | |
| 589 | A hexadecimal string takes the form:: |
| 590 | |
| 591 | [sign] ['0x'] integer ['.' fraction] ['p' exponent] |
| 592 | |
| 593 | where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` |
| 594 | and ``fraction`` are strings of hexadecimal digits, and ``exponent`` |
| 595 | is a decimal integer with an optional leading sign. Case is not |
| 596 | significant, and there must be at least one hexadecimal digit in |
| 597 | either the integer or the fraction. This syntax is similar to the |
| 598 | syntax specified in section 6.4.4.2 of the C99 standard, and also to |
| 599 | the syntax used in Java 1.5 onwards. In particular, the output of |
| 600 | :meth:`float.hex` is usable as a hexadecimal floating-point literal in |
| 601 | C or Java code, and hexadecimal strings produced by C's ``%a`` format |
| 602 | character or Java's ``Double.toHexString`` are accepted by |
| 603 | :meth:`float.fromhex`. |
| 604 | |
| 605 | |
| 606 | Note that the exponent is written in decimal rather than hexadecimal, |
| 607 | and that it gives the power of 2 by which to multiply the coefficient. |
| 608 | For example, the hexadecimal string ``0x3.a7p10`` represents the |
| 609 | floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or |
| 610 | ``3740.0``:: |
| 611 | |
| 612 | >>> float.fromhex('0x3.a7p10') |
| 613 | 3740.0 |
| 614 | |
| 615 | |
| 616 | Applying the reverse conversion to ``3740.0`` gives a different |
| 617 | hexadecimal string representing the same number:: |
| 618 | |
| 619 | >>> float.hex(3740.0) |
| 620 | '0x1.d380000000000p+11' |
| 621 | |
| 622 | |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 623 | .. _numeric-hash: |
| 624 | |
| 625 | Hashing of numeric types |
| 626 | ------------------------ |
| 627 | |
| 628 | For numbers ``x`` and ``y``, possibly of different types, it's a requirement |
| 629 | that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`__hash__` |
| 630 | method documentation for more details). For ease of implementation and |
| 631 | efficiency across a variety of numeric types (including :class:`int`, |
| 632 | :class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) |
| 633 | Python's hash for numeric types is based on a single mathematical function |
| 634 | that's defined for any rational number, and hence applies to all instances of |
| 635 | :class:`int` and :class:`fraction.Fraction`, and all finite instances of |
| 636 | :class:`float` and :class:`decimal.Decimal`. Essentially, this function is |
| 637 | given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is |
| 638 | made available to Python as the :attr:`modulus` attribute of |
| 639 | :data:`sys.hash_info`. |
| 640 | |
| 641 | .. impl-detail:: |
| 642 | |
| 643 | Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C |
| 644 | longs and ``P = 2**61 - 1`` on machines with 64-bit C longs. |
| 645 | |
| 646 | Here are the rules in detail: |
| 647 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 648 | - If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible |
| 649 | by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n, |
| 650 | P)`` gives the inverse of ``n`` modulo ``P``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 651 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 652 | - If ``x = m / n`` is a nonnegative rational number and ``n`` is |
| 653 | divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse |
| 654 | modulo ``P`` and the rule above doesn't apply; in this case define |
| 655 | ``hash(x)`` to be the constant value ``sys.hash_info.inf``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 656 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 657 | - If ``x = m / n`` is a negative rational number define ``hash(x)`` |
| 658 | as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with |
| 659 | ``-2``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 660 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 661 | - The particular values ``sys.hash_info.inf``, ``-sys.hash_info.inf`` |
| 662 | and ``sys.hash_info.nan`` are used as hash values for positive |
| 663 | infinity, negative infinity, or nans (respectively). (All hashable |
| 664 | nans have the same hash value.) |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 665 | |
Georg Brandl | 226ed7e | 2012-03-24 08:12:41 +0100 | [diff] [blame] | 666 | - For a :class:`complex` number ``z``, the hash values of the real |
| 667 | and imaginary parts are combined by computing ``hash(z.real) + |
| 668 | sys.hash_info.imag * hash(z.imag)``, reduced modulo |
| 669 | ``2**sys.hash_info.width`` so that it lies in |
| 670 | ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - |
| 671 | 1))``. Again, if the result is ``-1``, it's replaced with ``-2``. |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 672 | |
| 673 | |
| 674 | To clarify the above rules, here's some example Python code, |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 675 | equivalent to the built-in hash, for computing the hash of a rational |
Mark Dickinson | dc787d2 | 2010-05-23 13:33:13 +0000 | [diff] [blame] | 676 | number, :class:`float`, or :class:`complex`:: |
| 677 | |
| 678 | |
| 679 | import sys, math |
| 680 | |
| 681 | def hash_fraction(m, n): |
| 682 | """Compute the hash of a rational number m / n. |
| 683 | |
| 684 | Assumes m and n are integers, with n positive. |
| 685 | Equivalent to hash(fractions.Fraction(m, n)). |
| 686 | |
| 687 | """ |
| 688 | P = sys.hash_info.modulus |
| 689 | # Remove common factors of P. (Unnecessary if m and n already coprime.) |
| 690 | while m % P == n % P == 0: |
| 691 | m, n = m // P, n // P |
| 692 | |
| 693 | if n % P == 0: |
| 694 | hash_ = sys.hash_info.inf |
| 695 | else: |
| 696 | # Fermat's Little Theorem: pow(n, P-1, P) is 1, so |
| 697 | # pow(n, P-2, P) gives the inverse of n modulo P. |
| 698 | hash_ = (abs(m) % P) * pow(n, P - 2, P) % P |
| 699 | if m < 0: |
| 700 | hash_ = -hash_ |
| 701 | if hash_ == -1: |
| 702 | hash_ = -2 |
| 703 | return hash_ |
| 704 | |
| 705 | def hash_float(x): |
| 706 | """Compute the hash of a float x.""" |
| 707 | |
| 708 | if math.isnan(x): |
| 709 | return sys.hash_info.nan |
| 710 | elif math.isinf(x): |
| 711 | return sys.hash_info.inf if x > 0 else -sys.hash_info.inf |
| 712 | else: |
| 713 | return hash_fraction(*x.as_integer_ratio()) |
| 714 | |
| 715 | def hash_complex(z): |
| 716 | """Compute the hash of a complex number z.""" |
| 717 | |
| 718 | hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) |
| 719 | # do a signed reduction modulo 2**sys.hash_info.width |
| 720 | M = 2**(sys.hash_info.width - 1) |
| 721 | hash_ = (hash_ & (M - 1)) - (hash & M) |
| 722 | if hash_ == -1: |
| 723 | hash_ == -2 |
| 724 | return hash_ |
| 725 | |
Georg Brandl | 6ea420b | 2008-07-16 12:58:29 +0000 | [diff] [blame] | 726 | .. _typeiter: |
| 727 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 728 | Iterator Types |
| 729 | ============== |
| 730 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 731 | .. index:: |
| 732 | single: iterator protocol |
| 733 | single: protocol; iterator |
| 734 | single: sequence; iteration |
| 735 | single: container; iteration over |
| 736 | |
| 737 | Python supports a concept of iteration over containers. This is implemented |
| 738 | using two distinct methods; these are used to allow user-defined classes to |
| 739 | support iteration. Sequences, described below in more detail, always support |
| 740 | the iteration methods. |
| 741 | |
| 742 | One method needs to be defined for container objects to provide iteration |
| 743 | support: |
| 744 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 745 | .. XXX duplicated in reference/datamodel! |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 746 | |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 747 | .. method:: container.__iter__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 748 | |
| 749 | Return an iterator object. The object is required to support the iterator |
| 750 | protocol described below. If a container supports different types of |
| 751 | iteration, additional methods can be provided to specifically request |
| 752 | iterators for those iteration types. (An example of an object supporting |
| 753 | multiple forms of iteration would be a tree structure which supports both |
| 754 | breadth-first and depth-first traversal.) This method corresponds to the |
| 755 | :attr:`tp_iter` slot of the type structure for Python objects in the Python/C |
| 756 | API. |
| 757 | |
| 758 | The iterator objects themselves are required to support the following two |
| 759 | methods, which together form the :dfn:`iterator protocol`: |
| 760 | |
| 761 | |
| 762 | .. method:: iterator.__iter__() |
| 763 | |
| 764 | Return the iterator object itself. This is required to allow both containers |
| 765 | and iterators to be used with the :keyword:`for` and :keyword:`in` statements. |
| 766 | This method corresponds to the :attr:`tp_iter` slot of the type structure for |
| 767 | Python objects in the Python/C API. |
| 768 | |
| 769 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 770 | .. method:: iterator.__next__() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 771 | |
| 772 | Return the next item from the container. If there are no further items, raise |
| 773 | the :exc:`StopIteration` exception. This method corresponds to the |
| 774 | :attr:`tp_iternext` slot of the type structure for Python objects in the |
| 775 | Python/C API. |
| 776 | |
| 777 | Python defines several iterator objects to support iteration over general and |
| 778 | specific sequence types, dictionaries, and other more specialized forms. The |
| 779 | specific types are not important beyond their implementation of the iterator |
| 780 | protocol. |
| 781 | |
Georg Brandl | 905ec32 | 2007-09-28 13:39:25 +0000 | [diff] [blame] | 782 | Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must |
| 783 | continue to do so on subsequent calls. Implementations that do not obey this |
| 784 | property are deemed broken. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 785 | |
Benjamin Peterson | 0289b15 | 2009-06-28 17:22:03 +0000 | [diff] [blame] | 786 | |
| 787 | .. _generator-types: |
| 788 | |
| 789 | Generator Types |
| 790 | --------------- |
| 791 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 792 | Python's :term:`generator`\s provide a convenient way to implement the iterator |
| 793 | protocol. If a container object's :meth:`__iter__` method is implemented as a |
| 794 | generator, it will automatically return an iterator object (technically, a |
| 795 | generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods. |
Benjamin Peterson | 0289b15 | 2009-06-28 17:22:03 +0000 | [diff] [blame] | 796 | More information about generators can be found in :ref:`the documentation for |
| 797 | the yield expression <yieldexpr>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 798 | |
| 799 | |
| 800 | .. _typesseq: |
| 801 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 802 | Sequence Types --- :class:`list`, :class:`tuple`, :class:`range` |
| 803 | ================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 804 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 805 | There are three basic sequence types: lists, tuples, and range objects. |
| 806 | Additional sequence types tailored for processing of |
| 807 | :ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are |
| 808 | described in dedicated sections. |
Georg Brandl | e17d586 | 2009-01-18 10:40:25 +0000 | [diff] [blame] | 809 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 810 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 811 | .. _typesseq-common: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 812 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 813 | Common Sequence Operations |
| 814 | -------------------------- |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 815 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 816 | .. index:: object: sequence |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 817 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 818 | The operations in the following table are supported by most sequence types, |
| 819 | both mutable and immutable. The :class:`collections.abc.Sequence` ABC is |
| 820 | provided to make it easier to correctly implement these operations on |
| 821 | custom sequence types. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 822 | |
| 823 | This table lists the sequence operations sorted in ascending priority |
| 824 | (operations in the same box have the same priority). In the table, *s* and *t* |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 825 | are sequences of the same type, *n*, *i*, *j* and *k* are integers and *x* is |
| 826 | an arbitrary object that meets any type and value restrictions imposed by *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 827 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 828 | The ``in`` and ``not in`` operations have the same priorities as the |
| 829 | comparison operations. The ``+`` (concatenation) and ``*`` (repetition) |
| 830 | operations have the same priority as the corresponding numeric operations. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 831 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 832 | +--------------------------+--------------------------------+----------+ |
| 833 | | Operation | Result | Notes | |
| 834 | +==========================+================================+==========+ |
| 835 | | ``x in s`` | ``True`` if an item of *s* is | \(1) | |
| 836 | | | equal to *x*, else ``False`` | | |
| 837 | +--------------------------+--------------------------------+----------+ |
| 838 | | ``x not in s`` | ``False`` if an item of *s* is | \(1) | |
| 839 | | | equal to *x*, else ``True`` | | |
| 840 | +--------------------------+--------------------------------+----------+ |
| 841 | | ``s + t`` | the concatenation of *s* and | (6)(7) | |
| 842 | | | *t* | | |
| 843 | +--------------------------+--------------------------------+----------+ |
| 844 | | ``s * n, n * s`` | *n* shallow copies of *s* | (2)(7) | |
| 845 | | | concatenated | | |
| 846 | +--------------------------+--------------------------------+----------+ |
| 847 | | ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) | |
| 848 | +--------------------------+--------------------------------+----------+ |
| 849 | | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | |
| 850 | +--------------------------+--------------------------------+----------+ |
| 851 | | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) | |
| 852 | | | with step *k* | | |
| 853 | +--------------------------+--------------------------------+----------+ |
| 854 | | ``len(s)`` | length of *s* | | |
| 855 | +--------------------------+--------------------------------+----------+ |
| 856 | | ``min(s)`` | smallest item of *s* | | |
| 857 | +--------------------------+--------------------------------+----------+ |
| 858 | | ``max(s)`` | largest item of *s* | | |
| 859 | +--------------------------+--------------------------------+----------+ |
| 860 | | ``s.index(x, [i[, j]])`` | index of the first occurence | \(8) | |
| 861 | | | of *x* in *s* (at or after | | |
| 862 | | | index *i* and before index *j*)| | |
| 863 | +--------------------------+--------------------------------+----------+ |
| 864 | | ``s.count(x)`` | total number of occurences of | | |
| 865 | | | *x* in *s* | | |
| 866 | +--------------------------+--------------------------------+----------+ |
| 867 | |
| 868 | Sequences of the same type also support comparisons. In particular, tuples |
| 869 | and lists are compared lexicographically by comparing corresponding elements. |
| 870 | This means that to compare equal, every element must compare equal and the |
| 871 | two sequences must be of the same type and have the same length. (For full |
| 872 | details see :ref:`comparisons` in the language reference.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 873 | |
| 874 | .. index:: |
| 875 | triple: operations on; sequence; types |
| 876 | builtin: len |
| 877 | builtin: min |
| 878 | builtin: max |
| 879 | pair: concatenation; operation |
| 880 | pair: repetition; operation |
| 881 | pair: subscript; operation |
| 882 | pair: slice; operation |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 883 | operator: in |
| 884 | operator: not in |
| 885 | |
| 886 | Notes: |
| 887 | |
| 888 | (1) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 889 | While the ``in`` and ``not in`` operations are used only for simple |
| 890 | containment testing in the general case, some specialised sequences |
| 891 | (such as :class:`str`, :class:`bytes` and :class:`bytearray`) also use |
| 892 | them for subsequence testing:: |
| 893 | |
| 894 | >>> "gg" in "eggs" |
| 895 | True |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 896 | |
| 897 | (2) |
| 898 | Values of *n* less than ``0`` are treated as ``0`` (which yields an empty |
| 899 | sequence of the same type as *s*). Note also that the copies are shallow; |
| 900 | nested structures are not copied. This often haunts new Python programmers; |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 901 | consider:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 902 | |
| 903 | >>> lists = [[]] * 3 |
| 904 | >>> lists |
| 905 | [[], [], []] |
| 906 | >>> lists[0].append(3) |
| 907 | >>> lists |
| 908 | [[3], [3], [3]] |
| 909 | |
| 910 | What has happened is that ``[[]]`` is a one-element list containing an empty |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 911 | list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty |
| 912 | list. Modifying any of the elements of ``lists`` modifies this single list. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 913 | You can create a list of different lists this way:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 914 | |
| 915 | >>> lists = [[] for i in range(3)] |
| 916 | >>> lists[0].append(3) |
| 917 | >>> lists[1].append(5) |
| 918 | >>> lists[2].append(7) |
| 919 | >>> lists |
| 920 | [[3], [5], [7]] |
| 921 | |
| 922 | (3) |
| 923 | If *i* or *j* is negative, the index is relative to the end of the string: |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 924 | ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is |
| 925 | still ``0``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 926 | |
| 927 | (4) |
| 928 | The slice of *s* from *i* to *j* is defined as the sequence of items with index |
| 929 | *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use |
| 930 | ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or |
| 931 | ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is |
| 932 | empty. |
| 933 | |
| 934 | (5) |
| 935 | The slice of *s* from *i* to *j* with step *k* is defined as the sequence of |
Christian Heimes | 2c18161 | 2007-12-17 20:04:13 +0000 | [diff] [blame] | 936 | items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 937 | the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when |
| 938 | *j* is reached (but never including *j*). If *i* or *j* is greater than |
| 939 | ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become |
| 940 | "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. |
| 941 | If *k* is ``None``, it is treated like ``1``. |
| 942 | |
| 943 | (6) |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 944 | Concatenating immutable sequences always results in a new object. This |
| 945 | means that building up a sequence by repeated concatenation will have a |
| 946 | quadratic runtime cost in the total sequence length. To get a linear |
| 947 | runtime cost, you must switch to one of the alternatives below: |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 948 | |
Antoine Pitrou | fd9ebd4 | 2011-11-25 16:33:53 +0100 | [diff] [blame] | 949 | * if concatenating :class:`str` objects, you can build a list and use |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 950 | :meth:`str.join` at the end or else write to a :class:`io.StringIO` |
| 951 | instance and retrieve its value when complete; |
Antoine Pitrou | fd9ebd4 | 2011-11-25 16:33:53 +0100 | [diff] [blame] | 952 | |
| 953 | * if concatenating :class:`bytes` objects, you can similarly use |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 954 | :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place |
| 955 | concatenation with a :class:`bytearray` object. :class:`bytearray` |
| 956 | objects are mutable and have an efficient overallocation mechanism. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 957 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 958 | * if concatenating :class:`tuple` objects, extend a :class:`list` instead. |
| 959 | |
| 960 | * for other types, investigate the relevant class documentation |
| 961 | |
| 962 | |
| 963 | (7) |
| 964 | Some sequence types (such as :class:`range`) only support item sequences |
| 965 | that follow specific patterns, and hence don't support sequence |
| 966 | concatenation or repetition. |
| 967 | |
| 968 | (8) |
| 969 | ``index`` raises :exc:`ValueError` when *x* is not found in *s*. |
| 970 | When supported, the additional arguments to the index method allow |
| 971 | efficient searching of subsections of the sequence. Passing the extra |
| 972 | arguments is roughly equivalent to using ``s[i:j].index(x)``, only |
| 973 | without copying any data and with the returned index being relative to |
| 974 | the start of the sequence rather than the start of the slice. |
| 975 | |
| 976 | |
| 977 | .. _typesseq-immutable: |
| 978 | |
| 979 | Immutable Sequence Types |
| 980 | ------------------------ |
| 981 | |
| 982 | .. index:: |
| 983 | triple: immutable; sequence; types |
| 984 | object: tuple |
| 985 | |
| 986 | The only operation that immutable sequence types generally implement that is |
| 987 | not also implemented by mutable sequence types is support for the :func:`hash` |
| 988 | built-in. |
| 989 | |
| 990 | This support allows immutable sequences, such as :class:`tuple` instances, to |
| 991 | be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset` |
| 992 | instances. |
| 993 | |
| 994 | Attempting to hash an immutable sequence that contains unhashable values will |
| 995 | result in :exc:`TypeError`. |
| 996 | |
| 997 | |
| 998 | .. _typesseq-mutable: |
| 999 | |
| 1000 | Mutable Sequence Types |
| 1001 | ---------------------- |
| 1002 | |
| 1003 | .. index:: |
| 1004 | triple: mutable; sequence; types |
| 1005 | object: list |
| 1006 | object: bytearray |
| 1007 | |
| 1008 | The operations in the following table are defined on mutable sequence types. |
| 1009 | The :class:`collections.abc.MutableSequence` ABC is provided to make it |
| 1010 | easier to correctly implement these operations on custom sequence types. |
| 1011 | |
| 1012 | In the table *s* is an instance of a mutable sequence type, *t* is any |
| 1013 | iterable object and *x* is an arbitrary object that meets any type |
| 1014 | and value restrictions imposed by *s* (for example, :class:`bytearray` only |
| 1015 | accepts integers that meet the value restriction ``0 <= x <= 255``). |
| 1016 | |
| 1017 | |
| 1018 | .. index:: |
| 1019 | triple: operations on; sequence; types |
| 1020 | triple: operations on; list; type |
| 1021 | pair: subscript; assignment |
| 1022 | pair: slice; assignment |
| 1023 | statement: del |
| 1024 | single: append() (sequence method) |
| 1025 | single: extend() (sequence method) |
| 1026 | single: count() (sequence method) |
| 1027 | single: index() (sequence method) |
| 1028 | single: insert() (sequence method) |
| 1029 | single: pop() (sequence method) |
| 1030 | single: remove() (sequence method) |
| 1031 | single: reverse() (sequence method) |
| 1032 | |
| 1033 | +------------------------------+--------------------------------+---------------------+ |
| 1034 | | Operation | Result | Notes | |
| 1035 | +==============================+================================+=====================+ |
| 1036 | | ``s[i] = x`` | item *i* of *s* is replaced by | | |
| 1037 | | | *x* | | |
| 1038 | +------------------------------+--------------------------------+---------------------+ |
| 1039 | | ``s[i:j] = t`` | slice of *s* from *i* to *j* | | |
| 1040 | | | is replaced by the contents of | | |
| 1041 | | | the iterable *t* | | |
| 1042 | +------------------------------+--------------------------------+---------------------+ |
| 1043 | | ``del s[i:j]`` | same as ``s[i:j] = []`` | | |
| 1044 | +------------------------------+--------------------------------+---------------------+ |
| 1045 | | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | |
| 1046 | | | are replaced by those of *t* | | |
| 1047 | +------------------------------+--------------------------------+---------------------+ |
| 1048 | | ``del s[i:j:k]`` | removes the elements of | | |
| 1049 | | | ``s[i:j:k]`` from the list | | |
| 1050 | +------------------------------+--------------------------------+---------------------+ |
| 1051 | | ``s.append(x)`` | same as ``s[len(s):len(s)] = | | |
| 1052 | | | [x]`` | | |
| 1053 | +------------------------------+--------------------------------+---------------------+ |
| 1054 | | ``s.clear()`` | remove all items from ``s`` | \(5) | |
| 1055 | | | (same as ``del s[:]``) | | |
| 1056 | +------------------------------+--------------------------------+---------------------+ |
| 1057 | | ``s.copy()`` | return a shallow copy of ``s`` | \(5) | |
| 1058 | | | (same as ``s[:]``) | | |
| 1059 | +------------------------------+--------------------------------+---------------------+ |
| 1060 | | ``s.extend(t)`` | same as ``s[len(s):len(s)] = | | |
| 1061 | | | t`` | | |
| 1062 | +------------------------------+--------------------------------+---------------------+ |
| 1063 | | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | | |
| 1064 | +------------------------------+--------------------------------+---------------------+ |
| 1065 | | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(2) | |
| 1066 | | | return x`` | | |
| 1067 | +------------------------------+--------------------------------+---------------------+ |
| 1068 | | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) | |
| 1069 | +------------------------------+--------------------------------+---------------------+ |
| 1070 | | ``s.reverse()`` | reverses the items of *s* in | \(4) | |
| 1071 | | | place | | |
| 1072 | +------------------------------+--------------------------------+---------------------+ |
| 1073 | |
| 1074 | |
| 1075 | Notes: |
| 1076 | |
| 1077 | (1) |
| 1078 | *t* must have the same length as the slice it is replacing. |
| 1079 | |
| 1080 | (2) |
| 1081 | The optional argument *i* defaults to ``-1``, so that by default the last |
| 1082 | item is removed and returned. |
| 1083 | |
| 1084 | (3) |
| 1085 | ``remove`` raises :exc:`ValueError` when *x* is not found in *s*. |
| 1086 | |
| 1087 | (4) |
| 1088 | The :meth:`reverse` method modifies the sequence in place for economy of |
| 1089 | space when reversing a large sequence. To remind users that it operates by |
| 1090 | side effect, it does not return the reversed sequence. |
| 1091 | |
| 1092 | (5) |
| 1093 | :meth:`clear` and :meth:`!copy` are included for consistency with the |
| 1094 | interfaces of mutable containers that don't support slicing operations |
| 1095 | (such as :class:`dict` and :class:`set`) |
| 1096 | |
| 1097 | .. versionadded:: 3.3 |
| 1098 | :meth:`clear` and :meth:`!copy` methods. |
| 1099 | |
| 1100 | |
| 1101 | .. _typesseq-list: |
| 1102 | |
| 1103 | Lists |
| 1104 | ----- |
| 1105 | |
| 1106 | .. index:: object: list |
| 1107 | |
| 1108 | Lists are mutable sequences, typically used to store collections of |
| 1109 | homogeneous items (where the precise degree of similarity will vary by |
| 1110 | application). |
| 1111 | |
| 1112 | Lists may be constructed in several ways: |
| 1113 | |
| 1114 | * Using a pair of square brackets to denote the empty list: ``[]`` |
| 1115 | * Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]`` |
| 1116 | * Using a list comprehension: ``[x for x in iterable]`` |
| 1117 | * Using the :func:`list` built-in: ``list()`` or ``list(iterable)`` |
| 1118 | |
| 1119 | Many other operations also produce lists, including the :func:`sorted` built-in. |
| 1120 | |
| 1121 | Lists implement all of the :ref:`common <typesseq-common>` and |
| 1122 | :ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the |
| 1123 | following additional method: |
| 1124 | |
| 1125 | .. method:: list.sort(*, key=None, reverse=None) |
| 1126 | |
| 1127 | This method sorts the list in place, using only ``<`` comparisons |
| 1128 | between items. Exceptions are not suppressed - if any comparison operations |
| 1129 | fail, the entire sort operation will fail (and the list will likely be left |
| 1130 | in a partially modified state). |
| 1131 | |
| 1132 | *key* specifies a function of one argument that is used to extract a |
| 1133 | comparison key from each list element (for example, ``key=str.lower``). |
| 1134 | The key corresponding to each item in the list is calculated once and |
| 1135 | then used for the entire sorting process. The default value of ``None`` |
| 1136 | means that list items are sorted directly without calculating a separate |
| 1137 | key value. |
| 1138 | |
| 1139 | The :func:`functools.cmp_to_key` utility is available to convert a 2.x |
| 1140 | style *cmp* function to a *key* function. |
| 1141 | |
| 1142 | *reverse* is a boolean value. If set to ``True``, then the list elements |
| 1143 | are sorted as if each comparison were reversed. |
| 1144 | |
| 1145 | This method modifies the sequence in place for economy of space when |
| 1146 | sorting a large sequence. To remind users that it operates by side |
| 1147 | effect, it does not return the sorted sequence (use :func:`sorted` to |
| 1148 | explicitly request a new sorted list instance). |
| 1149 | |
| 1150 | The :meth:`sort` method is guaranteed to be stable. A sort is stable if it |
| 1151 | guarantees not to change the relative order of elements that compare equal |
| 1152 | --- this is helpful for sorting in multiple passes (for example, sort by |
| 1153 | department, then by salary grade). |
| 1154 | |
| 1155 | .. impl-detail:: |
| 1156 | |
| 1157 | While a list is being sorted, the effect of attempting to mutate, or even |
| 1158 | inspect, the list is undefined. The C implementation of Python makes the |
| 1159 | list appear empty for the duration, and raises :exc:`ValueError` if it can |
| 1160 | detect that the list has been mutated during a sort. |
| 1161 | |
| 1162 | |
| 1163 | .. _typesseq-tuple: |
| 1164 | |
| 1165 | Tuples |
| 1166 | ------ |
| 1167 | |
| 1168 | .. index:: object: tuple |
| 1169 | |
| 1170 | Tuples are immutable sequences, typically used to store collections of |
| 1171 | heterogeneous data (such as the 2-tuples produced by the :func:`enumerate` |
| 1172 | built-in). Tuples are also used for cases where an immutable sequence of |
| 1173 | homogeneous data is needed (such as allowing storage in a :class:`set` or |
| 1174 | :class:`dict` instance). |
| 1175 | |
| 1176 | Tuples may be constructed in a number of ways: |
| 1177 | |
| 1178 | * Using a pair of parentheses to denote the empty tuple: ``()`` |
| 1179 | * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)`` |
| 1180 | * Separating items with commas: ``a, b, c`` or ``(a, b, c)`` |
| 1181 | * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)`` |
| 1182 | |
| 1183 | Note that the parentheses are optional (except in the empty tuple case, or |
| 1184 | when needed to avoid syntactic ambiguity). It is actually the comma which |
| 1185 | makes a tuple, not the parentheses. |
| 1186 | |
| 1187 | Tuples implement all of the :ref:`common <typesseq-common>` sequence |
| 1188 | operations. |
| 1189 | |
| 1190 | For heterogeneous collections of data, :func:`collections.namedtuple` may |
| 1191 | be more appropriate than a simple tuple object. |
| 1192 | |
| 1193 | |
| 1194 | .. _typesseq-range: |
| 1195 | |
| 1196 | Ranges |
| 1197 | ------ |
| 1198 | |
| 1199 | .. index:: object: range |
| 1200 | |
| 1201 | The :class:`range` type represents an immutable sequence of numbers and is |
| 1202 | commonly used for looping a specific number of times. Instances are created |
| 1203 | using the :func:`range` built-in. |
| 1204 | |
| 1205 | For positive indices with results between the defined ``start`` and ``stop`` |
| 1206 | values, integers within the range are determined by the formula: |
| 1207 | ``r[i] = start + step*i`` |
| 1208 | |
| 1209 | For negative indices and slicing operations, a range instance determines the |
| 1210 | appropriate result for the corresponding tuple and returns either the |
| 1211 | appropriate integer (for negative indices) or an appropriate range object |
| 1212 | (for slicing operations) . |
| 1213 | |
| 1214 | The advantage of the :class:`range` type over a regular :class:`list` or |
| 1215 | :class:`tuple` is that a :class:`range` object will always take the same |
| 1216 | (small) amount of memory, no matter the size of the range it represents (as it |
| 1217 | only stores the ``start``, ``stop`` and ``step`` values, calculating individual |
| 1218 | items and subranges as needed). |
| 1219 | |
| 1220 | Ranges implement all of the :ref:`common <typesseq-common>` sequence operations |
| 1221 | except concatenation and repetition (due to the fact that range objects can |
| 1222 | only represent sequences that follow a strict pattern and repetition and |
| 1223 | concatenation will usually violate that pattern). |
| 1224 | |
| 1225 | |
| 1226 | .. _textseq: |
| 1227 | |
| 1228 | Text Sequence Type --- :class:`str` |
| 1229 | =================================== |
| 1230 | |
| 1231 | .. index:: |
| 1232 | object: string |
| 1233 | object: bytes |
| 1234 | object: bytearray |
| 1235 | object: io.StringIO |
| 1236 | |
| 1237 | |
| 1238 | Textual data in Python is handled with :class:`str` objects, which are |
| 1239 | immutable sequences of Unicode code points. String literals are |
| 1240 | written in a variety of ways: |
| 1241 | |
| 1242 | * Single quotes: ``'allows embedded "double" quotes'`` |
| 1243 | * Double quotes: ``"allows embedded 'single' quotes"``. |
| 1244 | * Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""`` |
| 1245 | |
| 1246 | Triple quoted strings may span multiple lines - all associated whitespace will |
| 1247 | be included in the string literal. |
| 1248 | |
| 1249 | String literals that are part of a single expression and have only whitespace |
| 1250 | between them will be implicitly converted to a single string literal. |
| 1251 | |
| 1252 | See :ref:`strings` for more about the various forms of string literal, |
| 1253 | including supported escape sequences, and the ``r`` ("raw") prefix that |
| 1254 | disables most escape sequence processing. |
| 1255 | |
| 1256 | Strings may also be created from other objects with the :func:`str` built-in. |
| 1257 | |
| 1258 | Since there is no separate "character" type, indexing a string produces |
| 1259 | strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``. |
| 1260 | |
| 1261 | There is also no mutable string type, but :meth:`str.join` or |
| 1262 | :class:`io.StringIO` can be used to efficiently construct strings from |
| 1263 | multiple fragments. |
| 1264 | |
| 1265 | .. versionchanged:: 3.3 |
| 1266 | For backwards compatibility with the Python 2 series, the ``u`` prefix is |
| 1267 | once again permitted on string literals. It has no effect on the meaning |
| 1268 | of string literals and cannot be combined with the ``r`` prefix. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1269 | |
| 1270 | .. _string-methods: |
| 1271 | |
| 1272 | String Methods |
| 1273 | -------------- |
| 1274 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1275 | .. index:: |
| 1276 | pair: string; methods |
| 1277 | module: re |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1278 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1279 | Strings implement all of the :ref:`common <typesseq-common>` sequence |
| 1280 | operations, along with the additional methods described below. |
Thomas Wouters | 8ce81f7 | 2007-09-20 18:22:40 +0000 | [diff] [blame] | 1281 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1282 | Strings also support two styles of string formatting, one providing a large |
| 1283 | degree of flexibility and customization (see :meth:`str.format`, |
| 1284 | :ref:`formatstrings` and :ref:`string-formatting`) and the other based on C |
| 1285 | ``printf`` style formatting that handles a narrower range of types and is |
| 1286 | slightly harder to use correctly, but is often faster for the cases it can |
| 1287 | handle (:ref:`old-string-formatting`). |
| 1288 | |
| 1289 | The :ref:`textservices` section of the standard library covers a number of |
| 1290 | other modules that provide various text related utilities (including regular |
| 1291 | expression support in the :mod:`re` module). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1292 | |
| 1293 | .. method:: str.capitalize() |
| 1294 | |
Senthil Kumaran | fa89798 | 2010-07-05 11:41:42 +0000 | [diff] [blame] | 1295 | Return a copy of the string with its first character capitalized and the |
Senthil Kumaran | 37c63a3 | 2010-07-06 02:08:36 +0000 | [diff] [blame] | 1296 | rest lowercased. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1297 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1298 | |
Benjamin Peterson | d5890c8 | 2012-01-14 13:23:30 -0500 | [diff] [blame] | 1299 | .. method:: str.casefold() |
| 1300 | |
| 1301 | Return a casefolded copy of the string. Casefolded strings may be used for |
Benjamin Peterson | 9430354 | 2012-01-18 23:09:32 -0500 | [diff] [blame] | 1302 | caseless matching. |
| 1303 | |
| 1304 | Casefolding is similar to lowercasing but more aggressive because it is |
| 1305 | intended to remove all case distinctions in a string. For example, the German |
| 1306 | lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already |
| 1307 | lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold` |
| 1308 | converts it to ``"ss"``. |
| 1309 | |
| 1310 | The casefolding algorithm is described in section 3.13 of the Unicode |
| 1311 | Standard. |
Benjamin Peterson | d5890c8 | 2012-01-14 13:23:30 -0500 | [diff] [blame] | 1312 | |
| 1313 | .. versionadded:: 3.3 |
| 1314 | |
| 1315 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1316 | .. method:: str.center(width[, fillchar]) |
| 1317 | |
| 1318 | Return centered in a string of length *width*. Padding is done using the |
| 1319 | specified *fillchar* (default is a space). |
| 1320 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1321 | |
| 1322 | .. method:: str.count(sub[, start[, end]]) |
| 1323 | |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 1324 | Return the number of non-overlapping occurrences of substring *sub* in the |
| 1325 | range [*start*, *end*]. Optional arguments *start* and *end* are |
| 1326 | interpreted as in slice notation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1327 | |
| 1328 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 1329 | .. method:: str.encode(encoding="utf-8", errors="strict") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1330 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 1331 | Return an encoded version of the string as a bytes object. Default encoding |
| 1332 | is ``'utf-8'``. *errors* may be given to set a different error handling scheme. |
| 1333 | The default for *errors* is ``'strict'``, meaning that encoding errors raise |
| 1334 | a :exc:`UnicodeError`. Other possible |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 1335 | values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, |
| 1336 | ``'backslashreplace'`` and any other name registered via |
| 1337 | :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a |
| 1338 | list of possible encodings, see section :ref:`standard-encodings`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1339 | |
Benjamin Peterson | 308d637 | 2009-09-18 21:42:35 +0000 | [diff] [blame] | 1340 | .. versionchanged:: 3.1 |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 1341 | Support for keyword arguments added. |
| 1342 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1343 | |
| 1344 | .. method:: str.endswith(suffix[, start[, end]]) |
| 1345 | |
| 1346 | Return ``True`` if the string ends with the specified *suffix*, otherwise return |
| 1347 | ``False``. *suffix* can also be a tuple of suffixes to look for. With optional |
| 1348 | *start*, test beginning at that position. With optional *end*, stop comparing |
| 1349 | at that position. |
| 1350 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1351 | |
| 1352 | .. method:: str.expandtabs([tabsize]) |
| 1353 | |
Eli Bendersky | c2c8960 | 2011-11-11 10:40:14 +0200 | [diff] [blame] | 1354 | Return a copy of the string where all tab characters are replaced by zero or |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1355 | more spaces, depending on the current column and the given tab size. The |
| 1356 | column number is reset to zero after each newline occurring in the string. |
| 1357 | If *tabsize* is not given, a tab size of ``8`` characters is assumed. This |
| 1358 | doesn't understand other non-printing characters or escape sequences. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1359 | |
| 1360 | |
| 1361 | .. method:: str.find(sub[, start[, end]]) |
| 1362 | |
Benjamin Peterson | d99cd81 | 2010-04-27 22:58:50 +0000 | [diff] [blame] | 1363 | Return the lowest index in the string where substring *sub* is found, such |
| 1364 | that *sub* is contained in the slice ``s[start:end]``. Optional arguments |
| 1365 | *start* and *end* are interpreted as in slice notation. Return ``-1`` if |
| 1366 | *sub* is not found. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1367 | |
Ezio Melotti | 0ed8c68 | 2011-05-09 03:54:30 +0300 | [diff] [blame] | 1368 | .. note:: |
| 1369 | |
| 1370 | The :meth:`~str.find` method should be used only if you need to know the |
| 1371 | position of *sub*. To check if *sub* is a substring or not, use the |
| 1372 | :keyword:`in` operator:: |
| 1373 | |
| 1374 | >>> 'Py' in 'Python' |
| 1375 | True |
| 1376 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1377 | |
Benjamin Peterson | ad3d5c2 | 2009-02-26 03:38:59 +0000 | [diff] [blame] | 1378 | .. method:: str.format(*args, **kwargs) |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1379 | |
Georg Brandl | 1f70cdf | 2010-03-21 09:04:24 +0000 | [diff] [blame] | 1380 | Perform a string formatting operation. The string on which this method is |
| 1381 | called can contain literal text or replacement fields delimited by braces |
| 1382 | ``{}``. Each replacement field contains either the numeric index of a |
| 1383 | positional argument, or the name of a keyword argument. Returns a copy of |
| 1384 | the string where each replacement field is replaced with the string value of |
| 1385 | the corresponding argument. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1386 | |
| 1387 | >>> "The sum of 1 + 2 is {0}".format(1+2) |
| 1388 | 'The sum of 1 + 2 is 3' |
| 1389 | |
| 1390 | See :ref:`formatstrings` for a description of the various formatting options |
| 1391 | that can be specified in format strings. |
| 1392 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1393 | |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1394 | .. method:: str.format_map(mapping) |
| 1395 | |
Éric Araujo | 2642ad0 | 2010-11-06 04:59:27 +0000 | [diff] [blame] | 1396 | Similar to ``str.format(**mapping)``, except that ``mapping`` is |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1397 | used directly and not copied to a :class:`dict` . This is useful |
Eric Smith | 5ad85f8 | 2010-11-06 13:22:13 +0000 | [diff] [blame] | 1398 | if for example ``mapping`` is a dict subclass: |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1399 | |
Eric Smith | 5ad85f8 | 2010-11-06 13:22:13 +0000 | [diff] [blame] | 1400 | >>> class Default(dict): |
| 1401 | ... def __missing__(self, key): |
| 1402 | ... return key |
| 1403 | ... |
| 1404 | >>> '{name} was born in {country}'.format_map(Default(name='Guido')) |
| 1405 | 'Guido was born in country' |
| 1406 | |
| 1407 | .. versionadded:: 3.2 |
| 1408 | |
Eric Smith | 27bbca6 | 2010-11-04 17:06:58 +0000 | [diff] [blame] | 1409 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1410 | .. method:: str.index(sub[, start[, end]]) |
| 1411 | |
| 1412 | Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found. |
| 1413 | |
| 1414 | |
| 1415 | .. method:: str.isalnum() |
| 1416 | |
| 1417 | Return true if all characters in the string are alphanumeric and there is at |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1418 | least one character, false otherwise. A character ``c`` is alphanumeric if one |
| 1419 | of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, |
| 1420 | ``c.isdigit()``, or ``c.isnumeric()``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1421 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1422 | |
| 1423 | .. method:: str.isalpha() |
| 1424 | |
| 1425 | Return true if all characters in the string are alphabetic and there is at least |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1426 | one character, false otherwise. Alphabetic characters are those characters defined |
| 1427 | in the Unicode character database as "Letter", i.e., those with general category |
| 1428 | property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different |
| 1429 | from the "Alphabetic" property defined in the Unicode Standard. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1430 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1431 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1432 | .. method:: str.isdecimal() |
| 1433 | |
| 1434 | Return true if all characters in the string are decimal |
| 1435 | characters and there is at least one character, false |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1436 | otherwise. Decimal characters are those from general category "Nd". This category |
| 1437 | includes digit characters, and all characters |
Ezio Melotti | e130a52 | 2011-10-19 10:58:56 +0300 | [diff] [blame] | 1438 | that can be used to form decimal-radix numbers, e.g. U+0660, |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1439 | ARABIC-INDIC DIGIT ZERO. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1440 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1441 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1442 | .. method:: str.isdigit() |
| 1443 | |
| 1444 | Return true if all characters in the string are digits and there is at least one |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1445 | character, false otherwise. Digits include decimal characters and digits that need |
| 1446 | special handling, such as the compatibility superscript digits. Formally, a digit |
| 1447 | is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1448 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1449 | |
| 1450 | .. method:: str.isidentifier() |
| 1451 | |
| 1452 | Return true if the string is a valid identifier according to the language |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1453 | definition, section :ref:`identifiers`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1454 | |
| 1455 | |
| 1456 | .. method:: str.islower() |
| 1457 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1458 | Return true if all cased characters [4]_ in the string are lowercase and |
| 1459 | there is at least one cased character, false otherwise. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1460 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1461 | |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1462 | .. method:: str.isnumeric() |
| 1463 | |
| 1464 | Return true if all characters in the string are numeric |
| 1465 | characters, and there is at least one character, false |
| 1466 | otherwise. Numeric characters include digit characters, and all characters |
| 1467 | that have the Unicode numeric value property, e.g. U+2155, |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1468 | VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property |
| 1469 | value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. |
Mark Summerfield | bbfd71d | 2008-07-01 15:50:04 +0000 | [diff] [blame] | 1470 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1471 | |
Georg Brandl | 559e5d7 | 2008-06-11 18:37:52 +0000 | [diff] [blame] | 1472 | .. method:: str.isprintable() |
| 1473 | |
| 1474 | Return true if all characters in the string are printable or the string is |
| 1475 | empty, false otherwise. Nonprintable characters are those characters defined |
| 1476 | in the Unicode character database as "Other" or "Separator", excepting the |
| 1477 | ASCII space (0x20) which is considered printable. (Note that printable |
| 1478 | characters in this context are those which should not be escaped when |
| 1479 | :func:`repr` is invoked on a string. It has no bearing on the handling of |
| 1480 | strings written to :data:`sys.stdout` or :data:`sys.stderr`.) |
| 1481 | |
| 1482 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1483 | .. method:: str.isspace() |
| 1484 | |
| 1485 | Return true if there are only whitespace characters in the string and there is |
Alexander Belopolsky | 0d26798 | 2010-12-23 02:58:25 +0000 | [diff] [blame] | 1486 | at least one character, false otherwise. Whitespace characters are those |
| 1487 | characters defined in the Unicode character database as "Other" or "Separator" |
| 1488 | and those with bidirectional property being one of "WS", "B", or "S". |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1489 | |
| 1490 | .. method:: str.istitle() |
| 1491 | |
| 1492 | Return true if the string is a titlecased string and there is at least one |
| 1493 | character, for example uppercase characters may only follow uncased characters |
| 1494 | and lowercase characters only cased ones. Return false otherwise. |
| 1495 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1496 | |
| 1497 | .. method:: str.isupper() |
| 1498 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1499 | Return true if all cased characters [4]_ in the string are uppercase and |
| 1500 | there is at least one cased character, false otherwise. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1501 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1502 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1503 | .. method:: str.join(iterable) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1504 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1505 | Return a string which is the concatenation of the strings in the |
| 1506 | :term:`iterable` *iterable*. A :exc:`TypeError` will be raised if there are |
Terry Jan Reedy | f4ec3c5 | 2012-01-11 03:29:42 -0500 | [diff] [blame] | 1507 | any non-string values in *iterable*, including :class:`bytes` objects. The |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 1508 | separator between elements is the string providing this method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1509 | |
| 1510 | |
| 1511 | .. method:: str.ljust(width[, fillchar]) |
| 1512 | |
| 1513 | Return the string left justified in a string of length *width*. Padding is done |
| 1514 | using the specified *fillchar* (default is a space). The original string is |
Terry Jan Reedy | f4ec3c5 | 2012-01-11 03:29:42 -0500 | [diff] [blame] | 1515 | returned if *width* is less than or equal to ``len(s)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1516 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1517 | |
| 1518 | .. method:: str.lower() |
| 1519 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1520 | Return a copy of the string with all the cased characters [4]_ converted to |
| 1521 | lowercase. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1522 | |
Benjamin Peterson | 9430354 | 2012-01-18 23:09:32 -0500 | [diff] [blame] | 1523 | The lowercasing algorithm used is described in section 3.13 of the Unicode |
| 1524 | Standard. |
| 1525 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1526 | |
| 1527 | .. method:: str.lstrip([chars]) |
| 1528 | |
| 1529 | Return a copy of the string with leading characters removed. The *chars* |
| 1530 | argument is a string specifying the set of characters to be removed. If omitted |
| 1531 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1532 | argument is not a prefix; rather, all combinations of its values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1533 | |
| 1534 | >>> ' spacious '.lstrip() |
| 1535 | 'spacious ' |
| 1536 | >>> 'www.example.com'.lstrip('cmowz.') |
| 1537 | 'example.com' |
| 1538 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1539 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 1540 | .. staticmethod:: str.maketrans(x[, y[, z]]) |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1541 | |
| 1542 | This static method returns a translation table usable for :meth:`str.translate`. |
| 1543 | |
| 1544 | If there is only one argument, it must be a dictionary mapping Unicode |
| 1545 | ordinals (integers) or characters (strings of length 1) to Unicode ordinals, |
| 1546 | strings (of arbitrary lengths) or None. Character keys will then be |
| 1547 | converted to ordinals. |
| 1548 | |
| 1549 | If there are two arguments, they must be strings of equal length, and in the |
| 1550 | resulting dictionary, each character in x will be mapped to the character at |
| 1551 | the same position in y. If there is a third argument, it must be a string, |
| 1552 | whose characters will be mapped to None in the result. |
| 1553 | |
| 1554 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1555 | .. method:: str.partition(sep) |
| 1556 | |
| 1557 | Split the string at the first occurrence of *sep*, and return a 3-tuple |
| 1558 | containing the part before the separator, the separator itself, and the part |
| 1559 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1560 | the string itself, followed by two empty strings. |
| 1561 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1562 | |
| 1563 | .. method:: str.replace(old, new[, count]) |
| 1564 | |
| 1565 | Return a copy of the string with all occurrences of substring *old* replaced by |
| 1566 | *new*. If the optional argument *count* is given, only the first *count* |
| 1567 | occurrences are replaced. |
| 1568 | |
| 1569 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1570 | .. method:: str.rfind(sub[, start[, end]]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1571 | |
Benjamin Peterson | d99cd81 | 2010-04-27 22:58:50 +0000 | [diff] [blame] | 1572 | Return the highest index in the string where substring *sub* is found, such |
| 1573 | that *sub* is contained within ``s[start:end]``. Optional arguments *start* |
| 1574 | and *end* are interpreted as in slice notation. Return ``-1`` on failure. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1575 | |
| 1576 | |
| 1577 | .. method:: str.rindex(sub[, start[, end]]) |
| 1578 | |
| 1579 | Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not |
| 1580 | found. |
| 1581 | |
| 1582 | |
| 1583 | .. method:: str.rjust(width[, fillchar]) |
| 1584 | |
| 1585 | Return the string right justified in a string of length *width*. Padding is done |
| 1586 | using the specified *fillchar* (default is a space). The original string is |
Terry Jan Reedy | f4ec3c5 | 2012-01-11 03:29:42 -0500 | [diff] [blame] | 1587 | returned if *width* is less than or equal to ``len(s)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1588 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1589 | |
| 1590 | .. method:: str.rpartition(sep) |
| 1591 | |
| 1592 | Split the string at the last occurrence of *sep*, and return a 3-tuple |
| 1593 | containing the part before the separator, the separator itself, and the part |
| 1594 | after the separator. If the separator is not found, return a 3-tuple containing |
| 1595 | two empty strings, followed by the string itself. |
| 1596 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1597 | |
Ezio Melotti | cda6b6d | 2012-02-26 09:39:55 +0200 | [diff] [blame] | 1598 | .. method:: str.rsplit(sep=None, maxsplit=-1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1599 | |
| 1600 | Return a list of the words in the string, using *sep* as the delimiter string. |
| 1601 | If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* |
| 1602 | ones. If *sep* is not specified or ``None``, any whitespace string is a |
| 1603 | separator. Except for splitting from the right, :meth:`rsplit` behaves like |
| 1604 | :meth:`split` which is described in detail below. |
| 1605 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1606 | |
| 1607 | .. method:: str.rstrip([chars]) |
| 1608 | |
| 1609 | Return a copy of the string with trailing characters removed. The *chars* |
| 1610 | argument is a string specifying the set of characters to be removed. If omitted |
| 1611 | or ``None``, the *chars* argument defaults to removing whitespace. The *chars* |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1612 | argument is not a suffix; rather, all combinations of its values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1613 | |
| 1614 | >>> ' spacious '.rstrip() |
| 1615 | ' spacious' |
| 1616 | >>> 'mississippi'.rstrip('ipz') |
| 1617 | 'mississ' |
| 1618 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1619 | |
Ezio Melotti | cda6b6d | 2012-02-26 09:39:55 +0200 | [diff] [blame] | 1620 | .. method:: str.split(sep=None, maxsplit=-1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1621 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1622 | Return a list of the words in the string, using *sep* as the delimiter |
| 1623 | string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, |
| 1624 | the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not |
Ezio Melotti | bf3165b | 2012-05-10 15:30:42 +0300 | [diff] [blame] | 1625 | specified or ``-1``, then there is no limit on the number of splits |
| 1626 | (all possible splits are made). |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1627 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 1628 | If *sep* is given, consecutive delimiters are not grouped together and are |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1629 | deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns |
| 1630 | ``['1', '', '2']``). The *sep* argument may consist of multiple characters |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1631 | (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1632 | Splitting an empty string with a specified separator returns ``['']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1633 | |
| 1634 | If *sep* is not specified or is ``None``, a different splitting algorithm is |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1635 | applied: runs of consecutive whitespace are regarded as a single separator, |
| 1636 | and the result will contain no empty strings at the start or end if the |
| 1637 | string has leading or trailing whitespace. Consequently, splitting an empty |
| 1638 | string or a string consisting of just whitespace with a ``None`` separator |
| 1639 | returns ``[]``. |
| 1640 | |
| 1641 | For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and |
| 1642 | ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1643 | |
| 1644 | |
R David Murray | 1b00f25 | 2012-08-15 10:43:58 -0400 | [diff] [blame] | 1645 | .. index:: |
| 1646 | single: universal newlines; str.splitlines method |
| 1647 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1648 | .. method:: str.splitlines([keepends]) |
| 1649 | |
R David Murray | 05c35a6 | 2012-08-06 16:08:09 -0400 | [diff] [blame] | 1650 | Return a list of the lines in the string, breaking at line boundaries. |
R David Murray | 1b00f25 | 2012-08-15 10:43:58 -0400 | [diff] [blame] | 1651 | This method uses the :term:`universal newlines` approach to splitting lines. |
R David Murray | 05c35a6 | 2012-08-06 16:08:09 -0400 | [diff] [blame] | 1652 | Line breaks are not included in the resulting list unless *keepends* is |
| 1653 | given and true. |
R David Murray | ae1b94b | 2012-06-01 16:19:36 -0400 | [diff] [blame] | 1654 | |
| 1655 | For example, ``'ab c\n\nde fg\rkl\r\n'.splitlines()`` returns |
R David Murray | 554b348 | 2012-06-02 11:20:29 -0400 | [diff] [blame] | 1656 | ``['ab c', '', 'de fg', 'kl']``, while the same call with ``splitlines(True)`` |
Sandro Tosi | 82a509c | 2012-08-12 12:35:14 +0200 | [diff] [blame] | 1657 | returns ``['ab c\n', '\n', 'de fg\r', 'kl\r\n']``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1658 | |
R David Murray | 05c35a6 | 2012-08-06 16:08:09 -0400 | [diff] [blame] | 1659 | Unlike :meth:`~str.split` when a delimiter string *sep* is given, this |
| 1660 | method returns an empty list for the empty string, and a terminal line |
| 1661 | break does not result in an extra line. |
| 1662 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1663 | |
| 1664 | .. method:: str.startswith(prefix[, start[, end]]) |
| 1665 | |
| 1666 | Return ``True`` if string starts with the *prefix*, otherwise return ``False``. |
| 1667 | *prefix* can also be a tuple of prefixes to look for. With optional *start*, |
| 1668 | test string beginning at that position. With optional *end*, stop comparing |
| 1669 | string at that position. |
| 1670 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1671 | |
| 1672 | .. method:: str.strip([chars]) |
| 1673 | |
| 1674 | Return a copy of the string with the leading and trailing characters removed. |
| 1675 | The *chars* argument is a string specifying the set of characters to be removed. |
| 1676 | If omitted or ``None``, the *chars* argument defaults to removing whitespace. |
| 1677 | The *chars* argument is not a prefix or suffix; rather, all combinations of its |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1678 | values are stripped: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1679 | |
| 1680 | >>> ' spacious '.strip() |
| 1681 | 'spacious' |
| 1682 | >>> 'www.example.com'.strip('cmowz.') |
| 1683 | 'example' |
| 1684 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1685 | |
| 1686 | .. method:: str.swapcase() |
| 1687 | |
| 1688 | Return a copy of the string with uppercase characters converted to lowercase and |
Benjamin Peterson | b2bf01d | 2012-01-11 18:17:06 -0500 | [diff] [blame] | 1689 | vice versa. Note that it is not necessarily true that |
| 1690 | ``s.swapcase().swapcase() == s``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1691 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1692 | |
| 1693 | .. method:: str.title() |
| 1694 | |
Raymond Hettinger | b8b0ba1 | 2009-09-29 06:22:28 +0000 | [diff] [blame] | 1695 | Return a titlecased version of the string where words start with an uppercase |
| 1696 | character and the remaining characters are lowercase. |
| 1697 | |
| 1698 | The algorithm uses a simple language-independent definition of a word as |
| 1699 | groups of consecutive letters. The definition works in many contexts but |
| 1700 | it means that apostrophes in contractions and possessives form word |
| 1701 | boundaries, which may not be the desired result:: |
| 1702 | |
| 1703 | >>> "they're bill's friends from the UK".title() |
| 1704 | "They'Re Bill'S Friends From The Uk" |
| 1705 | |
| 1706 | A workaround for apostrophes can be constructed using regular expressions:: |
| 1707 | |
| 1708 | >>> import re |
| 1709 | >>> def titlecase(s): |
| 1710 | return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", |
| 1711 | lambda mo: mo.group(0)[0].upper() + |
| 1712 | mo.group(0)[1:].lower(), |
| 1713 | s) |
| 1714 | |
| 1715 | >>> titlecase("they're bill's friends.") |
| 1716 | "They're Bill's Friends." |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1717 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1718 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1719 | .. method:: str.translate(map) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1720 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1721 | Return a copy of the *s* where all characters have been mapped through the |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1722 | *map* which must be a dictionary of Unicode ordinals (integers) to Unicode |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1723 | ordinals, strings or ``None``. Unmapped characters are left untouched. |
| 1724 | Characters mapped to ``None`` are deleted. |
| 1725 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 1726 | You can use :meth:`str.maketrans` to create a translation map from |
| 1727 | character-to-character mappings in different formats. |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1728 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1729 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1730 | |
Georg Brandl | ceee077 | 2007-11-27 23:48:05 +0000 | [diff] [blame] | 1731 | An even more flexible approach is to create a custom character mapping |
| 1732 | codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1733 | example). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1734 | |
| 1735 | |
| 1736 | .. method:: str.upper() |
| 1737 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1738 | Return a copy of the string with all the cased characters [4]_ converted to |
| 1739 | uppercase. Note that ``str.upper().isupper()`` might be ``False`` if ``s`` |
| 1740 | contains uncased characters or if the Unicode category of the resulting |
Benjamin Peterson | 9430354 | 2012-01-18 23:09:32 -0500 | [diff] [blame] | 1741 | character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, |
| 1742 | titlecase). |
| 1743 | |
| 1744 | The uppercasing algorithm used is described in section 3.13 of the Unicode |
| 1745 | Standard. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1746 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1747 | |
| 1748 | .. method:: str.zfill(width) |
| 1749 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1750 | Return the numeric string left filled with zeros in a string of length |
| 1751 | *width*. A sign prefix is handled correctly. The original string is |
Terry Jan Reedy | f4ec3c5 | 2012-01-11 03:29:42 -0500 | [diff] [blame] | 1752 | returned if *width* is less than or equal to ``len(s)``. |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 1753 | |
| 1754 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1755 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1756 | .. _old-string-formatting: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1757 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1758 | ``printf``-style String Formatting |
| 1759 | ---------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1760 | |
| 1761 | .. index:: |
| 1762 | single: formatting, string (%) |
| 1763 | single: interpolation, string (%) |
| 1764 | single: string; formatting |
| 1765 | single: string; interpolation |
| 1766 | single: printf-style formatting |
| 1767 | single: sprintf-style formatting |
| 1768 | single: % formatting |
| 1769 | single: % interpolation |
| 1770 | |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1771 | .. note:: |
| 1772 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1773 | The formatting operations described here exhibit a variety of quirks that |
| 1774 | lead to a number of common errors (such as failing to display tuples and |
| 1775 | dictionaries correctly). Using the newer :meth:`str.format` interface |
| 1776 | helps avoid these errors, and also provides a generally more powerful, |
| 1777 | flexible and extensible approach to formatting text. |
Georg Brandl | 4b49131 | 2007-08-31 09:22:56 +0000 | [diff] [blame] | 1778 | |
| 1779 | String objects have one unique built-in operation: the ``%`` operator (modulo). |
| 1780 | This is also known as the string *formatting* or *interpolation* operator. |
| 1781 | Given ``format % values`` (where *format* is a string), ``%`` conversion |
| 1782 | specifications in *format* are replaced with zero or more elements of *values*. |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1783 | The effect is similar to using the :c:func:`sprintf` in the C language. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1784 | |
| 1785 | If *format* requires a single argument, *values* may be a single non-tuple |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 1786 | object. [5]_ Otherwise, *values* must be a tuple with exactly the number of |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1787 | items specified by the format string, or a single mapping object (for example, a |
| 1788 | dictionary). |
| 1789 | |
| 1790 | A conversion specifier contains two or more characters and has the following |
| 1791 | components, which must occur in this order: |
| 1792 | |
| 1793 | #. The ``'%'`` character, which marks the start of the specifier. |
| 1794 | |
| 1795 | #. Mapping key (optional), consisting of a parenthesised sequence of characters |
| 1796 | (for example, ``(somename)``). |
| 1797 | |
| 1798 | #. Conversion flags (optional), which affect the result of some conversion |
| 1799 | types. |
| 1800 | |
| 1801 | #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the |
| 1802 | actual width is read from the next element of the tuple in *values*, and the |
| 1803 | object to convert comes after the minimum field width and optional precision. |
| 1804 | |
| 1805 | #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 1806 | specified as ``'*'`` (an asterisk), the actual precision is read from the next |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1807 | element of the tuple in *values*, and the value to convert comes after the |
| 1808 | precision. |
| 1809 | |
| 1810 | #. Length modifier (optional). |
| 1811 | |
| 1812 | #. Conversion type. |
| 1813 | |
| 1814 | When the right argument is a dictionary (or other mapping type), then the |
| 1815 | formats in the string *must* include a parenthesised mapping key into that |
| 1816 | dictionary inserted immediately after the ``'%'`` character. The mapping key |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 1817 | selects the value to be formatted from the mapping. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1818 | |
Georg Brandl | edc9e7f | 2010-10-17 09:19:03 +0000 | [diff] [blame] | 1819 | >>> print('%(language)s has %(number)03d quote types.' % |
| 1820 | ... {'language': "Python", "number": 2}) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1821 | Python has 002 quote types. |
| 1822 | |
| 1823 | In this case no ``*`` specifiers may occur in a format (since they require a |
| 1824 | sequential parameter list). |
| 1825 | |
| 1826 | The conversion flag characters are: |
| 1827 | |
| 1828 | +---------+---------------------------------------------------------------------+ |
| 1829 | | Flag | Meaning | |
| 1830 | +=========+=====================================================================+ |
| 1831 | | ``'#'`` | The value conversion will use the "alternate form" (where defined | |
| 1832 | | | below). | |
| 1833 | +---------+---------------------------------------------------------------------+ |
| 1834 | | ``'0'`` | The conversion will be zero padded for numeric values. | |
| 1835 | +---------+---------------------------------------------------------------------+ |
| 1836 | | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | |
| 1837 | | | conversion if both are given). | |
| 1838 | +---------+---------------------------------------------------------------------+ |
| 1839 | | ``' '`` | (a space) A blank should be left before a positive number (or empty | |
| 1840 | | | string) produced by a signed conversion. | |
| 1841 | +---------+---------------------------------------------------------------------+ |
| 1842 | | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | |
| 1843 | | | (overrides a "space" flag). | |
| 1844 | +---------+---------------------------------------------------------------------+ |
| 1845 | |
| 1846 | A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1847 | is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1848 | |
| 1849 | The conversion types are: |
| 1850 | |
| 1851 | +------------+-----------------------------------------------------+-------+ |
| 1852 | | Conversion | Meaning | Notes | |
| 1853 | +============+=====================================================+=======+ |
| 1854 | | ``'d'`` | Signed integer decimal. | | |
| 1855 | +------------+-----------------------------------------------------+-------+ |
| 1856 | | ``'i'`` | Signed integer decimal. | | |
| 1857 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1858 | | ``'o'`` | Signed octal value. | \(1) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1859 | +------------+-----------------------------------------------------+-------+ |
Benjamin Peterson | e0124bd | 2009-03-09 21:04:33 +0000 | [diff] [blame] | 1860 | | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1861 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1862 | | ``'x'`` | Signed hexadecimal (lowercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1863 | +------------+-----------------------------------------------------+-------+ |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1864 | | ``'X'`` | Signed hexadecimal (uppercase). | \(2) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1865 | +------------+-----------------------------------------------------+-------+ |
| 1866 | | ``'e'`` | Floating point exponential format (lowercase). | \(3) | |
| 1867 | +------------+-----------------------------------------------------+-------+ |
| 1868 | | ``'E'`` | Floating point exponential format (uppercase). | \(3) | |
| 1869 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 1870 | | ``'f'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1871 | +------------+-----------------------------------------------------+-------+ |
Eric Smith | 22b85b3 | 2008-07-17 19:18:29 +0000 | [diff] [blame] | 1872 | | ``'F'`` | Floating point decimal format. | \(3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1873 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 1874 | | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | |
| 1875 | | | format if exponent is less than -4 or not less than | | |
| 1876 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1877 | +------------+-----------------------------------------------------+-------+ |
Christian Heimes | 8dc226f | 2008-05-06 23:45:46 +0000 | [diff] [blame] | 1878 | | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | |
| 1879 | | | format if exponent is less than -4 or not less than | | |
| 1880 | | | precision, decimal format otherwise. | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1881 | +------------+-----------------------------------------------------+-------+ |
| 1882 | | ``'c'`` | Single character (accepts integer or single | | |
| 1883 | | | character string). | | |
| 1884 | +------------+-----------------------------------------------------+-------+ |
Ezio Melotti | 0639d5a | 2009-12-19 23:26:38 +0000 | [diff] [blame] | 1885 | | ``'r'`` | String (converts any Python object using | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1886 | | | :func:`repr`). | | |
| 1887 | +------------+-----------------------------------------------------+-------+ |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 1888 | | ``'s'`` | String (converts any Python object using | \(5) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1889 | | | :func:`str`). | | |
| 1890 | +------------+-----------------------------------------------------+-------+ |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 1891 | | ``'a'`` | String (converts any Python object using | \(5) | |
| 1892 | | | :func:`ascii`). | | |
| 1893 | +------------+-----------------------------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1894 | | ``'%'`` | No argument is converted, results in a ``'%'`` | | |
| 1895 | | | character in the result. | | |
| 1896 | +------------+-----------------------------------------------------+-------+ |
| 1897 | |
| 1898 | Notes: |
| 1899 | |
| 1900 | (1) |
| 1901 | The alternate form causes a leading zero (``'0'``) to be inserted between |
| 1902 | left-hand padding and the formatting of the number if the leading character |
| 1903 | of the result is not already a zero. |
| 1904 | |
| 1905 | (2) |
| 1906 | The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether |
| 1907 | the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding |
| 1908 | and the formatting of the number if the leading character of the result is not |
| 1909 | already a zero. |
| 1910 | |
| 1911 | (3) |
| 1912 | The alternate form causes the result to always contain a decimal point, even if |
| 1913 | no digits follow it. |
| 1914 | |
| 1915 | The precision determines the number of digits after the decimal point and |
| 1916 | defaults to 6. |
| 1917 | |
| 1918 | (4) |
| 1919 | The alternate form causes the result to always contain a decimal point, and |
| 1920 | trailing zeroes are not removed as they would otherwise be. |
| 1921 | |
| 1922 | The precision determines the number of significant digits before and after the |
| 1923 | decimal point and defaults to 6. |
| 1924 | |
| 1925 | (5) |
Eli Bendersky | ef4902a | 2011-07-29 09:30:42 +0300 | [diff] [blame] | 1926 | If precision is ``N``, the output is truncated to ``N`` characters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1927 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1928 | |
Alexandre Vassalotti | 5f8ced2 | 2008-05-16 00:03:33 +0000 | [diff] [blame] | 1929 | (7) |
| 1930 | See :pep:`237`. |
| 1931 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1932 | Since Python strings have an explicit length, ``%s`` conversions do not assume |
| 1933 | that ``'\0'`` is the end of the string. |
| 1934 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1935 | .. XXX Examples? |
| 1936 | |
Mark Dickinson | 33841c3 | 2009-05-01 15:37:04 +0000 | [diff] [blame] | 1937 | .. versionchanged:: 3.1 |
| 1938 | ``%f`` conversions for numbers whose absolute value is over 1e50 are no |
| 1939 | longer replaced by ``%g`` conversions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1940 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1941 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1942 | .. _binaryseq: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1943 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1944 | Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview` |
| 1945 | ================================================================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1946 | |
| 1947 | .. index:: |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1948 | object: bytes |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 1949 | object: bytearray |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1950 | object: memoryview |
| 1951 | module: array |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1952 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1953 | The core built-in types for manipulating binary data are :class:`bytes` and |
| 1954 | :class:`bytearray`. They are supported by :class:`memoryview` which uses |
| 1955 | the buffer protocol to access the memory of other binary objects without |
| 1956 | needing to make a copy. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 1957 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1958 | The :mod:`array` module supports efficient storage of basic data types like |
| 1959 | 32-bit integers and IEEE754 double-precision floating values. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1960 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1961 | .. _typebytes: |
Senthil Kumaran | 7cafd26 | 2010-10-02 03:16:04 +0000 | [diff] [blame] | 1962 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 1963 | Bytes |
| 1964 | ----- |
| 1965 | |
| 1966 | .. index:: object: bytes |
| 1967 | |
| 1968 | Bytes objects are immutable sequences of single bytes. Since many major |
| 1969 | binary protocols are based on the ASCII text encoding, bytes objects offer |
| 1970 | several methods that are only valid when working with ASCII compatible |
| 1971 | data and are closely related to string objects in a variety of other ways. |
| 1972 | |
| 1973 | Firstly, the syntax for bytes literals is largely the same as that for string |
| 1974 | literals, except that a ``b`` prefix is added: |
| 1975 | |
| 1976 | * Single quotes: ``b'still allows embedded "double" quotes'`` |
| 1977 | * Double quotes: ``b"still allows embedded 'single' quotes"``. |
| 1978 | * Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""`` |
| 1979 | |
| 1980 | Only ASCII characters are permitted in bytes literals (regardless of the |
| 1981 | declared source code encoding). Any binary values over 127 must be entered |
| 1982 | into bytes literals using the appropriate escape sequence. |
| 1983 | |
| 1984 | As with string literals, bytes literals may also use a ``r`` prefix to disable |
| 1985 | processing of escape sequences. See :ref:`strings` for more about the various |
| 1986 | forms of bytes literal, including supported escape sequences. |
| 1987 | |
| 1988 | While bytes literals and representations are based on ASCII text, bytes |
| 1989 | objects actually behave like immutable sequences of integers, with each |
| 1990 | value in the sequence restricted such that ``0 <= x < 256`` (attempts to |
| 1991 | violate this restriction will trigger :exc:`ValueError`. This is done |
| 1992 | deliberately to emphasise that while many binary formats include ASCII based |
| 1993 | elements and can be usefully manipulated with some text-oriented algorithms, |
| 1994 | this is not generally the case for arbitrary binary data (blindly applying |
| 1995 | text processing algorithms to binary data formats that are not ASCII |
| 1996 | compatible will usually lead to data corruption). |
| 1997 | |
| 1998 | In addition to the literal forms, bytes objects can be created in a number of |
| 1999 | other ways: |
| 2000 | |
| 2001 | * A zero-filled bytes object of a specified length: ``bytes(10)`` |
| 2002 | * From an iterable of integers: ``bytes(range(20))`` |
| 2003 | * Copying existing binary data via the buffer protocol: ``bytes(obj)`` |
| 2004 | |
| 2005 | Since bytes objects are sequences of integers, for a bytes object *b*, |
| 2006 | ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes object of |
| 2007 | length 1. (This contrasts with text strings, where both indexing and |
| 2008 | slicing will produce a string of length 1) |
| 2009 | |
| 2010 | The representation of bytes objects uses the literal format (``b'...'``) |
| 2011 | since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can |
| 2012 | always convert a bytes object into a list of integers using ``list(b)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2013 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2014 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2015 | .. note:: |
| 2016 | For Python 2.x users: In the Python 2.x series, a variety of implicit |
| 2017 | conversions between 8-bit strings (the closest thing 2.x offers to a |
| 2018 | built-in binary data type) and Unicode strings were permitted. This was a |
| 2019 | backwards compatibility workaround to account for the fact that Python |
| 2020 | originally only supported 8-bit text, and Unicode text was a later |
| 2021 | addition. In Python 3.x, those implicit conversions are gone - conversions |
| 2022 | between 8-bit binary data and Unicode text must be explicit, and bytes and |
| 2023 | string objects will always compare unequal. |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 2024 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2025 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2026 | .. _typebytearray: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2027 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2028 | Bytearray Objects |
| 2029 | ----------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2030 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2031 | .. index:: object: bytearray |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 2032 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2033 | :class:`bytearray` objects are a mutable counterpart to :class:`bytes` |
| 2034 | objects. There is no dedicated literal syntax for bytearray objects, instead |
| 2035 | they are always created by calling the constructor: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2036 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2037 | * Creating an empty instance: ``bytearray()`` |
| 2038 | * Creating a zero-filled instance with a given length: ``bytearray(10)`` |
| 2039 | * From an iterable of integers: ``bytearray(range(20))`` |
| 2040 | * Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!)`` |
Eli Bendersky | cbbaa96 | 2011-02-25 05:47:53 +0000 | [diff] [blame] | 2041 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2042 | As bytearray objects are mutable, they support the |
| 2043 | :ref:`mutable <typesseq-mutable>` sequence operations in addition to the |
| 2044 | common bytes and bytearray operations described in :ref:`bytes-methods`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2045 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 2046 | |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2047 | .. _bytes-methods: |
| 2048 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2049 | Bytes and Bytearray Operations |
| 2050 | ------------------------------ |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2051 | |
| 2052 | .. index:: pair: bytes; methods |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 2053 | pair: bytearray; methods |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2054 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2055 | Both bytes and bytearray objects support the :ref:`common <typesseq-common>` |
| 2056 | sequence operations. They interoperate not just with operands of the same |
| 2057 | type, but with any object that supports the |
| 2058 | :ref:`buffer protocol <bufferobjects>`. Due to this flexibility, they can be |
| 2059 | freely mixed in operations without causing errors. However, the return type |
| 2060 | of the result may depend on the order of operands. |
Guido van Rossum | 98297ee | 2007-11-06 21:34:58 +0000 | [diff] [blame] | 2061 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2062 | Due to the common use of ASCII text as the basis for binary protocols, bytes |
| 2063 | and bytearray objects provide almost all methods found on text strings, with |
| 2064 | the exceptions of: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2065 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2066 | * :meth:`str.encode` (which converts text strings to bytes objects) |
| 2067 | * :meth:`str.format` and :meth:`str.format_map` (which are used to format |
| 2068 | text for display to users) |
| 2069 | * :meth:`str.isidentifier`, :meth:`str.isnumeric`, :meth:`str.isdecimal`, |
| 2070 | :meth:`str.isprintable` (which are used to check various properties of |
| 2071 | text strings which are not typically applicable to binary protocols). |
| 2072 | |
| 2073 | All other string methods are supported, although sometimes with slight |
| 2074 | differences in functionality and semantics (as described below). |
Antoine Pitrou | ac65d96 | 2011-10-20 23:54:17 +0200 | [diff] [blame] | 2075 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2076 | .. note:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2077 | |
Georg Brandl | 9541463 | 2007-11-22 11:00:28 +0000 | [diff] [blame] | 2078 | The methods on bytes and bytearray objects don't accept strings as their |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2079 | arguments, just as the methods on strings don't accept bytes as their |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2080 | arguments. For example, you have to write:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2081 | |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2082 | a = "abc" |
| 2083 | b = a.replace("a", "f") |
| 2084 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2085 | and:: |
Georg Brandl | 7c67613 | 2007-10-23 18:17:00 +0000 | [diff] [blame] | 2086 | |
| 2087 | a = b"abc" |
| 2088 | b = a.replace(b"a", b"f") |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2089 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2090 | Whenever a bytes or bytearray method needs to interpret the bytes as |
| 2091 | characters (e.g. the :meth:`is...` methods, :meth:`split`, :meth:`strip`), |
| 2092 | the ASCII character set is assumed (text strings use Unicode semantics). |
| 2093 | |
| 2094 | .. note:: |
| 2095 | Using these ASCII based methods to manipulate binary data that is not |
| 2096 | stored in an ASCII based format may lead to data corruption. |
| 2097 | |
| 2098 | The search operations (:keyword:`in`, :meth:`count`, :meth:`find`, |
| 2099 | :meth:`index`, :meth:`rfind` and :meth:`rindex`) all accept both integers |
| 2100 | in the range 0 to 255 as well as bytes and byte array sequences. |
| 2101 | |
| 2102 | .. versionchanged:: 3.3 |
| 2103 | All of the search methods also accept an integer in range 0 to 255 |
| 2104 | (a byte) as their first argument. |
| 2105 | |
| 2106 | |
| 2107 | Each bytes and bytearray instance provides a :meth:`decode` convenience |
| 2108 | method that is the inverse of "meth:`str.encode`: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2109 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 2110 | .. method:: bytes.decode(encoding="utf-8", errors="strict") |
| 2111 | bytearray.decode(encoding="utf-8", errors="strict") |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 2112 | |
Victor Stinner | e14e212 | 2010-11-07 18:41:46 +0000 | [diff] [blame] | 2113 | Return a string decoded from the given bytes. Default encoding is |
| 2114 | ``'utf-8'``. *errors* may be given to set a different |
Georg Brandl | 4f5f98d | 2009-05-04 21:01:20 +0000 | [diff] [blame] | 2115 | error handling scheme. The default for *errors* is ``'strict'``, meaning |
| 2116 | that encoding errors raise a :exc:`UnicodeError`. Other possible values are |
| 2117 | ``'ignore'``, ``'replace'`` and any other name registered via |
| 2118 | :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a |
| 2119 | list of possible encodings, see section :ref:`standard-encodings`. |
| 2120 | |
Benjamin Peterson | 308d637 | 2009-09-18 21:42:35 +0000 | [diff] [blame] | 2121 | .. versionchanged:: 3.1 |
| 2122 | Added support for keyword arguments. |
| 2123 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2124 | Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal |
| 2125 | numbers are a commonly used format for describing binary data. Accordingly, |
| 2126 | the bytes and bytearray types have an additional class method to read data in |
| 2127 | that format: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2128 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2129 | .. classmethod:: bytes.fromhex(string) |
| 2130 | bytearray.fromhex(string) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2131 | |
Georg Brandl | 18da8f0 | 2008-07-01 20:08:02 +0000 | [diff] [blame] | 2132 | This :class:`bytes` class method returns a bytes or bytearray object, |
| 2133 | decoding the given string object. The string must contain two hexadecimal |
| 2134 | digits per byte, spaces are ignored. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2135 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2136 | >>> bytes.fromhex('2Ef0 F1f2 ') |
| 2137 | b'.\xf0\xf1\xf2' |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2138 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2139 | |
| 2140 | The maketrans and translate methods differ in semantics from the versions |
| 2141 | available on strings: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 2142 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2143 | .. method:: bytes.translate(table[, delete]) |
Georg Brandl | 751771b | 2009-05-31 21:38:37 +0000 | [diff] [blame] | 2144 | bytearray.translate(table[, delete]) |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2145 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2146 | Return a copy of the bytes or bytearray object where all bytes occurring in |
| 2147 | the optional argument *delete* are removed, and the remaining bytes have been |
| 2148 | mapped through the given translation table, which must be a bytes object of |
| 2149 | length 256. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2150 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2151 | You can use the :func:`bytes.maketrans` method to create a translation table. |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2152 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2153 | Set the *table* argument to ``None`` for translations that only delete |
| 2154 | characters:: |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2155 | |
Georg Brandl | 454636f | 2008-12-27 23:33:20 +0000 | [diff] [blame] | 2156 | >>> b'read this short text'.translate(None, b'aeiou') |
| 2157 | b'rd ths shrt txt' |
Georg Brandl | 226878c | 2007-08-31 10:15:37 +0000 | [diff] [blame] | 2158 | |
| 2159 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2160 | .. staticmethod:: bytes.maketrans(from, to) |
Georg Brandl | 751771b | 2009-05-31 21:38:37 +0000 | [diff] [blame] | 2161 | bytearray.maketrans(from, to) |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2162 | |
| 2163 | This static method returns a translation table usable for |
| 2164 | :meth:`bytes.translate` that will map each character in *from* into the |
| 2165 | character at the same position in *to*; *from* and *to* must be bytes objects |
| 2166 | and have the same length. |
| 2167 | |
| 2168 | .. versionadded:: 3.1 |
| 2169 | |
| 2170 | |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2171 | .. _typememoryview: |
| 2172 | |
| 2173 | Memory Views |
| 2174 | ------------ |
| 2175 | |
| 2176 | :class:`memoryview` objects allow Python code to access the internal data |
| 2177 | of an object that supports the :ref:`buffer protocol <bufferobjects>` without |
| 2178 | copying. |
| 2179 | |
| 2180 | .. class:: memoryview(obj) |
| 2181 | |
| 2182 | Create a :class:`memoryview` that references *obj*. *obj* must support the |
| 2183 | buffer protocol. Built-in objects that support the buffer protocol include |
| 2184 | :class:`bytes` and :class:`bytearray`. |
| 2185 | |
| 2186 | A :class:`memoryview` has the notion of an *element*, which is the |
| 2187 | atomic memory unit handled by the originating object *obj*. For many |
| 2188 | simple types such as :class:`bytes` and :class:`bytearray`, an element |
| 2189 | is a single byte, but other types such as :class:`array.array` may have |
| 2190 | bigger elements. |
| 2191 | |
| 2192 | ``len(view)`` is equal to the length of :class:`~memoryview.tolist`. |
| 2193 | If ``view.ndim = 0``, the length is 1. If ``view.ndim = 1``, the length |
| 2194 | is equal to the number of elements in the view. For higher dimensions, |
| 2195 | the length is equal to the length of the nested list representation of |
| 2196 | the view. The :class:`~memoryview.itemsize` attribute will give you the |
| 2197 | number of bytes in a single element. |
| 2198 | |
| 2199 | A :class:`memoryview` supports slicing to expose its data. If |
| 2200 | :class:`~memoryview.format` is one of the native format specifiers |
| 2201 | from the :mod:`struct` module, indexing will return a single element |
| 2202 | with the correct type. Full slicing will result in a subview:: |
| 2203 | |
| 2204 | >>> v = memoryview(b'abcefg') |
| 2205 | >>> v[1] |
| 2206 | 98 |
| 2207 | >>> v[-1] |
| 2208 | 103 |
| 2209 | >>> v[1:4] |
| 2210 | <memory at 0x7f3ddc9f4350> |
| 2211 | >>> bytes(v[1:4]) |
| 2212 | b'bce' |
| 2213 | |
| 2214 | Other native formats:: |
| 2215 | |
| 2216 | >>> import array |
| 2217 | >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444]) |
| 2218 | >>> a[0] |
| 2219 | -11111111 |
| 2220 | >>> a[-1] |
| 2221 | 44444444 |
| 2222 | >>> a[2:3].tolist() |
| 2223 | [-33333333] |
| 2224 | >>> a[::2].tolist() |
| 2225 | [-11111111, -33333333] |
| 2226 | >>> a[::-1].tolist() |
| 2227 | [44444444, -33333333, 22222222, -11111111] |
| 2228 | |
| 2229 | .. versionadded:: 3.3 |
| 2230 | |
| 2231 | If the underlying object is writable, the memoryview supports slice |
| 2232 | assignment. Resizing is not allowed:: |
| 2233 | |
| 2234 | >>> data = bytearray(b'abcefg') |
| 2235 | >>> v = memoryview(data) |
| 2236 | >>> v.readonly |
| 2237 | False |
| 2238 | >>> v[0] = ord(b'z') |
| 2239 | >>> data |
| 2240 | bytearray(b'zbcefg') |
| 2241 | >>> v[1:4] = b'123' |
| 2242 | >>> data |
| 2243 | bytearray(b'z123fg') |
| 2244 | >>> v[2:3] = b'spam' |
| 2245 | Traceback (most recent call last): |
| 2246 | File "<stdin>", line 1, in <module> |
| 2247 | ValueError: memoryview assignment: lvalue and rvalue have different structures |
| 2248 | >>> v[2:6] = b'spam' |
| 2249 | >>> data |
| 2250 | bytearray(b'z1spam') |
| 2251 | |
| 2252 | Memoryviews of hashable (read-only) types are also hashable. The hash |
| 2253 | is defined as ``hash(m) == hash(m.tobytes())``:: |
| 2254 | |
| 2255 | >>> v = memoryview(b'abcefg') |
| 2256 | >>> hash(v) == hash(b'abcefg') |
| 2257 | True |
| 2258 | >>> hash(v[2:4]) == hash(b'ce') |
| 2259 | True |
| 2260 | >>> hash(v[::-2]) == hash(b'abcefg'[::-2]) |
| 2261 | True |
| 2262 | |
| 2263 | Hashing of multi-dimensional objects is supported:: |
| 2264 | |
| 2265 | >>> buf = bytes(list(range(12))) |
| 2266 | >>> x = memoryview(buf) |
| 2267 | >>> y = x.cast('B', shape=[2,2,3]) |
| 2268 | >>> x.tolist() |
| 2269 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] |
| 2270 | >>> y.tolist() |
| 2271 | [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] |
| 2272 | >>> hash(x) == hash(y) == hash(y.tobytes()) |
| 2273 | True |
| 2274 | |
| 2275 | .. versionchanged:: 3.3 |
| 2276 | Memoryview objects are now hashable. |
| 2277 | |
| 2278 | |
| 2279 | :class:`memoryview` has several methods: |
| 2280 | |
| 2281 | .. method:: tobytes() |
| 2282 | |
| 2283 | Return the data in the buffer as a bytestring. This is equivalent to |
| 2284 | calling the :class:`bytes` constructor on the memoryview. :: |
| 2285 | |
| 2286 | >>> m = memoryview(b"abc") |
| 2287 | >>> m.tobytes() |
| 2288 | b'abc' |
| 2289 | >>> bytes(m) |
| 2290 | b'abc' |
| 2291 | |
| 2292 | For non-contiguous arrays the result is equal to the flattened list |
| 2293 | representation with all elements converted to bytes. |
| 2294 | |
| 2295 | .. method:: tolist() |
| 2296 | |
| 2297 | Return the data in the buffer as a list of elements. :: |
| 2298 | |
| 2299 | >>> memoryview(b'abc').tolist() |
| 2300 | [97, 98, 99] |
| 2301 | >>> import array |
| 2302 | >>> a = array.array('d', [1.1, 2.2, 3.3]) |
| 2303 | >>> m = memoryview(a) |
| 2304 | >>> m.tolist() |
| 2305 | [1.1, 2.2, 3.3] |
| 2306 | |
| 2307 | .. method:: release() |
| 2308 | |
| 2309 | Release the underlying buffer exposed by the memoryview object. Many |
| 2310 | objects take special actions when a view is held on them (for example, |
| 2311 | a :class:`bytearray` would temporarily forbid resizing); therefore, |
| 2312 | calling release() is handy to remove these restrictions (and free any |
| 2313 | dangling resources) as soon as possible. |
| 2314 | |
| 2315 | After this method has been called, any further operation on the view |
| 2316 | raises a :class:`ValueError` (except :meth:`release()` itself which can |
| 2317 | be called multiple times):: |
| 2318 | |
| 2319 | >>> m = memoryview(b'abc') |
| 2320 | >>> m.release() |
| 2321 | >>> m[0] |
| 2322 | Traceback (most recent call last): |
| 2323 | File "<stdin>", line 1, in <module> |
| 2324 | ValueError: operation forbidden on released memoryview object |
| 2325 | |
| 2326 | The context management protocol can be used for a similar effect, |
| 2327 | using the ``with`` statement:: |
| 2328 | |
| 2329 | >>> with memoryview(b'abc') as m: |
| 2330 | ... m[0] |
| 2331 | ... |
| 2332 | 97 |
| 2333 | >>> m[0] |
| 2334 | Traceback (most recent call last): |
| 2335 | File "<stdin>", line 1, in <module> |
| 2336 | ValueError: operation forbidden on released memoryview object |
| 2337 | |
| 2338 | .. versionadded:: 3.2 |
| 2339 | |
| 2340 | .. method:: cast(format[, shape]) |
| 2341 | |
| 2342 | Cast a memoryview to a new format or shape. *shape* defaults to |
| 2343 | ``[byte_length//new_itemsize]``, which means that the result view |
| 2344 | will be one-dimensional. The return value is a new memoryview, but |
| 2345 | the buffer itself is not copied. Supported casts are 1D -> C-contiguous |
| 2346 | and C-contiguous -> 1D. One of the formats must be a byte format |
| 2347 | ('B', 'b' or 'c'). The byte length of the result must be the same |
| 2348 | as the original length. |
| 2349 | |
| 2350 | Cast 1D/long to 1D/unsigned bytes:: |
| 2351 | |
| 2352 | >>> import array |
| 2353 | >>> a = array.array('l', [1,2,3]) |
| 2354 | >>> x = memoryview(a) |
| 2355 | >>> x.format |
| 2356 | 'l' |
| 2357 | >>> x.itemsize |
| 2358 | 8 |
| 2359 | >>> len(x) |
| 2360 | 3 |
| 2361 | >>> x.nbytes |
| 2362 | 24 |
| 2363 | >>> y = x.cast('B') |
| 2364 | >>> y.format |
| 2365 | 'B' |
| 2366 | >>> y.itemsize |
| 2367 | 1 |
| 2368 | >>> len(y) |
| 2369 | 24 |
| 2370 | >>> y.nbytes |
| 2371 | 24 |
| 2372 | |
| 2373 | Cast 1D/unsigned bytes to 1D/char:: |
| 2374 | |
| 2375 | >>> b = bytearray(b'zyz') |
| 2376 | >>> x = memoryview(b) |
| 2377 | >>> x[0] = b'a' |
| 2378 | Traceback (most recent call last): |
| 2379 | File "<stdin>", line 1, in <module> |
| 2380 | ValueError: memoryview: invalid value for format "B" |
| 2381 | >>> y = x.cast('c') |
| 2382 | >>> y[0] = b'a' |
| 2383 | >>> b |
| 2384 | bytearray(b'ayz') |
| 2385 | |
| 2386 | Cast 1D/bytes to 3D/ints to 1D/signed char:: |
| 2387 | |
| 2388 | >>> import struct |
| 2389 | >>> buf = struct.pack("i"*12, *list(range(12))) |
| 2390 | >>> x = memoryview(buf) |
| 2391 | >>> y = x.cast('i', shape=[2,2,3]) |
| 2392 | >>> y.tolist() |
| 2393 | [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] |
| 2394 | >>> y.format |
| 2395 | 'i' |
| 2396 | >>> y.itemsize |
| 2397 | 4 |
| 2398 | >>> len(y) |
| 2399 | 2 |
| 2400 | >>> y.nbytes |
| 2401 | 48 |
| 2402 | >>> z = y.cast('b') |
| 2403 | >>> z.format |
| 2404 | 'b' |
| 2405 | >>> z.itemsize |
| 2406 | 1 |
| 2407 | >>> len(z) |
| 2408 | 48 |
| 2409 | >>> z.nbytes |
| 2410 | 48 |
| 2411 | |
| 2412 | Cast 1D/unsigned char to to 2D/unsigned long:: |
| 2413 | |
| 2414 | >>> buf = struct.pack("L"*6, *list(range(6))) |
| 2415 | >>> x = memoryview(buf) |
| 2416 | >>> y = x.cast('L', shape=[2,3]) |
| 2417 | >>> len(y) |
| 2418 | 2 |
| 2419 | >>> y.nbytes |
| 2420 | 48 |
| 2421 | >>> y.tolist() |
| 2422 | [[0, 1, 2], [3, 4, 5]] |
| 2423 | |
| 2424 | .. versionadded:: 3.3 |
| 2425 | |
| 2426 | There are also several readonly attributes available: |
| 2427 | |
| 2428 | .. attribute:: obj |
| 2429 | |
| 2430 | The underlying object of the memoryview:: |
| 2431 | |
| 2432 | >>> b = bytearray(b'xyz') |
| 2433 | >>> m = memoryview(b) |
| 2434 | >>> m.obj is b |
| 2435 | True |
| 2436 | |
| 2437 | .. versionadded:: 3.3 |
| 2438 | |
| 2439 | .. attribute:: nbytes |
| 2440 | |
| 2441 | ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is |
| 2442 | the amount of space in bytes that the array would use in a contiguous |
| 2443 | representation. It is not necessarily equal to len(m):: |
| 2444 | |
| 2445 | >>> import array |
| 2446 | >>> a = array.array('i', [1,2,3,4,5]) |
| 2447 | >>> m = memoryview(a) |
| 2448 | >>> len(m) |
| 2449 | 5 |
| 2450 | >>> m.nbytes |
| 2451 | 20 |
| 2452 | >>> y = m[::2] |
| 2453 | >>> len(y) |
| 2454 | 3 |
| 2455 | >>> y.nbytes |
| 2456 | 12 |
| 2457 | >>> len(y.tobytes()) |
| 2458 | 12 |
| 2459 | |
| 2460 | Multi-dimensional arrays:: |
| 2461 | |
| 2462 | >>> import struct |
| 2463 | >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) |
| 2464 | >>> x = memoryview(buf) |
| 2465 | >>> y = x.cast('d', shape=[3,4]) |
| 2466 | >>> y.tolist() |
| 2467 | [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] |
| 2468 | >>> len(y) |
| 2469 | 3 |
| 2470 | >>> y.nbytes |
| 2471 | 96 |
| 2472 | |
| 2473 | .. versionadded:: 3.3 |
| 2474 | |
| 2475 | .. attribute:: readonly |
| 2476 | |
| 2477 | A bool indicating whether the memory is read only. |
| 2478 | |
| 2479 | .. attribute:: format |
| 2480 | |
| 2481 | A string containing the format (in :mod:`struct` module style) for each |
| 2482 | element in the view. A memoryview can be created from exporters with |
| 2483 | arbitrary format strings, but some methods (e.g. :meth:`tolist`) are |
| 2484 | restricted to native single element formats. Special care must be taken |
| 2485 | when comparing memoryviews. Since comparisons are required to return a |
| 2486 | value for ``==`` and ``!=``, two memoryviews referencing the same |
| 2487 | exporter can compare as not-equal if the exporter's format is not |
| 2488 | understood:: |
| 2489 | |
| 2490 | >>> from ctypes import BigEndianStructure, c_long |
| 2491 | >>> class BEPoint(BigEndianStructure): |
| 2492 | ... _fields_ = [("x", c_long), ("y", c_long)] |
| 2493 | ... |
| 2494 | >>> point = BEPoint(100, 200) |
| 2495 | >>> a = memoryview(point) |
| 2496 | >>> b = memoryview(point) |
| 2497 | >>> a == b |
| 2498 | False |
| 2499 | >>> a.tolist() |
| 2500 | Traceback (most recent call last): |
| 2501 | File "<stdin>", line 1, in <module> |
| 2502 | NotImplementedError: memoryview: unsupported format T{>l:x:>l:y:} |
| 2503 | |
| 2504 | .. attribute:: itemsize |
| 2505 | |
| 2506 | The size in bytes of each element of the memoryview:: |
| 2507 | |
| 2508 | >>> import array, struct |
| 2509 | >>> m = memoryview(array.array('H', [32000, 32001, 32002])) |
| 2510 | >>> m.itemsize |
| 2511 | 2 |
| 2512 | >>> m[0] |
| 2513 | 32000 |
| 2514 | >>> struct.calcsize('H') == m.itemsize |
| 2515 | True |
| 2516 | |
| 2517 | .. attribute:: ndim |
| 2518 | |
| 2519 | An integer indicating how many dimensions of a multi-dimensional array the |
| 2520 | memory represents. |
| 2521 | |
| 2522 | .. attribute:: shape |
| 2523 | |
| 2524 | A tuple of integers the length of :attr:`ndim` giving the shape of the |
| 2525 | memory as a N-dimensional array. |
| 2526 | |
| 2527 | .. attribute:: strides |
| 2528 | |
| 2529 | A tuple of integers the length of :attr:`ndim` giving the size in bytes to |
| 2530 | access each element for each dimension of the array. |
| 2531 | |
| 2532 | .. attribute:: suboffsets |
| 2533 | |
| 2534 | Used internally for PIL-style arrays. The value is informational only. |
| 2535 | |
| 2536 | .. attribute:: c_contiguous |
| 2537 | |
| 2538 | A bool indicating whether the memory is C-contiguous. |
| 2539 | |
| 2540 | .. versionadded:: 3.3 |
| 2541 | |
| 2542 | .. attribute:: f_contiguous |
| 2543 | |
| 2544 | A bool indicating whether the memory is Fortran contiguous. |
| 2545 | |
| 2546 | .. versionadded:: 3.3 |
| 2547 | |
| 2548 | .. attribute:: contiguous |
| 2549 | |
| 2550 | A bool indicating whether the memory is contiguous. |
| 2551 | |
| 2552 | .. versionadded:: 3.3 |
| 2553 | |
| 2554 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2555 | .. _types-set: |
| 2556 | |
| 2557 | Set Types --- :class:`set`, :class:`frozenset` |
| 2558 | ============================================== |
| 2559 | |
| 2560 | .. index:: object: set |
| 2561 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 2562 | A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2563 | Common uses include membership testing, removing duplicates from a sequence, and |
| 2564 | computing mathematical operations such as intersection, union, difference, and |
| 2565 | symmetric difference. |
| 2566 | (For other containers see the built in :class:`dict`, :class:`list`, |
| 2567 | and :class:`tuple` classes, and the :mod:`collections` module.) |
| 2568 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2569 | Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in |
| 2570 | set``. Being an unordered collection, sets do not record element position or |
| 2571 | order of insertion. Accordingly, sets do not support indexing, slicing, or |
| 2572 | other sequence-like behavior. |
| 2573 | |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 2574 | There are currently two built-in set types, :class:`set` and :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2575 | The :class:`set` type is mutable --- the contents can be changed using methods |
| 2576 | like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value |
| 2577 | and cannot be used as either a dictionary key or as an element of another set. |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 2578 | The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2579 | altered after it is created; it can therefore be used as a dictionary key or as |
| 2580 | an element of another set. |
| 2581 | |
Georg Brandl | 99cd957 | 2010-03-21 09:10:32 +0000 | [diff] [blame] | 2582 | Non-empty sets (not frozensets) can be created by placing a comma-separated list |
Georg Brandl | 53b95e7 | 2010-03-21 11:53:50 +0000 | [diff] [blame] | 2583 | of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the |
| 2584 | :class:`set` constructor. |
Georg Brandl | 99cd957 | 2010-03-21 09:10:32 +0000 | [diff] [blame] | 2585 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2586 | The constructors for both classes work the same: |
| 2587 | |
| 2588 | .. class:: set([iterable]) |
| 2589 | frozenset([iterable]) |
| 2590 | |
| 2591 | Return a new set or frozenset object whose elements are taken from |
| 2592 | *iterable*. The elements of a set must be hashable. To represent sets of |
| 2593 | sets, the inner sets must be :class:`frozenset` objects. If *iterable* is |
| 2594 | not specified, a new empty set is returned. |
| 2595 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2596 | Instances of :class:`set` and :class:`frozenset` provide the following |
| 2597 | operations: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2598 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2599 | .. describe:: len(s) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2600 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2601 | Return the cardinality of set *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2602 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2603 | .. describe:: x in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2604 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2605 | Test *x* for membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2606 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2607 | .. describe:: x not in s |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2608 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2609 | Test *x* for non-membership in *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2610 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2611 | .. method:: isdisjoint(other) |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 2612 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2613 | Return True if the set has no elements in common with *other*. Sets are |
Georg Brandl | 2ee470f | 2008-07-16 12:55:28 +0000 | [diff] [blame] | 2614 | disjoint if and only if their intersection is the empty set. |
Guido van Rossum | 58da931 | 2007-11-10 23:39:45 +0000 | [diff] [blame] | 2615 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2616 | .. method:: issubset(other) |
| 2617 | set <= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2618 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2619 | Test whether every element in the set is in *other*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2620 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2621 | .. method:: set < other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 2622 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2623 | Test whether the set is a true subset of *other*, that is, |
| 2624 | ``set <= other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 2625 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2626 | .. method:: issuperset(other) |
| 2627 | set >= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2628 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2629 | Test whether every element in *other* is in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2630 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2631 | .. method:: set > other |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 2632 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2633 | Test whether the set is a true superset of *other*, that is, ``set >= |
| 2634 | other and set != other``. |
Georg Brandl | a6f5278 | 2007-09-01 15:49:30 +0000 | [diff] [blame] | 2635 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 2636 | .. method:: union(other, ...) |
| 2637 | set | other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2638 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 2639 | Return a new set with elements from the set and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2640 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 2641 | .. method:: intersection(other, ...) |
| 2642 | set & other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2643 | |
Benjamin Peterson | b58dda7 | 2009-01-18 22:27:04 +0000 | [diff] [blame] | 2644 | Return a new set with elements common to the set and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2645 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 2646 | .. method:: difference(other, ...) |
| 2647 | set - other - ... |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 2648 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 2649 | Return a new set with elements in the set that are not in the others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2650 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2651 | .. method:: symmetric_difference(other) |
| 2652 | set ^ other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2653 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2654 | Return a new set with elements in either the set or *other* but not both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2655 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2656 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2657 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2658 | Return a new set with a shallow copy of *s*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2659 | |
| 2660 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2661 | Note, the non-operator versions of :meth:`union`, :meth:`intersection`, |
| 2662 | :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and |
| 2663 | :meth:`issuperset` methods will accept any iterable as an argument. In |
| 2664 | contrast, their operator based counterparts require their arguments to be |
| 2665 | sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` |
| 2666 | in favor of the more readable ``set('abc').intersection('cbs')``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2667 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2668 | Both :class:`set` and :class:`frozenset` support set to set comparisons. Two |
| 2669 | sets are equal if and only if every element of each set is contained in the |
| 2670 | other (each is a subset of the other). A set is less than another set if and |
| 2671 | only if the first set is a proper subset of the second set (is a subset, but |
| 2672 | is not equal). A set is greater than another set if and only if the first set |
| 2673 | is a proper superset of the second set (is a superset, but is not equal). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2674 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2675 | Instances of :class:`set` are compared to instances of :class:`frozenset` |
| 2676 | based on their members. For example, ``set('abc') == frozenset('abc')`` |
| 2677 | returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2678 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2679 | The subset and equality comparisons do not generalize to a complete ordering |
| 2680 | function. For example, any two disjoint sets are not equal and are not |
| 2681 | subsets of each other, so *all* of the following return ``False``: ``a<b``, |
Georg Brandl | 05f5ab7 | 2008-09-24 09:11:47 +0000 | [diff] [blame] | 2682 | ``a==b``, or ``a>b``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2683 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2684 | Since sets only define partial ordering (subset relationships), the output of |
| 2685 | the :meth:`list.sort` method is undefined for lists of sets. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2686 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2687 | Set elements, like dictionary keys, must be :term:`hashable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2688 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2689 | Binary operations that mix :class:`set` instances with :class:`frozenset` |
| 2690 | return the type of the first operand. For example: ``frozenset('ab') | |
| 2691 | set('bc')`` returns an instance of :class:`frozenset`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2692 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2693 | The following table lists operations available for :class:`set` that do not |
| 2694 | apply to immutable instances of :class:`frozenset`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2695 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 2696 | .. method:: update(other, ...) |
| 2697 | set |= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2698 | |
Georg Brandl | a6053b4 | 2009-09-01 08:11:14 +0000 | [diff] [blame] | 2699 | Update the set, adding elements from all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2700 | |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 2701 | .. method:: intersection_update(other, ...) |
| 2702 | set &= other & ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2703 | |
Georg Brandl | a6053b4 | 2009-09-01 08:11:14 +0000 | [diff] [blame] | 2704 | Update the set, keeping only elements found in it and all others. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2705 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 2706 | .. method:: difference_update(other, ...) |
| 2707 | set -= other | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2708 | |
Amaury Forgeot d'Arc | fdfe62d | 2008-06-17 20:36:03 +0000 | [diff] [blame] | 2709 | Update the set, removing elements found in others. |
| 2710 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2711 | .. method:: symmetric_difference_update(other) |
| 2712 | set ^= other |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2713 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2714 | Update the set, keeping only elements found in either set, but not in both. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2715 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2716 | .. method:: add(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2717 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2718 | Add element *elem* to the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2719 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2720 | .. method:: remove(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2721 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2722 | Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is |
| 2723 | not contained in the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2724 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2725 | .. method:: discard(elem) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2726 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2727 | Remove element *elem* from the set if it is present. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2728 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2729 | .. method:: pop() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2730 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2731 | Remove and return an arbitrary element from the set. Raises |
| 2732 | :exc:`KeyError` if the set is empty. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2733 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2734 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2735 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2736 | Remove all elements from the set. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2737 | |
| 2738 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2739 | Note, the non-operator versions of the :meth:`update`, |
| 2740 | :meth:`intersection_update`, :meth:`difference_update`, and |
| 2741 | :meth:`symmetric_difference_update` methods will accept any iterable as an |
| 2742 | argument. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2743 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2744 | Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and |
| 2745 | :meth:`discard` methods may be a set. To support searching for an equivalent |
| 2746 | frozenset, the *elem* set is temporarily mutated during the search and then |
| 2747 | restored. During the search, the *elem* set should not be read or mutated |
| 2748 | since it does not have a meaningful value. |
Benjamin Peterson | 699adb9 | 2008-05-08 22:27:58 +0000 | [diff] [blame] | 2749 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2750 | |
| 2751 | .. _typesmapping: |
| 2752 | |
| 2753 | Mapping Types --- :class:`dict` |
| 2754 | =============================== |
| 2755 | |
| 2756 | .. index:: |
| 2757 | object: mapping |
| 2758 | object: dictionary |
| 2759 | triple: operations on; mapping; types |
| 2760 | triple: operations on; dictionary; type |
| 2761 | statement: del |
| 2762 | builtin: len |
| 2763 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 2764 | A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects. |
| 2765 | Mappings are mutable objects. There is currently only one standard mapping |
| 2766 | type, the :dfn:`dictionary`. (For other containers see the built in |
| 2767 | :class:`list`, :class:`set`, and :class:`tuple` classes, and the |
| 2768 | :mod:`collections` module.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2769 | |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 2770 | A dictionary's keys are *almost* arbitrary values. Values that are not |
| 2771 | :term:`hashable`, that is, values containing lists, dictionaries or other |
| 2772 | mutable types (that are compared by value rather than by object identity) may |
| 2773 | not be used as keys. Numeric types used for keys obey the normal rules for |
| 2774 | numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) |
| 2775 | then they can be used interchangeably to index the same dictionary entry. (Note |
| 2776 | however, that since computers store floating-point numbers as approximations it |
| 2777 | is usually unwise to use them as dictionary keys.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2778 | |
| 2779 | Dictionaries can be created by placing a comma-separated list of ``key: value`` |
| 2780 | pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: |
| 2781 | 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. |
| 2782 | |
| 2783 | .. class:: dict([arg]) |
| 2784 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2785 | Return a new dictionary initialized from an optional positional argument or |
| 2786 | from a set of keyword arguments. If no arguments are given, return a new |
| 2787 | empty dictionary. If the positional argument *arg* is a mapping object, |
| 2788 | return a dictionary mapping the same keys to the same values as does the |
| 2789 | mapping object. Otherwise the positional argument must be a sequence, a |
| 2790 | container that supports iteration, or an iterator object. The elements of |
| 2791 | the argument must each also be of one of those kinds, and each must in turn |
| 2792 | contain exactly two objects. The first is used as a key in the new |
| 2793 | dictionary, and the second as the key's value. If a given key is seen more |
| 2794 | than once, the last value associated with it is retained in the new |
| 2795 | dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2796 | |
| 2797 | If keyword arguments are given, the keywords themselves with their associated |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2798 | values are added as items to the dictionary. If a key is specified both in |
| 2799 | the positional argument and as a keyword argument, the value associated with |
| 2800 | the keyword is retained in the dictionary. For example, these all return a |
Georg Brandl | c16e8f1 | 2010-10-17 11:23:56 +0000 | [diff] [blame] | 2801 | dictionary equal to ``{"one": 1, "two": 2}``: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2802 | |
Georg Brandl | c16e8f1 | 2010-10-17 11:23:56 +0000 | [diff] [blame] | 2803 | * ``dict(one=1, two=2)`` |
| 2804 | * ``dict({'one': 1, 'two': 2})`` |
| 2805 | * ``dict(zip(('one', 'two'), (1, 2)))`` |
| 2806 | * ``dict([['two', 2], ['one', 1]])`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2807 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2808 | The first example only works for keys that are valid Python identifiers; the |
| 2809 | others work with any valid keys. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2810 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2811 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2812 | These are the operations that dictionaries support (and therefore, custom |
| 2813 | mapping types should support too): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2814 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2815 | .. describe:: len(d) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2816 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2817 | Return the number of items in the dictionary *d*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2818 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2819 | .. describe:: d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2820 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2821 | Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is |
| 2822 | not in the map. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 2823 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2824 | If a subclass of dict defines a method :meth:`__missing__`, if the key *key* |
| 2825 | is not present, the ``d[key]`` operation calls that method with the key *key* |
| 2826 | as argument. The ``d[key]`` operation then returns or raises whatever is |
| 2827 | returned or raised by the ``__missing__(key)`` call if the key is not |
| 2828 | present. No other operations or methods invoke :meth:`__missing__`. If |
| 2829 | :meth:`__missing__` is not defined, :exc:`KeyError` is raised. |
Raymond Hettinger | 5254e97 | 2011-01-08 09:35:38 +0000 | [diff] [blame] | 2830 | :meth:`__missing__` must be a method; it cannot be an instance variable:: |
| 2831 | |
| 2832 | >>> class Counter(dict): |
| 2833 | ... def __missing__(self, key): |
| 2834 | ... return 0 |
| 2835 | >>> c = Counter() |
| 2836 | >>> c['red'] |
| 2837 | 0 |
| 2838 | >>> c['red'] += 1 |
| 2839 | >>> c['red'] |
| 2840 | 1 |
| 2841 | |
| 2842 | See :class:`collections.Counter` for a complete implementation including |
| 2843 | other methods helpful for accumulating and managing tallies. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2844 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2845 | .. describe:: d[key] = value |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2846 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2847 | Set ``d[key]`` to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2848 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2849 | .. describe:: del d[key] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2850 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2851 | Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the |
| 2852 | map. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2853 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2854 | .. describe:: key in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2855 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2856 | Return ``True`` if *d* has a key *key*, else ``False``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2857 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2858 | .. describe:: key not in d |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2859 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2860 | Equivalent to ``not key in d``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2861 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 2862 | .. describe:: iter(d) |
| 2863 | |
| 2864 | Return an iterator over the keys of the dictionary. This is a shortcut |
Georg Brandl | ede6c2a | 2010-01-05 10:22:04 +0000 | [diff] [blame] | 2865 | for ``iter(d.keys())``. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 2866 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2867 | .. method:: clear() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2868 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2869 | Remove all items from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2870 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2871 | .. method:: copy() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2872 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2873 | Return a shallow copy of the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2874 | |
Georg Brandl | abc3877 | 2009-04-12 15:51:51 +0000 | [diff] [blame] | 2875 | .. classmethod:: fromkeys(seq[, value]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2876 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2877 | Create a new dictionary with keys from *seq* and values set to *value*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2878 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2879 | :meth:`fromkeys` is a class method that returns a new dictionary. *value* |
| 2880 | defaults to ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2881 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2882 | .. method:: get(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2883 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2884 | Return the value for *key* if *key* is in the dictionary, else *default*. |
| 2885 | If *default* is not given, it defaults to ``None``, so that this method |
| 2886 | never raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2887 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2888 | .. method:: items() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2889 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 2890 | Return a new view of the dictionary's items (``(key, value)`` pairs). |
| 2891 | See the :ref:`documentation of view objects <dict-views>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2892 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2893 | .. method:: keys() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2894 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 2895 | Return a new view of the dictionary's keys. See the :ref:`documentation |
| 2896 | of view objects <dict-views>`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2897 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2898 | .. method:: pop(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2899 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2900 | If *key* is in the dictionary, remove it and return its value, else return |
| 2901 | *default*. If *default* is not given and *key* is not in the dictionary, |
| 2902 | a :exc:`KeyError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2903 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2904 | .. method:: popitem() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2905 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2906 | Remove and return an arbitrary ``(key, value)`` pair from the dictionary. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2907 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2908 | :meth:`popitem` is useful to destructively iterate over a dictionary, as |
| 2909 | often used in set algorithms. If the dictionary is empty, calling |
| 2910 | :meth:`popitem` raises a :exc:`KeyError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2911 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2912 | .. method:: setdefault(key[, default]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2913 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2914 | If *key* is in the dictionary, return its value. If not, insert *key* |
| 2915 | with a value of *default* and return *default*. *default* defaults to |
| 2916 | ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2917 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2918 | .. method:: update([other]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2919 | |
Éric Araujo | 0fc86b8 | 2010-08-18 22:29:54 +0000 | [diff] [blame] | 2920 | Update the dictionary with the key/value pairs from *other*, overwriting |
| 2921 | existing keys. Return ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2922 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2923 | :meth:`update` accepts either another dictionary object or an iterable of |
Georg Brandl | fda2106 | 2010-09-25 16:56:36 +0000 | [diff] [blame] | 2924 | key/value pairs (as tuples or other iterables of length two). If keyword |
Benjamin Peterson | 8719ad5 | 2009-09-11 22:24:02 +0000 | [diff] [blame] | 2925 | arguments are specified, the dictionary is then updated with those |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2926 | key/value pairs: ``d.update(red=1, blue=2)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2927 | |
Alexandre Vassalotti | a79e33e | 2008-05-15 22:51:26 +0000 | [diff] [blame] | 2928 | .. method:: values() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2929 | |
Victor Stinner | 0db176f | 2012-04-16 00:16:30 +0200 | [diff] [blame] | 2930 | Return a new view of the dictionary's values. See the |
| 2931 | :ref:`documentation of view objects <dict-views>`. |
| 2932 | |
| 2933 | .. seealso:: |
| 2934 | :class:`types.MappingProxyType` can be used to create a read-only view |
| 2935 | of a :class:`dict`. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2936 | |
| 2937 | |
Benjamin Peterson | 44309e6 | 2008-11-22 00:41:45 +0000 | [diff] [blame] | 2938 | .. _dict-views: |
| 2939 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2940 | Dictionary view objects |
| 2941 | ----------------------- |
| 2942 | |
| 2943 | The objects returned by :meth:`dict.keys`, :meth:`dict.values` and |
| 2944 | :meth:`dict.items` are *view objects*. They provide a dynamic view on the |
| 2945 | dictionary's entries, which means that when the dictionary changes, the view |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 2946 | reflects these changes. |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2947 | |
| 2948 | Dictionary views can be iterated over to yield their respective data, and |
| 2949 | support membership tests: |
| 2950 | |
| 2951 | .. describe:: len(dictview) |
| 2952 | |
| 2953 | Return the number of entries in the dictionary. |
| 2954 | |
| 2955 | .. describe:: iter(dictview) |
| 2956 | |
| 2957 | Return an iterator over the keys, values or items (represented as tuples of |
| 2958 | ``(key, value)``) in the dictionary. |
| 2959 | |
| 2960 | Keys and values are iterated over in an arbitrary order which is non-random, |
| 2961 | varies across Python implementations, and depends on the dictionary's history |
| 2962 | of insertions and deletions. If keys, values and items views are iterated |
| 2963 | over with no intervening modifications to the dictionary, the order of items |
| 2964 | will directly correspond. This allows the creation of ``(value, key)`` pairs |
| 2965 | using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to |
| 2966 | create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. |
| 2967 | |
Georg Brandl | 8126914 | 2009-05-17 08:31:29 +0000 | [diff] [blame] | 2968 | Iterating views while adding or deleting entries in the dictionary may raise |
| 2969 | a :exc:`RuntimeError` or fail to iterate over all entries. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 2970 | |
Georg Brandl | d22a815 | 2007-09-04 17:43:37 +0000 | [diff] [blame] | 2971 | .. describe:: x in dictview |
| 2972 | |
| 2973 | Return ``True`` if *x* is in the underlying dictionary's keys, values or |
| 2974 | items (in the latter case, *x* should be a ``(key, value)`` tuple). |
| 2975 | |
| 2976 | |
Benjamin Peterson | ce0506c | 2008-11-17 21:47:41 +0000 | [diff] [blame] | 2977 | Keys views are set-like since their entries are unique and hashable. If all |
Georg Brandl | f74cf77 | 2010-10-15 16:03:02 +0000 | [diff] [blame] | 2978 | values are hashable, so that ``(key, value)`` pairs are unique and hashable, |
| 2979 | then the items view is also set-like. (Values views are not treated as set-like |
| 2980 | since the entries are generally not unique.) For set-like views, all of the |
Nick Coghlan | 273069c | 2012-08-20 17:14:07 +1000 | [diff] [blame^] | 2981 | operations defined for the abstract base class :class:`collections.abc.Set` are |
Georg Brandl | f74cf77 | 2010-10-15 16:03:02 +0000 | [diff] [blame] | 2982 | available (for example, ``==``, ``<``, or ``^``). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2983 | |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 2984 | An example of dictionary view usage:: |
| 2985 | |
| 2986 | >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} |
| 2987 | >>> keys = dishes.keys() |
| 2988 | >>> values = dishes.values() |
| 2989 | |
| 2990 | >>> # iteration |
| 2991 | >>> n = 0 |
| 2992 | >>> for val in values: |
| 2993 | ... n += val |
| 2994 | >>> print(n) |
| 2995 | 504 |
| 2996 | |
| 2997 | >>> # keys and values are iterated over in the same order |
| 2998 | >>> list(keys) |
| 2999 | ['eggs', 'bacon', 'sausage', 'spam'] |
| 3000 | >>> list(values) |
| 3001 | [2, 1, 1, 500] |
| 3002 | |
| 3003 | >>> # view objects are dynamic and reflect dict changes |
| 3004 | >>> del dishes['eggs'] |
| 3005 | >>> del dishes['sausage'] |
| 3006 | >>> list(keys) |
| 3007 | ['spam', 'bacon'] |
| 3008 | |
| 3009 | >>> # set operations |
| 3010 | >>> keys & {'eggs', 'bacon', 'salad'} |
Gregory P. Smith | e838812 | 2008-09-04 04:18:09 +0000 | [diff] [blame] | 3011 | {'bacon'} |
Georg Brandl | f74cf77 | 2010-10-15 16:03:02 +0000 | [diff] [blame] | 3012 | >>> keys ^ {'sausage', 'juice'} |
Sandro Tosi | 2a8d195 | 2011-08-02 18:42:04 +0200 | [diff] [blame] | 3013 | {'juice', 'sausage', 'bacon', 'spam'} |
Georg Brandl | c53c966 | 2007-09-04 17:58:02 +0000 | [diff] [blame] | 3014 | |
| 3015 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3016 | .. _typecontextmanager: |
| 3017 | |
| 3018 | Context Manager Types |
| 3019 | ===================== |
| 3020 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3021 | .. index:: |
| 3022 | single: context manager |
| 3023 | single: context management protocol |
| 3024 | single: protocol; context management |
| 3025 | |
| 3026 | Python's :keyword:`with` statement supports the concept of a runtime context |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 3027 | defined by a context manager. This is implemented using a pair of methods |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3028 | that allow user-defined classes to define a runtime context that is entered |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 3029 | before the statement body is executed and exited when the statement ends: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3030 | |
| 3031 | |
| 3032 | .. method:: contextmanager.__enter__() |
| 3033 | |
| 3034 | Enter the runtime context and return either this object or another object |
| 3035 | related to the runtime context. The value returned by this method is bound to |
| 3036 | the identifier in the :keyword:`as` clause of :keyword:`with` statements using |
| 3037 | this context manager. |
| 3038 | |
Antoine Pitrou | 11cb961 | 2010-09-15 11:11:28 +0000 | [diff] [blame] | 3039 | An example of a context manager that returns itself is a :term:`file object`. |
| 3040 | File objects return themselves from __enter__() to allow :func:`open` to be |
| 3041 | used as the context expression in a :keyword:`with` statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3042 | |
| 3043 | An example of a context manager that returns a related object is the one |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 3044 | returned by :func:`decimal.localcontext`. These managers set the active |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3045 | decimal context to a copy of the original decimal context and then return the |
| 3046 | copy. This allows changes to be made to the current decimal context in the body |
| 3047 | of the :keyword:`with` statement without affecting code outside the |
| 3048 | :keyword:`with` statement. |
| 3049 | |
| 3050 | |
| 3051 | .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) |
| 3052 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 3053 | Exit the runtime context and return a Boolean flag indicating if any exception |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3054 | that occurred should be suppressed. If an exception occurred while executing the |
| 3055 | body of the :keyword:`with` statement, the arguments contain the exception type, |
| 3056 | value and traceback information. Otherwise, all three arguments are ``None``. |
| 3057 | |
| 3058 | Returning a true value from this method will cause the :keyword:`with` statement |
| 3059 | to suppress the exception and continue execution with the statement immediately |
| 3060 | following the :keyword:`with` statement. Otherwise the exception continues |
| 3061 | propagating after this method has finished executing. Exceptions that occur |
| 3062 | during execution of this method will replace any exception that occurred in the |
| 3063 | body of the :keyword:`with` statement. |
| 3064 | |
| 3065 | The exception passed in should never be reraised explicitly - instead, this |
| 3066 | method should return a false value to indicate that the method completed |
| 3067 | successfully and does not want to suppress the raised exception. This allows |
| 3068 | context management code (such as ``contextlib.nested``) to easily detect whether |
| 3069 | or not an :meth:`__exit__` method has actually failed. |
| 3070 | |
| 3071 | Python defines several context managers to support easy thread synchronisation, |
| 3072 | prompt closure of files or other objects, and simpler manipulation of the active |
| 3073 | decimal arithmetic context. The specific types are not treated specially beyond |
| 3074 | their implementation of the context management protocol. See the |
| 3075 | :mod:`contextlib` module for some examples. |
| 3076 | |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 3077 | Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 3078 | provide a convenient way to implement these protocols. If a generator function is |
Antoine Pitrou | a654090 | 2010-12-12 20:09:18 +0000 | [diff] [blame] | 3079 | decorated with the :class:`contextlib.contextmanager` decorator, it will return a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3080 | context manager implementing the necessary :meth:`__enter__` and |
| 3081 | :meth:`__exit__` methods, rather than the iterator produced by an undecorated |
| 3082 | generator function. |
| 3083 | |
| 3084 | Note that there is no specific slot for any of these methods in the type |
| 3085 | structure for Python objects in the Python/C API. Extension types wanting to |
| 3086 | define these methods must provide them as a normal Python accessible method. |
| 3087 | Compared to the overhead of setting up the runtime context, the overhead of a |
| 3088 | single class dictionary lookup is negligible. |
| 3089 | |
| 3090 | |
| 3091 | .. _typesother: |
| 3092 | |
| 3093 | Other Built-in Types |
| 3094 | ==================== |
| 3095 | |
| 3096 | The interpreter supports several other kinds of objects. Most of these support |
| 3097 | only one or two operations. |
| 3098 | |
| 3099 | |
| 3100 | .. _typesmodules: |
| 3101 | |
| 3102 | Modules |
| 3103 | ------- |
| 3104 | |
| 3105 | The only special operation on a module is attribute access: ``m.name``, where |
| 3106 | *m* is a module and *name* accesses a name defined in *m*'s symbol table. |
| 3107 | Module attributes can be assigned to. (Note that the :keyword:`import` |
| 3108 | statement is not, strictly speaking, an operation on a module object; ``import |
| 3109 | foo`` does not require a module object named *foo* to exist, rather it requires |
| 3110 | an (external) *definition* for a module named *foo* somewhere.) |
| 3111 | |
Senthil Kumaran | a6bac95 | 2011-07-04 11:28:30 -0700 | [diff] [blame] | 3112 | A special attribute of every module is :attr:`__dict__`. This is the dictionary |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3113 | containing the module's symbol table. Modifying this dictionary will actually |
| 3114 | change the module's symbol table, but direct assignment to the :attr:`__dict__` |
| 3115 | attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines |
| 3116 | ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying |
| 3117 | :attr:`__dict__` directly is not recommended. |
| 3118 | |
| 3119 | Modules built into the interpreter are written like this: ``<module 'sys' |
| 3120 | (built-in)>``. If loaded from a file, they are written as ``<module 'os' from |
| 3121 | '/usr/local/lib/pythonX.Y/os.pyc'>``. |
| 3122 | |
| 3123 | |
| 3124 | .. _typesobjects: |
| 3125 | |
| 3126 | Classes and Class Instances |
| 3127 | --------------------------- |
| 3128 | |
| 3129 | See :ref:`objects` and :ref:`class` for these. |
| 3130 | |
| 3131 | |
| 3132 | .. _typesfunctions: |
| 3133 | |
| 3134 | Functions |
| 3135 | --------- |
| 3136 | |
| 3137 | Function objects are created by function definitions. The only operation on a |
| 3138 | function object is to call it: ``func(argument-list)``. |
| 3139 | |
| 3140 | There are really two flavors of function objects: built-in functions and |
| 3141 | user-defined functions. Both support the same operation (to call the function), |
| 3142 | but the implementation is different, hence the different object types. |
| 3143 | |
| 3144 | See :ref:`function` for more information. |
| 3145 | |
| 3146 | |
| 3147 | .. _typesmethods: |
| 3148 | |
| 3149 | Methods |
| 3150 | ------- |
| 3151 | |
| 3152 | .. index:: object: method |
| 3153 | |
| 3154 | Methods are functions that are called using the attribute notation. There are |
| 3155 | two flavors: built-in methods (such as :meth:`append` on lists) and class |
| 3156 | instance methods. Built-in methods are described with the types that support |
| 3157 | them. |
| 3158 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 3159 | If you access a method (a function defined in a class namespace) through an |
| 3160 | instance, you get a special object: a :dfn:`bound method` (also called |
| 3161 | :dfn:`instance method`) object. When called, it will add the ``self`` argument |
| 3162 | to the argument list. Bound methods have two special read-only attributes: |
| 3163 | ``m.__self__`` is the object on which the method operates, and ``m.__func__`` is |
| 3164 | the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` |
| 3165 | is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., |
| 3166 | arg-n)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3167 | |
Georg Brandl | 2e0b755 | 2007-11-27 12:43:08 +0000 | [diff] [blame] | 3168 | Like function objects, bound method objects support getting arbitrary |
| 3169 | attributes. However, since method attributes are actually stored on the |
| 3170 | underlying function object (``meth.__func__``), setting method attributes on |
| 3171 | bound methods is disallowed. Attempting to set a method attribute results in a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3172 | :exc:`TypeError` being raised. In order to set a method attribute, you need to |
| 3173 | explicitly set it on the underlying function object:: |
| 3174 | |
| 3175 | class C: |
| 3176 | def method(self): |
| 3177 | pass |
| 3178 | |
| 3179 | c = C() |
Christian Heimes | ff73795 | 2007-11-27 10:40:20 +0000 | [diff] [blame] | 3180 | c.method.__func__.whoami = 'my name is c' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3181 | |
| 3182 | See :ref:`types` for more information. |
| 3183 | |
| 3184 | |
| 3185 | .. _bltin-code-objects: |
| 3186 | |
| 3187 | Code Objects |
| 3188 | ------------ |
| 3189 | |
| 3190 | .. index:: object: code |
| 3191 | |
| 3192 | .. index:: |
| 3193 | builtin: compile |
| 3194 | single: __code__ (function object attribute) |
| 3195 | |
| 3196 | Code objects are used by the implementation to represent "pseudo-compiled" |
| 3197 | executable Python code such as a function body. They differ from function |
| 3198 | objects because they don't contain a reference to their global execution |
| 3199 | environment. Code objects are returned by the built-in :func:`compile` function |
| 3200 | and can be extracted from function objects through their :attr:`__code__` |
| 3201 | attribute. See also the :mod:`code` module. |
| 3202 | |
| 3203 | .. index:: |
| 3204 | builtin: exec |
| 3205 | builtin: eval |
| 3206 | |
| 3207 | A code object can be executed or evaluated by passing it (instead of a source |
| 3208 | string) to the :func:`exec` or :func:`eval` built-in functions. |
| 3209 | |
| 3210 | See :ref:`types` for more information. |
| 3211 | |
| 3212 | |
| 3213 | .. _bltin-type-objects: |
| 3214 | |
| 3215 | Type Objects |
| 3216 | ------------ |
| 3217 | |
| 3218 | .. index:: |
| 3219 | builtin: type |
| 3220 | module: types |
| 3221 | |
| 3222 | Type objects represent the various object types. An object's type is accessed |
| 3223 | by the built-in function :func:`type`. There are no special operations on |
| 3224 | types. The standard module :mod:`types` defines names for all standard built-in |
| 3225 | types. |
| 3226 | |
Martin v. Löwis | 250ad61 | 2008-04-07 05:43:42 +0000 | [diff] [blame] | 3227 | Types are written like this: ``<class 'int'>``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3228 | |
| 3229 | |
| 3230 | .. _bltin-null-object: |
| 3231 | |
| 3232 | The Null Object |
| 3233 | --------------- |
| 3234 | |
| 3235 | This object is returned by functions that don't explicitly return a value. It |
| 3236 | supports no special operations. There is exactly one null object, named |
Benjamin Peterson | 98f2b9b | 2011-07-30 12:26:27 -0500 | [diff] [blame] | 3237 | ``None`` (a built-in name). ``type(None)()`` produces the same singleton. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3238 | |
| 3239 | It is written as ``None``. |
| 3240 | |
| 3241 | |
| 3242 | .. _bltin-ellipsis-object: |
| 3243 | |
| 3244 | The Ellipsis Object |
| 3245 | ------------------- |
| 3246 | |
Benjamin Peterson | d5a1c44 | 2012-05-14 22:09:31 -0700 | [diff] [blame] | 3247 | This object is commonly used by slicing (see :ref:`slicings`). It supports no |
| 3248 | special operations. There is exactly one ellipsis object, named |
| 3249 | :const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the |
| 3250 | :const:`Ellipsis` singleton. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3251 | |
| 3252 | It is written as ``Ellipsis`` or ``...``. |
| 3253 | |
| 3254 | |
Éric Araujo | 18ddf82 | 2011-09-01 23:10:36 +0200 | [diff] [blame] | 3255 | .. _bltin-notimplemented-object: |
| 3256 | |
Benjamin Peterson | 50211fa | 2011-07-30 09:57:24 -0500 | [diff] [blame] | 3257 | The NotImplemented Object |
| 3258 | ------------------------- |
| 3259 | |
| 3260 | This object is returned from comparisons and binary operations when they are |
| 3261 | asked to operate on types they don't support. See :ref:`comparisons` for more |
Benjamin Peterson | 98f2b9b | 2011-07-30 12:26:27 -0500 | [diff] [blame] | 3262 | information. There is exactly one ``NotImplemented`` object. |
| 3263 | ``type(NotImplemented)()`` produces the singleton instance. |
Benjamin Peterson | 50211fa | 2011-07-30 09:57:24 -0500 | [diff] [blame] | 3264 | |
| 3265 | It is written as ``NotImplemented``. |
| 3266 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3267 | |
Éric Araujo | 18ddf82 | 2011-09-01 23:10:36 +0200 | [diff] [blame] | 3268 | .. _bltin-boolean-values: |
| 3269 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3270 | Boolean Values |
| 3271 | -------------- |
| 3272 | |
| 3273 | Boolean values are the two constant objects ``False`` and ``True``. They are |
| 3274 | used to represent truth values (although other values can also be considered |
| 3275 | false or true). In numeric contexts (for example when used as the argument to |
| 3276 | an arithmetic operator), they behave like the integers 0 and 1, respectively. |
Ezio Melotti | c1f26f6 | 2011-12-02 19:47:24 +0200 | [diff] [blame] | 3277 | The built-in function :func:`bool` can be used to convert any value to a |
| 3278 | Boolean, if the value can be interpreted as a truth value (see section |
| 3279 | :ref:`truth` above). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3280 | |
| 3281 | .. index:: |
| 3282 | single: False |
| 3283 | single: True |
| 3284 | pair: Boolean; values |
| 3285 | |
| 3286 | They are written as ``False`` and ``True``, respectively. |
| 3287 | |
| 3288 | |
| 3289 | .. _typesinternal: |
| 3290 | |
| 3291 | Internal Objects |
| 3292 | ---------------- |
| 3293 | |
| 3294 | See :ref:`types` for this information. It describes stack frame objects, |
| 3295 | traceback objects, and slice objects. |
| 3296 | |
| 3297 | |
| 3298 | .. _specialattrs: |
| 3299 | |
| 3300 | Special Attributes |
| 3301 | ================== |
| 3302 | |
| 3303 | The implementation adds a few special read-only attributes to several object |
| 3304 | types, where they are relevant. Some of these are not reported by the |
| 3305 | :func:`dir` built-in function. |
| 3306 | |
| 3307 | |
| 3308 | .. attribute:: object.__dict__ |
| 3309 | |
| 3310 | A dictionary or other mapping object used to store an object's (writable) |
| 3311 | attributes. |
| 3312 | |
| 3313 | |
| 3314 | .. attribute:: instance.__class__ |
| 3315 | |
| 3316 | The class to which a class instance belongs. |
| 3317 | |
| 3318 | |
| 3319 | .. attribute:: class.__bases__ |
| 3320 | |
Benjamin Peterson | 1baf465 | 2009-12-31 03:11:23 +0000 | [diff] [blame] | 3321 | The tuple of base classes of a class object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3322 | |
| 3323 | |
| 3324 | .. attribute:: class.__name__ |
| 3325 | |
| 3326 | The name of the class or type. |
| 3327 | |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 3328 | |
Antoine Pitrou | 86a36b5 | 2011-11-25 18:56:07 +0100 | [diff] [blame] | 3329 | .. attribute:: class.__qualname__ |
| 3330 | |
| 3331 | The :term:`qualified name` of the class or type. |
| 3332 | |
| 3333 | .. versionadded:: 3.3 |
| 3334 | |
| 3335 | |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 3336 | .. attribute:: class.__mro__ |
| 3337 | |
| 3338 | This attribute is a tuple of classes that are considered when looking for |
| 3339 | base classes during method resolution. |
| 3340 | |
| 3341 | |
| 3342 | .. method:: class.mro() |
| 3343 | |
| 3344 | This method can be overridden by a metaclass to customize the method |
| 3345 | resolution order for its instances. It is called at class instantiation, and |
| 3346 | its result is stored in :attr:`__mro__`. |
| 3347 | |
| 3348 | |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 3349 | .. method:: class.__subclasses__ |
| 3350 | |
Florent Xicluna | 74e6495 | 2011-10-28 11:21:19 +0200 | [diff] [blame] | 3351 | Each class keeps a list of weak references to its immediate subclasses. This |
| 3352 | method returns a list of all those references still alive. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 3353 | Example:: |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 3354 | |
| 3355 | >>> int.__subclasses__() |
Florent Xicluna | 74e6495 | 2011-10-28 11:21:19 +0200 | [diff] [blame] | 3356 | [<class 'bool'>] |
Georg Brandl | 7a51e58 | 2009-03-28 19:13:21 +0000 | [diff] [blame] | 3357 | |
| 3358 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3359 | .. rubric:: Footnotes |
| 3360 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 3361 | .. [1] Additional information on these special methods may be found in the Python |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3362 | Reference Manual (:ref:`customization`). |
| 3363 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 3364 | .. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3365 | similarly for tuples. |
| 3366 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 3367 | .. [3] They must have since the parser can't tell the type of the operands. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3368 | |
Ezio Melotti | 0656a56 | 2011-08-15 14:27:19 +0300 | [diff] [blame] | 3369 | .. [4] Cased characters are those with general category property being one of |
| 3370 | "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase). |
| 3371 | |
| 3372 | .. [5] To format only a tuple you should therefore provide a singleton tuple whose only |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 3373 | element is the tuple to be formatted. |