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