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