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