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