1.. XXX: reference/datamodel and this have quite a few overlaps! 2 3 4.. _bltin-types: 5 6************** 7Built-in Types 8************** 9 10The following sections describe the standard types that are built into the 11interpreter. 12 13.. index:: pair: built-in; types 14 15The principal built-in types are numerics, sequences, mappings, classes, 16instances and exceptions. 17 18Some collection classes are mutable. The methods that add, subtract, or 19rearrange their members in place, and don't return a specific item, never return 20the collection instance itself but ``None``. 21 22Some operations are supported by several object types; in particular, 23practically all objects can be compared for equality, tested for truth 24value, and converted to a string (with the :func:`repr` function or the 25slightly different :func:`str` function). The latter function is implicitly 26used when an object is written by the :func:`print` function. 27 28 29.. _truth: 30 31Truth Value Testing 32=================== 33 34.. index:: 35 statement: if 36 statement: while 37 pair: truth; value 38 pair: Boolean; operations 39 single: false 40 41Any object can be tested for truth value, for use in an :keyword:`if` or 42:keyword:`while` condition or as operand of the Boolean operations below. 43 44.. index:: single: true 45 46By default, an object is considered true unless its class defines either a 47:meth:`__bool__` method that returns ``False`` or a :meth:`__len__` method that 48returns zero, when called with the object. [1]_ Here are most of the built-in 49objects considered false: 50 51 .. index:: 52 single: None (Built-in object) 53 single: False (Built-in object) 54 55* constants defined to be false: ``None`` and ``False``. 56 57* zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, 58 ``Fraction(0, 1)`` 59 60* empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``, 61 ``range(0)`` 62 63.. index:: 64 operator: or 65 operator: and 66 single: False 67 single: True 68 69Operations and built-in functions that have a Boolean result always return ``0`` 70or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated. 71(Important exception: the Boolean operations ``or`` and ``and`` always return 72one of their operands.) 73 74 75.. _boolean: 76 77Boolean Operations --- :keyword:`!and`, :keyword:`!or`, :keyword:`!not` 78======================================================================= 79 80.. index:: pair: Boolean; operations 81 82These are the Boolean operations, ordered by ascending priority: 83 84+-------------+---------------------------------+-------+ 85| Operation | Result | Notes | 86+=============+=================================+=======+ 87| ``x or y`` | if *x* is false, then *y*, else | \(1) | 88| | *x* | | 89+-------------+---------------------------------+-------+ 90| ``x and y`` | if *x* is false, then *x*, else | \(2) | 91| | *y* | | 92+-------------+---------------------------------+-------+ 93| ``not x`` | if *x* is false, then ``True``, | \(3) | 94| | else ``False`` | | 95+-------------+---------------------------------+-------+ 96 97.. index:: 98 operator: and 99 operator: or 100 operator: not 101 102Notes: 103 104(1) 105 This is a short-circuit operator, so it only evaluates the second 106 argument if the first one is false. 107 108(2) 109 This is a short-circuit operator, so it only evaluates the second 110 argument if the first one is true. 111 112(3) 113 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is 114 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error. 115 116 117.. _stdcomparisons: 118 119Comparisons 120=========== 121 122.. index:: 123 pair: chaining; comparisons 124 pair: operator; comparison 125 operator: == 126 operator: < (less) 127 operator: <= 128 operator: > (greater) 129 operator: >= 130 operator: != 131 operator: is 132 operator: is not 133 134There are eight comparison operations in Python. They all have the same 135priority (which is higher than that of the Boolean operations). Comparisons can 136be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and 137y <= z``, except that *y* is evaluated only once (but in both cases *z* is not 138evaluated at all when ``x < y`` is found to be false). 139 140This table summarizes the comparison operations: 141 142+------------+-------------------------+ 143| Operation | Meaning | 144+============+=========================+ 145| ``<`` | strictly less than | 146+------------+-------------------------+ 147| ``<=`` | less than or equal | 148+------------+-------------------------+ 149| ``>`` | strictly greater than | 150+------------+-------------------------+ 151| ``>=`` | greater than or equal | 152+------------+-------------------------+ 153| ``==`` | equal | 154+------------+-------------------------+ 155| ``!=`` | not equal | 156+------------+-------------------------+ 157| ``is`` | object identity | 158+------------+-------------------------+ 159| ``is not`` | negated object identity | 160+------------+-------------------------+ 161 162.. index:: 163 pair: object; numeric 164 pair: objects; comparing 165 166Objects of different types, except different numeric types, never compare equal. 167The ``==`` operator is always defined but for some object types (for example, 168class objects) is equivalent to :keyword:`is`. The ``<``, ``<=``, ``>`` and ``>=`` 169operators are only defined where they make sense; for example, they raise a 170:exc:`TypeError` exception when one of the arguments is a complex number. 171 172.. index:: 173 single: __eq__() (instance method) 174 single: __ne__() (instance method) 175 single: __lt__() (instance method) 176 single: __le__() (instance method) 177 single: __gt__() (instance method) 178 single: __ge__() (instance method) 179 180Non-identical instances of a class normally compare as non-equal unless the 181class defines the :meth:`~object.__eq__` method. 182 183Instances of a class cannot be ordered with respect to other instances of the 184same class, or other types of object, unless the class defines enough of the 185methods :meth:`~object.__lt__`, :meth:`~object.__le__`, :meth:`~object.__gt__`, and 186:meth:`~object.__ge__` (in general, :meth:`~object.__lt__` and 187:meth:`~object.__eq__` are sufficient, if you want the conventional meanings of the 188comparison operators). 189 190The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be 191customized; also they can be applied to any two objects and never raise an 192exception. 193 194.. index:: 195 operator: in 196 operator: not in 197 198Two more operations with the same syntactic priority, :keyword:`in` and 199:keyword:`not in`, are supported by types that are :term:`iterable` or 200implement the :meth:`__contains__` method. 201 202.. _typesnumeric: 203 204Numeric Types --- :class:`int`, :class:`float`, :class:`complex` 205================================================================ 206 207.. index:: 208 object: numeric 209 object: Boolean 210 object: integer 211 object: floating point 212 object: complex number 213 pair: C; language 214 215There are three distinct numeric types: :dfn:`integers`, :dfn:`floating 216point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a 217subtype of integers. Integers have unlimited precision. Floating point 218numbers are usually implemented using :c:type:`double` in C; information 219about the precision and internal representation of floating point 220numbers for the machine on which your program is running is available 221in :data:`sys.float_info`. Complex numbers have a real and imaginary 222part, which are each a floating point number. To extract these parts 223from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard 224library includes the additional numeric types :mod:`fractions.Fraction`, for 225rationals, and :mod:`decimal.Decimal`, for floating-point numbers with 226user-definable precision.) 227 228.. index:: 229 pair: numeric; literals 230 pair: integer; literals 231 pair: floating point; literals 232 pair: complex number; literals 233 pair: hexadecimal; literals 234 pair: octal; literals 235 pair: binary; literals 236 237Numbers are created by numeric literals or as the result of built-in functions 238and operators. Unadorned integer literals (including hex, octal and binary 239numbers) yield integers. Numeric literals containing a decimal point or an 240exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a 241numeric literal yields an imaginary number (a complex number with a zero real 242part) which you can add to an integer or float to get a complex number with real 243and imaginary parts. 244 245.. index:: 246 single: arithmetic 247 builtin: int 248 builtin: float 249 builtin: complex 250 single: operator; + (plus) 251 single: + (plus); unary operator 252 single: + (plus); binary operator 253 single: operator; - (minus) 254 single: - (minus); unary operator 255 single: - (minus); binary operator 256 operator: * (asterisk) 257 operator: / (slash) 258 operator: // 259 operator: % (percent) 260 operator: ** 261 262Python fully supports mixed arithmetic: when a binary arithmetic operator has 263operands of different numeric types, the operand with the "narrower" type is 264widened to that of the other, where integer is narrower than floating point, 265which is narrower than complex. A comparison between numbers of different types 266behaves as though the exact values of those numbers were being compared. [2]_ 267 268The constructors :func:`int`, :func:`float`, and 269:func:`complex` can be used to produce numbers of a specific type. 270 271All numeric types (except complex) support the following operations (for priorities of 272the operations, see :ref:`operator-summary`): 273 274+---------------------+---------------------------------+---------+--------------------+ 275| Operation | Result | Notes | Full documentation | 276+=====================+=================================+=========+====================+ 277| ``x + y`` | sum of *x* and *y* | | | 278+---------------------+---------------------------------+---------+--------------------+ 279| ``x - y`` | difference of *x* and *y* | | | 280+---------------------+---------------------------------+---------+--------------------+ 281| ``x * y`` | product of *x* and *y* | | | 282+---------------------+---------------------------------+---------+--------------------+ 283| ``x / y`` | quotient of *x* and *y* | | | 284+---------------------+---------------------------------+---------+--------------------+ 285| ``x // y`` | floored quotient of *x* and | \(1) | | 286| | *y* | | | 287+---------------------+---------------------------------+---------+--------------------+ 288| ``x % y`` | remainder of ``x / y`` | \(2) | | 289+---------------------+---------------------------------+---------+--------------------+ 290| ``-x`` | *x* negated | | | 291+---------------------+---------------------------------+---------+--------------------+ 292| ``+x`` | *x* unchanged | | | 293+---------------------+---------------------------------+---------+--------------------+ 294| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | 295| | *x* | | | 296+---------------------+---------------------------------+---------+--------------------+ 297| ``int(x)`` | *x* converted to integer | \(3)\(6)| :func:`int` | 298+---------------------+---------------------------------+---------+--------------------+ 299| ``float(x)`` | *x* converted to floating point | \(4)\(6)| :func:`float` | 300+---------------------+---------------------------------+---------+--------------------+ 301| ``complex(re, im)`` | a complex number with real part | \(6) | :func:`complex` | 302| | *re*, imaginary part *im*. | | | 303| | *im* defaults to zero. | | | 304+---------------------+---------------------------------+---------+--------------------+ 305| ``c.conjugate()`` | conjugate of the complex number | | | 306| | *c* | | | 307+---------------------+---------------------------------+---------+--------------------+ 308| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | 309+---------------------+---------------------------------+---------+--------------------+ 310| ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` | 311+---------------------+---------------------------------+---------+--------------------+ 312| ``x ** y`` | *x* to the power *y* | \(5) | | 313+---------------------+---------------------------------+---------+--------------------+ 314 315.. index:: 316 triple: operations on; numeric; types 317 single: conjugate() (complex number method) 318 319Notes: 320 321(1) 322 Also referred to as integer division. The resultant value is a whole 323 integer, though the result's type is not necessarily int. The result is 324 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is 325 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. 326 327(2) 328 Not for complex numbers. Instead convert to floats using :func:`abs` if 329 appropriate. 330 331(3) 332 .. index:: 333 module: math 334 single: floor() (in module math) 335 single: ceil() (in module math) 336 single: trunc() (in module math) 337 pair: numeric; conversions 338 pair: C; language 339 340 Conversion from floating point to integer may round or truncate 341 as in C; see functions :func:`math.floor` and :func:`math.ceil` for 342 well-defined conversions. 343 344(4) 345 float also accepts the strings "nan" and "inf" with an optional prefix "+" 346 or "-" for Not a Number (NaN) and positive or negative infinity. 347 348(5) 349 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for 350 programming languages. 351 352(6) 353 The numeric literals accepted include the digits ``0`` to ``9`` or any 354 Unicode equivalent (code points with the ``Nd`` property). 355 356 See https://www.unicode.org/Public/13.0.0/ucd/extracted/DerivedNumericType.txt 357 for a complete list of code points with the ``Nd`` property. 358 359 360All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include 361the following operations: 362 363+--------------------+---------------------------------------------+ 364| Operation | Result | 365+====================+=============================================+ 366| :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` | 367| x) <math.trunc>` | | 368+--------------------+---------------------------------------------+ 369| :func:`round(x[, | *x* rounded to *n* digits, | 370| n]) <round>` | rounding half to even. If *n* is | 371| | omitted, it defaults to 0. | 372+--------------------+---------------------------------------------+ 373| :func:`math.floor(\| the greatest :class:`~numbers.Integral` | 374| x) <math.floor>` | <= *x* | 375+--------------------+---------------------------------------------+ 376| :func:`math.ceil(x)| the least :class:`~numbers.Integral` >= *x* | 377| <math.ceil>` | | 378+--------------------+---------------------------------------------+ 379 380For additional numeric operations see the :mod:`math` and :mod:`cmath` 381modules. 382 383.. XXXJH exceptions: overflow (when? what operations?) zerodivision 384 385 386.. _bitstring-ops: 387 388Bitwise Operations on Integer Types 389----------------------------------- 390 391.. index:: 392 triple: operations on; integer; types 393 pair: bitwise; operations 394 pair: shifting; operations 395 pair: masking; operations 396 operator: | (vertical bar) 397 operator: ^ (caret) 398 operator: & (ampersand) 399 operator: << 400 operator: >> 401 operator: ~ (tilde) 402 403Bitwise operations only make sense for integers. The result of bitwise 404operations is calculated as though carried out in two's complement with an 405infinite number of sign bits. 406 407The priorities of the binary bitwise operations are all lower than the numeric 408operations and higher than the comparisons; the unary operation ``~`` has the 409same priority as the other unary numeric operations (``+`` and ``-``). 410 411This table lists the bitwise operations sorted in ascending priority: 412 413+------------+--------------------------------+----------+ 414| Operation | Result | Notes | 415+============+================================+==========+ 416| ``x | y`` | bitwise :dfn:`or` of *x* and | \(4) | 417| | *y* | | 418+------------+--------------------------------+----------+ 419| ``x ^ y`` | bitwise :dfn:`exclusive or` of | \(4) | 420| | *x* and *y* | | 421+------------+--------------------------------+----------+ 422| ``x & y`` | bitwise :dfn:`and` of *x* and | \(4) | 423| | *y* | | 424+------------+--------------------------------+----------+ 425| ``x << n`` | *x* shifted left by *n* bits | (1)(2) | 426+------------+--------------------------------+----------+ 427| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) | 428+------------+--------------------------------+----------+ 429| ``~x`` | the bits of *x* inverted | | 430+------------+--------------------------------+----------+ 431 432Notes: 433 434(1) 435 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised. 436 437(2) 438 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``. 439 440(3) 441 A right shift by *n* bits is equivalent to floor division by ``pow(2, n)``. 442 443(4) 444 Performing these calculations with at least one extra sign extension bit in 445 a finite two's complement representation (a working bit-width of 446 ``1 + max(x.bit_length(), y.bit_length())`` or more) is sufficient to get the 447 same result as if there were an infinite number of sign bits. 448 449 450Additional Methods on Integer Types 451----------------------------------- 452 453The int type implements the :class:`numbers.Integral` :term:`abstract base 454class`. In addition, it provides a few more methods: 455 456.. method:: int.bit_length() 457 458 Return the number of bits necessary to represent an integer in binary, 459 excluding the sign and leading zeros:: 460 461 >>> n = -37 462 >>> bin(n) 463 '-0b100101' 464 >>> n.bit_length() 465 6 466 467 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the 468 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``. 469 Equivalently, when ``abs(x)`` is small enough to have a correctly 470 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``. 471 If ``x`` is zero, then ``x.bit_length()`` returns ``0``. 472 473 Equivalent to:: 474 475 def bit_length(self): 476 s = bin(self) # binary representation: bin(-37) --> '-0b100101' 477 s = s.lstrip('-0b') # remove leading zeros and minus sign 478 return len(s) # len('100101') --> 6 479 480 .. versionadded:: 3.1 481 482.. method:: int.bit_count() 483 484 Return the number of ones in the binary representation of the absolute 485 value of the integer. This is also known as the population count. 486 Example:: 487 488 >>> n = 19 489 >>> bin(n) 490 '0b10011' 491 >>> n.bit_count() 492 3 493 >>> (-n).bit_count() 494 3 495 496 Equivalent to:: 497 498 def bit_count(self): 499 return bin(self).count("1") 500 501 .. versionadded:: 3.10 502 503.. method:: int.to_bytes(length, byteorder, *, signed=False) 504 505 Return an array of bytes representing an integer. 506 507 >>> (1024).to_bytes(2, byteorder='big') 508 b'\x04\x00' 509 >>> (1024).to_bytes(10, byteorder='big') 510 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' 511 >>> (-1024).to_bytes(10, byteorder='big', signed=True) 512 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' 513 >>> x = 1000 514 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') 515 b'\xe8\x03' 516 517 The integer is represented using *length* bytes. An :exc:`OverflowError` 518 is raised if the integer is not representable with the given number of 519 bytes. 520 521 The *byteorder* argument determines the byte order used to represent the 522 integer. If *byteorder* is ``"big"``, the most significant byte is at the 523 beginning of the byte array. If *byteorder* is ``"little"``, the most 524 significant byte is at the end of the byte array. To request the native 525 byte order of the host system, use :data:`sys.byteorder` as the byte order 526 value. 527 528 The *signed* argument determines whether two's complement is used to 529 represent the integer. If *signed* is ``False`` and a negative integer is 530 given, an :exc:`OverflowError` is raised. The default value for *signed* 531 is ``False``. 532 533 .. versionadded:: 3.2 534 535.. classmethod:: int.from_bytes(bytes, byteorder, *, signed=False) 536 537 Return the integer represented by the given array of bytes. 538 539 >>> int.from_bytes(b'\x00\x10', byteorder='big') 540 16 541 >>> int.from_bytes(b'\x00\x10', byteorder='little') 542 4096 543 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) 544 -1024 545 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 546 64512 547 >>> int.from_bytes([255, 0, 0], byteorder='big') 548 16711680 549 550 The argument *bytes* must either be a :term:`bytes-like object` or an 551 iterable producing bytes. 552 553 The *byteorder* argument determines the byte order used to represent the 554 integer. If *byteorder* is ``"big"``, the most significant byte is at the 555 beginning of the byte array. If *byteorder* is ``"little"``, the most 556 significant byte is at the end of the byte array. To request the native 557 byte order of the host system, use :data:`sys.byteorder` as the byte order 558 value. 559 560 The *signed* argument indicates whether two's complement is used to 561 represent the integer. 562 563 .. versionadded:: 3.2 564 565.. method:: int.as_integer_ratio() 566 567 Return a pair of integers whose ratio is exactly equal to the original 568 integer and with a positive denominator. The integer ratio of integers 569 (whole numbers) is always the integer as the numerator and ``1`` as the 570 denominator. 571 572 .. versionadded:: 3.8 573 574Additional Methods on Float 575--------------------------- 576 577The float type implements the :class:`numbers.Real` :term:`abstract base 578class`. float also has the following additional methods. 579 580.. method:: float.as_integer_ratio() 581 582 Return a pair of integers whose ratio is exactly equal to the 583 original float and with a positive denominator. Raises 584 :exc:`OverflowError` on infinities and a :exc:`ValueError` on 585 NaNs. 586 587.. method:: float.is_integer() 588 589 Return ``True`` if the float instance is finite with integral 590 value, and ``False`` otherwise:: 591 592 >>> (-2.0).is_integer() 593 True 594 >>> (3.2).is_integer() 595 False 596 597Two methods support conversion to 598and from hexadecimal strings. Since Python's floats are stored 599internally as binary numbers, converting a float to or from a 600*decimal* string usually involves a small rounding error. In 601contrast, hexadecimal strings allow exact representation and 602specification of floating-point numbers. This can be useful when 603debugging, and in numerical work. 604 605 606.. method:: float.hex() 607 608 Return a representation of a floating-point number as a hexadecimal 609 string. For finite floating-point numbers, this representation 610 will always include a leading ``0x`` and a trailing ``p`` and 611 exponent. 612 613 614.. classmethod:: float.fromhex(s) 615 616 Class method to return the float represented by a hexadecimal 617 string *s*. The string *s* may have leading and trailing 618 whitespace. 619 620 621Note that :meth:`float.hex` is an instance method, while 622:meth:`float.fromhex` is a class method. 623 624A hexadecimal string takes the form:: 625 626 [sign] ['0x'] integer ['.' fraction] ['p' exponent] 627 628where the optional ``sign`` may by either ``+`` or ``-``, ``integer`` 629and ``fraction`` are strings of hexadecimal digits, and ``exponent`` 630is a decimal integer with an optional leading sign. Case is not 631significant, and there must be at least one hexadecimal digit in 632either the integer or the fraction. This syntax is similar to the 633syntax specified in section 6.4.4.2 of the C99 standard, and also to 634the syntax used in Java 1.5 onwards. In particular, the output of 635:meth:`float.hex` is usable as a hexadecimal floating-point literal in 636C or Java code, and hexadecimal strings produced by C's ``%a`` format 637character or Java's ``Double.toHexString`` are accepted by 638:meth:`float.fromhex`. 639 640 641Note that the exponent is written in decimal rather than hexadecimal, 642and that it gives the power of 2 by which to multiply the coefficient. 643For example, the hexadecimal string ``0x3.a7p10`` represents the 644floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or 645``3740.0``:: 646 647 >>> float.fromhex('0x3.a7p10') 648 3740.0 649 650 651Applying the reverse conversion to ``3740.0`` gives a different 652hexadecimal string representing the same number:: 653 654 >>> float.hex(3740.0) 655 '0x1.d380000000000p+11' 656 657 658.. _numeric-hash: 659 660Hashing of numeric types 661------------------------ 662 663For numbers ``x`` and ``y``, possibly of different types, it's a requirement 664that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`~object.__hash__` 665method documentation for more details). For ease of implementation and 666efficiency across a variety of numeric types (including :class:`int`, 667:class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) 668Python's hash for numeric types is based on a single mathematical function 669that's defined for any rational number, and hence applies to all instances of 670:class:`int` and :class:`fractions.Fraction`, and all finite instances of 671:class:`float` and :class:`decimal.Decimal`. Essentially, this function is 672given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is 673made available to Python as the :attr:`modulus` attribute of 674:data:`sys.hash_info`. 675 676.. impl-detail:: 677 678 Currently, the prime used is ``P = 2**31 - 1`` on machines with 32-bit C 679 longs and ``P = 2**61 - 1`` on machines with 64-bit C longs. 680 681Here are the rules in detail: 682 683- If ``x = m / n`` is a nonnegative rational number and ``n`` is not divisible 684 by ``P``, define ``hash(x)`` as ``m * invmod(n, P) % P``, where ``invmod(n, 685 P)`` gives the inverse of ``n`` modulo ``P``. 686 687- If ``x = m / n`` is a nonnegative rational number and ``n`` is 688 divisible by ``P`` (but ``m`` is not) then ``n`` has no inverse 689 modulo ``P`` and the rule above doesn't apply; in this case define 690 ``hash(x)`` to be the constant value ``sys.hash_info.inf``. 691 692- If ``x = m / n`` is a negative rational number define ``hash(x)`` 693 as ``-hash(-x)``. If the resulting hash is ``-1``, replace it with 694 ``-2``. 695 696- The particular values ``sys.hash_info.inf`` and ``-sys.hash_info.inf`` 697 are used as hash values for positive 698 infinity or negative infinity (respectively). 699 700- For a :class:`complex` number ``z``, the hash values of the real 701 and imaginary parts are combined by computing ``hash(z.real) + 702 sys.hash_info.imag * hash(z.imag)``, reduced modulo 703 ``2**sys.hash_info.width`` so that it lies in 704 ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 705 1))``. Again, if the result is ``-1``, it's replaced with ``-2``. 706 707 708To clarify the above rules, here's some example Python code, 709equivalent to the built-in hash, for computing the hash of a rational 710number, :class:`float`, or :class:`complex`:: 711 712 713 import sys, math 714 715 def hash_fraction(m, n): 716 """Compute the hash of a rational number m / n. 717 718 Assumes m and n are integers, with n positive. 719 Equivalent to hash(fractions.Fraction(m, n)). 720 721 """ 722 P = sys.hash_info.modulus 723 # Remove common factors of P. (Unnecessary if m and n already coprime.) 724 while m % P == n % P == 0: 725 m, n = m // P, n // P 726 727 if n % P == 0: 728 hash_value = sys.hash_info.inf 729 else: 730 # Fermat's Little Theorem: pow(n, P-1, P) is 1, so 731 # pow(n, P-2, P) gives the inverse of n modulo P. 732 hash_value = (abs(m) % P) * pow(n, P - 2, P) % P 733 if m < 0: 734 hash_value = -hash_value 735 if hash_value == -1: 736 hash_value = -2 737 return hash_value 738 739 def hash_float(x): 740 """Compute the hash of a float x.""" 741 742 if math.isnan(x): 743 return object.__hash__(x) 744 elif math.isinf(x): 745 return sys.hash_info.inf if x > 0 else -sys.hash_info.inf 746 else: 747 return hash_fraction(*x.as_integer_ratio()) 748 749 def hash_complex(z): 750 """Compute the hash of a complex number z.""" 751 752 hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) 753 # do a signed reduction modulo 2**sys.hash_info.width 754 M = 2**(sys.hash_info.width - 1) 755 hash_value = (hash_value & (M - 1)) - (hash_value & M) 756 if hash_value == -1: 757 hash_value = -2 758 return hash_value 759 760.. _typeiter: 761 762Iterator Types 763============== 764 765.. index:: 766 single: iterator protocol 767 single: protocol; iterator 768 single: sequence; iteration 769 single: container; iteration over 770 771Python supports a concept of iteration over containers. This is implemented 772using two distinct methods; these are used to allow user-defined classes to 773support iteration. Sequences, described below in more detail, always support 774the iteration methods. 775 776One method needs to be defined for container objects to provide :term:`iterable` 777support: 778 779.. XXX duplicated in reference/datamodel! 780 781.. method:: container.__iter__() 782 783 Return an :term:`iterator` object. The object is required to support the 784 iterator protocol described below. If a container supports different types 785 of iteration, additional methods can be provided to specifically request 786 iterators for those iteration types. (An example of an object supporting 787 multiple forms of iteration would be a tree structure which supports both 788 breadth-first and depth-first traversal.) This method corresponds to the 789 :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python 790 objects in the Python/C API. 791 792The iterator objects themselves are required to support the following two 793methods, which together form the :dfn:`iterator protocol`: 794 795 796.. method:: iterator.__iter__() 797 798 Return the :term:`iterator` object itself. This is required to allow both 799 containers and iterators to be used with the :keyword:`for` and 800 :keyword:`in` statements. This method corresponds to the 801 :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python 802 objects in the Python/C API. 803 804 805.. method:: iterator.__next__() 806 807 Return the next item from the :term:`iterator`. If there are no further 808 items, raise the :exc:`StopIteration` exception. This method corresponds to 809 the :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for 810 Python objects in the Python/C API. 811 812Python defines several iterator objects to support iteration over general and 813specific sequence types, dictionaries, and other more specialized forms. The 814specific types are not important beyond their implementation of the iterator 815protocol. 816 817Once an iterator's :meth:`~iterator.__next__` method raises 818:exc:`StopIteration`, it must continue to do so on subsequent calls. 819Implementations that do not obey this property are deemed broken. 820 821 822.. _generator-types: 823 824Generator Types 825--------------- 826 827Python's :term:`generator`\s provide a convenient way to implement the iterator 828protocol. If a container object's :meth:`__iter__` method is implemented as a 829generator, it will automatically return an iterator object (technically, a 830generator object) supplying the :meth:`__iter__` and :meth:`~generator.__next__` 831methods. 832More information about generators can be found in :ref:`the documentation for 833the yield expression <yieldexpr>`. 834 835 836.. _typesseq: 837 838Sequence Types --- :class:`list`, :class:`tuple`, :class:`range` 839================================================================ 840 841There are three basic sequence types: lists, tuples, and range objects. 842Additional sequence types tailored for processing of 843:ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are 844described in dedicated sections. 845 846 847.. _typesseq-common: 848 849Common Sequence Operations 850-------------------------- 851 852.. index:: object: sequence 853 854The operations in the following table are supported by most sequence types, 855both mutable and immutable. The :class:`collections.abc.Sequence` ABC is 856provided to make it easier to correctly implement these operations on 857custom sequence types. 858 859This table lists the sequence operations sorted in ascending priority. In the 860table, *s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are 861integers and *x* is an arbitrary object that meets any type and value 862restrictions imposed by *s*. 863 864The ``in`` and ``not in`` operations have the same priorities as the 865comparison operations. The ``+`` (concatenation) and ``*`` (repetition) 866operations have the same priority as the corresponding numeric operations. [3]_ 867 868.. index:: 869 triple: operations on; sequence; types 870 builtin: len 871 builtin: min 872 builtin: max 873 pair: concatenation; operation 874 pair: repetition; operation 875 pair: subscript; operation 876 pair: slice; operation 877 operator: in 878 operator: not in 879 single: count() (sequence method) 880 single: index() (sequence method) 881 882+--------------------------+--------------------------------+----------+ 883| Operation | Result | Notes | 884+==========================+================================+==========+ 885| ``x in s`` | ``True`` if an item of *s* is | \(1) | 886| | equal to *x*, else ``False`` | | 887+--------------------------+--------------------------------+----------+ 888| ``x not in s`` | ``False`` if an item of *s* is | \(1) | 889| | equal to *x*, else ``True`` | | 890+--------------------------+--------------------------------+----------+ 891| ``s + t`` | the concatenation of *s* and | (6)(7) | 892| | *t* | | 893+--------------------------+--------------------------------+----------+ 894| ``s * n`` or | equivalent to adding *s* to | (2)(7) | 895| ``n * s`` | itself *n* times | | 896+--------------------------+--------------------------------+----------+ 897| ``s[i]`` | *i*\ th item of *s*, origin 0 | \(3) | 898+--------------------------+--------------------------------+----------+ 899| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) | 900+--------------------------+--------------------------------+----------+ 901| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) | 902| | with step *k* | | 903+--------------------------+--------------------------------+----------+ 904| ``len(s)`` | length of *s* | | 905+--------------------------+--------------------------------+----------+ 906| ``min(s)`` | smallest item of *s* | | 907+--------------------------+--------------------------------+----------+ 908| ``max(s)`` | largest item of *s* | | 909+--------------------------+--------------------------------+----------+ 910| ``s.index(x[, i[, j]])`` | index of the first occurrence | \(8) | 911| | of *x* in *s* (at or after | | 912| | index *i* and before index *j*)| | 913+--------------------------+--------------------------------+----------+ 914| ``s.count(x)`` | total number of occurrences of | | 915| | *x* in *s* | | 916+--------------------------+--------------------------------+----------+ 917 918Sequences of the same type also support comparisons. In particular, tuples 919and lists are compared lexicographically by comparing corresponding elements. 920This means that to compare equal, every element must compare equal and the 921two sequences must be of the same type and have the same length. (For full 922details see :ref:`comparisons` in the language reference.) 923 924.. index:: 925 single: loop; over mutable sequence 926 single: mutable sequence; loop over 927 928Forward and reversed iterators over mutable sequences access values using an 929index. That index will continue to march forward (or backward) even if the 930underlying sequence is mutated. The iterator terminates only when an 931:exc:`IndexError` or a :exc:`StopIteration` is encountered (or when the index 932drops below zero). 933 934Notes: 935 936(1) 937 While the ``in`` and ``not in`` operations are used only for simple 938 containment testing in the general case, some specialised sequences 939 (such as :class:`str`, :class:`bytes` and :class:`bytearray`) also use 940 them for subsequence testing:: 941 942 >>> "gg" in "eggs" 943 True 944 945(2) 946 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty 947 sequence of the same type as *s*). Note that items in the sequence *s* 948 are not copied; they are referenced multiple times. This often haunts 949 new Python programmers; consider:: 950 951 >>> lists = [[]] * 3 952 >>> lists 953 [[], [], []] 954 >>> lists[0].append(3) 955 >>> lists 956 [[3], [3], [3]] 957 958 What has happened is that ``[[]]`` is a one-element list containing an empty 959 list, so all three elements of ``[[]] * 3`` are references to this single empty 960 list. Modifying any of the elements of ``lists`` modifies this single list. 961 You can create a list of different lists this way:: 962 963 >>> lists = [[] for i in range(3)] 964 >>> lists[0].append(3) 965 >>> lists[1].append(5) 966 >>> lists[2].append(7) 967 >>> lists 968 [[3], [5], [7]] 969 970 Further explanation is available in the FAQ entry 971 :ref:`faq-multidimensional-list`. 972 973(3) 974 If *i* or *j* is negative, the index is relative to the end of sequence *s*: 975 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is 976 still ``0``. 977 978(4) 979 The slice of *s* from *i* to *j* is defined as the sequence of items with index 980 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use 981 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or 982 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is 983 empty. 984 985(5) 986 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of 987 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words, 988 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when 989 *j* is reached (but never including *j*). When *k* is positive, 990 *i* and *j* are reduced to ``len(s)`` if they are greater. 991 When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if 992 they are greater. If *i* or *j* are omitted or ``None``, they become 993 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. 994 If *k* is ``None``, it is treated like ``1``. 995 996(6) 997 Concatenating immutable sequences always results in a new object. This 998 means that building up a sequence by repeated concatenation will have a 999 quadratic runtime cost in the total sequence length. To get a linear 1000 runtime cost, you must switch to one of the alternatives below: 1001 1002 * if concatenating :class:`str` objects, you can build a list and use 1003 :meth:`str.join` at the end or else write to an :class:`io.StringIO` 1004 instance and retrieve its value when complete 1005 1006 * if concatenating :class:`bytes` objects, you can similarly use 1007 :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place 1008 concatenation with a :class:`bytearray` object. :class:`bytearray` 1009 objects are mutable and have an efficient overallocation mechanism 1010 1011 * if concatenating :class:`tuple` objects, extend a :class:`list` instead 1012 1013 * for other types, investigate the relevant class documentation 1014 1015 1016(7) 1017 Some sequence types (such as :class:`range`) only support item sequences 1018 that follow specific patterns, and hence don't support sequence 1019 concatenation or repetition. 1020 1021(8) 1022 ``index`` raises :exc:`ValueError` when *x* is not found in *s*. 1023 Not all implementations support passing the additional arguments *i* and *j*. 1024 These arguments allow efficient searching of subsections of the sequence. Passing 1025 the extra arguments is roughly equivalent to using ``s[i:j].index(x)``, only 1026 without copying any data and with the returned index being relative to 1027 the start of the sequence rather than the start of the slice. 1028 1029 1030.. _typesseq-immutable: 1031 1032Immutable Sequence Types 1033------------------------ 1034 1035.. index:: 1036 triple: immutable; sequence; types 1037 object: tuple 1038 builtin: hash 1039 1040The only operation that immutable sequence types generally implement that is 1041not also implemented by mutable sequence types is support for the :func:`hash` 1042built-in. 1043 1044This support allows immutable sequences, such as :class:`tuple` instances, to 1045be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset` 1046instances. 1047 1048Attempting to hash an immutable sequence that contains unhashable values will 1049result in :exc:`TypeError`. 1050 1051 1052.. _typesseq-mutable: 1053 1054Mutable Sequence Types 1055---------------------- 1056 1057.. index:: 1058 triple: mutable; sequence; types 1059 object: list 1060 object: bytearray 1061 1062The operations in the following table are defined on mutable sequence types. 1063The :class:`collections.abc.MutableSequence` ABC is provided to make it 1064easier to correctly implement these operations on custom sequence types. 1065 1066In the table *s* is an instance of a mutable sequence type, *t* is any 1067iterable object and *x* is an arbitrary object that meets any type 1068and value restrictions imposed by *s* (for example, :class:`bytearray` only 1069accepts integers that meet the value restriction ``0 <= x <= 255``). 1070 1071 1072.. index:: 1073 triple: operations on; sequence; types 1074 triple: operations on; list; type 1075 pair: subscript; assignment 1076 pair: slice; assignment 1077 statement: del 1078 single: append() (sequence method) 1079 single: clear() (sequence method) 1080 single: copy() (sequence method) 1081 single: extend() (sequence method) 1082 single: insert() (sequence method) 1083 single: pop() (sequence method) 1084 single: remove() (sequence method) 1085 single: reverse() (sequence method) 1086 1087+------------------------------+--------------------------------+---------------------+ 1088| Operation | Result | Notes | 1089+==============================+================================+=====================+ 1090| ``s[i] = x`` | item *i* of *s* is replaced by | | 1091| | *x* | | 1092+------------------------------+--------------------------------+---------------------+ 1093| ``s[i:j] = t`` | slice of *s* from *i* to *j* | | 1094| | is replaced by the contents of | | 1095| | the iterable *t* | | 1096+------------------------------+--------------------------------+---------------------+ 1097| ``del s[i:j]`` | same as ``s[i:j] = []`` | | 1098+------------------------------+--------------------------------+---------------------+ 1099| ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) | 1100| | are replaced by those of *t* | | 1101+------------------------------+--------------------------------+---------------------+ 1102| ``del s[i:j:k]`` | removes the elements of | | 1103| | ``s[i:j:k]`` from the list | | 1104+------------------------------+--------------------------------+---------------------+ 1105| ``s.append(x)`` | appends *x* to the end of the | | 1106| | sequence (same as | | 1107| | ``s[len(s):len(s)] = [x]``) | | 1108+------------------------------+--------------------------------+---------------------+ 1109| ``s.clear()`` | removes all items from *s* | \(5) | 1110| | (same as ``del s[:]``) | | 1111+------------------------------+--------------------------------+---------------------+ 1112| ``s.copy()`` | creates a shallow copy of *s* | \(5) | 1113| | (same as ``s[:]``) | | 1114+------------------------------+--------------------------------+---------------------+ 1115| ``s.extend(t)`` or | extends *s* with the | | 1116| ``s += t`` | contents of *t* (for the | | 1117| | most part the same as | | 1118| | ``s[len(s):len(s)] = t``) | | 1119+------------------------------+--------------------------------+---------------------+ 1120| ``s *= n`` | updates *s* with its contents | \(6) | 1121| | repeated *n* times | | 1122+------------------------------+--------------------------------+---------------------+ 1123| ``s.insert(i, x)`` | inserts *x* into *s* at the | | 1124| | index given by *i* | | 1125| | (same as ``s[i:i] = [x]``) | | 1126+------------------------------+--------------------------------+---------------------+ 1127| ``s.pop()`` or ``s.pop(i)`` | retrieves the item at *i* and | \(2) | 1128| | also removes it from *s* | | 1129+------------------------------+--------------------------------+---------------------+ 1130| ``s.remove(x)`` | remove the first item from *s* | \(3) | 1131| | where ``s[i]`` is equal to *x* | | 1132+------------------------------+--------------------------------+---------------------+ 1133| ``s.reverse()`` | reverses the items of *s* in | \(4) | 1134| | place | | 1135+------------------------------+--------------------------------+---------------------+ 1136 1137 1138Notes: 1139 1140(1) 1141 *t* must have the same length as the slice it is replacing. 1142 1143(2) 1144 The optional argument *i* defaults to ``-1``, so that by default the last 1145 item is removed and returned. 1146 1147(3) 1148 :meth:`remove` raises :exc:`ValueError` when *x* is not found in *s*. 1149 1150(4) 1151 The :meth:`reverse` method modifies the sequence in place for economy of 1152 space when reversing a large sequence. To remind users that it operates by 1153 side effect, it does not return the reversed sequence. 1154 1155(5) 1156 :meth:`clear` and :meth:`!copy` are included for consistency with the 1157 interfaces of mutable containers that don't support slicing operations 1158 (such as :class:`dict` and :class:`set`). :meth:`!copy` is not part of the 1159 :class:`collections.abc.MutableSequence` ABC, but most concrete 1160 mutable sequence classes provide it. 1161 1162 .. versionadded:: 3.3 1163 :meth:`clear` and :meth:`!copy` methods. 1164 1165(6) 1166 The value *n* is an integer, or an object implementing 1167 :meth:`~object.__index__`. Zero and negative values of *n* clear 1168 the sequence. Items in the sequence are not copied; they are referenced 1169 multiple times, as explained for ``s * n`` under :ref:`typesseq-common`. 1170 1171 1172.. _typesseq-list: 1173 1174Lists 1175----- 1176 1177.. index:: object: list 1178 1179Lists are mutable sequences, typically used to store collections of 1180homogeneous items (where the precise degree of similarity will vary by 1181application). 1182 1183.. class:: list([iterable]) 1184 1185 Lists may be constructed in several ways: 1186 1187 * Using a pair of square brackets to denote the empty list: ``[]`` 1188 * Using square brackets, separating items with commas: ``[a]``, ``[a, b, c]`` 1189 * Using a list comprehension: ``[x for x in iterable]`` 1190 * Using the type constructor: ``list()`` or ``list(iterable)`` 1191 1192 The constructor builds a list whose items are the same and in the same 1193 order as *iterable*'s items. *iterable* may be either a sequence, a 1194 container that supports iteration, or an iterator object. If *iterable* 1195 is already a list, a copy is made and returned, similar to ``iterable[:]``. 1196 For example, ``list('abc')`` returns ``['a', 'b', 'c']`` and 1197 ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. 1198 If no argument is given, the constructor creates a new empty list, ``[]``. 1199 1200 1201 Many other operations also produce lists, including the :func:`sorted` 1202 built-in. 1203 1204 Lists implement all of the :ref:`common <typesseq-common>` and 1205 :ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the 1206 following additional method: 1207 1208 .. method:: list.sort(*, key=None, reverse=False) 1209 1210 This method sorts the list in place, using only ``<`` comparisons 1211 between items. Exceptions are not suppressed - if any comparison operations 1212 fail, the entire sort operation will fail (and the list will likely be left 1213 in a partially modified state). 1214 1215 :meth:`sort` accepts two arguments that can only be passed by keyword 1216 (:ref:`keyword-only arguments <keyword-only_parameter>`): 1217 1218 *key* specifies a function of one argument that is used to extract a 1219 comparison key from each list element (for example, ``key=str.lower``). 1220 The key corresponding to each item in the list is calculated once and 1221 then used for the entire sorting process. The default value of ``None`` 1222 means that list items are sorted directly without calculating a separate 1223 key value. 1224 1225 The :func:`functools.cmp_to_key` utility is available to convert a 2.x 1226 style *cmp* function to a *key* function. 1227 1228 *reverse* is a boolean value. If set to ``True``, then the list elements 1229 are sorted as if each comparison were reversed. 1230 1231 This method modifies the sequence in place for economy of space when 1232 sorting a large sequence. To remind users that it operates by side 1233 effect, it does not return the sorted sequence (use :func:`sorted` to 1234 explicitly request a new sorted list instance). 1235 1236 The :meth:`sort` method is guaranteed to be stable. A sort is stable if it 1237 guarantees not to change the relative order of elements that compare equal 1238 --- this is helpful for sorting in multiple passes (for example, sort by 1239 department, then by salary grade). 1240 1241 For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. 1242 1243 .. impl-detail:: 1244 1245 While a list is being sorted, the effect of attempting to mutate, or even 1246 inspect, the list is undefined. The C implementation of Python makes the 1247 list appear empty for the duration, and raises :exc:`ValueError` if it can 1248 detect that the list has been mutated during a sort. 1249 1250 1251.. _typesseq-tuple: 1252 1253Tuples 1254------ 1255 1256.. index:: object: tuple 1257 1258Tuples are immutable sequences, typically used to store collections of 1259heterogeneous data (such as the 2-tuples produced by the :func:`enumerate` 1260built-in). Tuples are also used for cases where an immutable sequence of 1261homogeneous data is needed (such as allowing storage in a :class:`set` or 1262:class:`dict` instance). 1263 1264.. class:: tuple([iterable]) 1265 1266 Tuples may be constructed in a number of ways: 1267 1268 * Using a pair of parentheses to denote the empty tuple: ``()`` 1269 * Using a trailing comma for a singleton tuple: ``a,`` or ``(a,)`` 1270 * Separating items with commas: ``a, b, c`` or ``(a, b, c)`` 1271 * Using the :func:`tuple` built-in: ``tuple()`` or ``tuple(iterable)`` 1272 1273 The constructor builds a tuple whose items are the same and in the same 1274 order as *iterable*'s items. *iterable* may be either a sequence, a 1275 container that supports iteration, or an iterator object. If *iterable* 1276 is already a tuple, it is returned unchanged. For example, 1277 ``tuple('abc')`` returns ``('a', 'b', 'c')`` and 1278 ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. 1279 If no argument is given, the constructor creates a new empty tuple, ``()``. 1280 1281 Note that it is actually the comma which makes a tuple, not the parentheses. 1282 The parentheses are optional, except in the empty tuple case, or 1283 when they are needed to avoid syntactic ambiguity. For example, 1284 ``f(a, b, c)`` is a function call with three arguments, while 1285 ``f((a, b, c))`` is a function call with a 3-tuple as the sole argument. 1286 1287 Tuples implement all of the :ref:`common <typesseq-common>` sequence 1288 operations. 1289 1290For heterogeneous collections of data where access by name is clearer than 1291access by index, :func:`collections.namedtuple` may be a more appropriate 1292choice than a simple tuple object. 1293 1294 1295.. _typesseq-range: 1296 1297Ranges 1298------ 1299 1300.. index:: object: range 1301 1302The :class:`range` type represents an immutable sequence of numbers and is 1303commonly used for looping a specific number of times in :keyword:`for` 1304loops. 1305 1306.. class:: range(stop) 1307 range(start, stop[, step]) 1308 1309 The arguments to the range constructor must be integers (either built-in 1310 :class:`int` or any object that implements the :meth:`~object.__index__` special 1311 method). If the *step* argument is omitted, it defaults to ``1``. 1312 If the *start* argument is omitted, it defaults to ``0``. 1313 If *step* is zero, :exc:`ValueError` is raised. 1314 1315 For a positive *step*, the contents of a range ``r`` are determined by the 1316 formula ``r[i] = start + step*i`` where ``i >= 0`` and 1317 ``r[i] < stop``. 1318 1319 For a negative *step*, the contents of the range are still determined by 1320 the formula ``r[i] = start + step*i``, but the constraints are ``i >= 0`` 1321 and ``r[i] > stop``. 1322 1323 A range object will be empty if ``r[0]`` does not meet the value 1324 constraint. Ranges do support negative indices, but these are interpreted 1325 as indexing from the end of the sequence determined by the positive 1326 indices. 1327 1328 Ranges containing absolute values larger than :data:`sys.maxsize` are 1329 permitted but some features (such as :func:`len`) may raise 1330 :exc:`OverflowError`. 1331 1332 Range examples:: 1333 1334 >>> list(range(10)) 1335 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 1336 >>> list(range(1, 11)) 1337 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 1338 >>> list(range(0, 30, 5)) 1339 [0, 5, 10, 15, 20, 25] 1340 >>> list(range(0, 10, 3)) 1341 [0, 3, 6, 9] 1342 >>> list(range(0, -10, -1)) 1343 [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] 1344 >>> list(range(0)) 1345 [] 1346 >>> list(range(1, 0)) 1347 [] 1348 1349 Ranges implement all of the :ref:`common <typesseq-common>` sequence operations 1350 except concatenation and repetition (due to the fact that range objects can 1351 only represent sequences that follow a strict pattern and repetition and 1352 concatenation will usually violate that pattern). 1353 1354 .. attribute:: start 1355 1356 The value of the *start* parameter (or ``0`` if the parameter was 1357 not supplied) 1358 1359 .. attribute:: stop 1360 1361 The value of the *stop* parameter 1362 1363 .. attribute:: step 1364 1365 The value of the *step* parameter (or ``1`` if the parameter was 1366 not supplied) 1367 1368The advantage of the :class:`range` type over a regular :class:`list` or 1369:class:`tuple` is that a :class:`range` object will always take the same 1370(small) amount of memory, no matter the size of the range it represents (as it 1371only stores the ``start``, ``stop`` and ``step`` values, calculating individual 1372items and subranges as needed). 1373 1374Range objects implement the :class:`collections.abc.Sequence` ABC, and provide 1375features such as containment tests, element index lookup, slicing and 1376support for negative indices (see :ref:`typesseq`): 1377 1378 >>> r = range(0, 20, 2) 1379 >>> r 1380 range(0, 20, 2) 1381 >>> 11 in r 1382 False 1383 >>> 10 in r 1384 True 1385 >>> r.index(10) 1386 5 1387 >>> r[5] 1388 10 1389 >>> r[:5] 1390 range(0, 10, 2) 1391 >>> r[-1] 1392 18 1393 1394Testing range objects for equality with ``==`` and ``!=`` compares 1395them as sequences. That is, two range objects are considered equal if 1396they represent the same sequence of values. (Note that two range 1397objects that compare equal might have different :attr:`~range.start`, 1398:attr:`~range.stop` and :attr:`~range.step` attributes, for example 1399``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.) 1400 1401.. versionchanged:: 3.2 1402 Implement the Sequence ABC. 1403 Support slicing and negative indices. 1404 Test :class:`int` objects for membership in constant time instead of 1405 iterating through all items. 1406 1407.. versionchanged:: 3.3 1408 Define '==' and '!=' to compare range objects based on the 1409 sequence of values they define (instead of comparing based on 1410 object identity). 1411 1412.. versionadded:: 3.3 1413 The :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step` 1414 attributes. 1415 1416.. seealso:: 1417 1418 * The `linspace recipe <http://code.activestate.com/recipes/579000/>`_ 1419 shows how to implement a lazy version of range suitable for floating 1420 point applications. 1421 1422.. index:: 1423 single: string; text sequence type 1424 single: str (built-in class); (see also string) 1425 object: string 1426 1427.. _textseq: 1428 1429Text Sequence Type --- :class:`str` 1430=================================== 1431 1432Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`. 1433Strings are immutable 1434:ref:`sequences <typesseq>` of Unicode code points. String literals are 1435written in a variety of ways: 1436 1437* Single quotes: ``'allows embedded "double" quotes'`` 1438* Double quotes: ``"allows embedded 'single' quotes"`` 1439* Triple quoted: ``'''Three single quotes'''``, ``"""Three double quotes"""`` 1440 1441Triple quoted strings may span multiple lines - all associated whitespace will 1442be included in the string literal. 1443 1444String literals that are part of a single expression and have only whitespace 1445between them will be implicitly converted to a single string literal. That 1446is, ``("spam " "eggs") == "spam eggs"``. 1447 1448See :ref:`strings` for more about the various forms of string literal, 1449including supported escape sequences, and the ``r`` ("raw") prefix that 1450disables most escape sequence processing. 1451 1452Strings may also be created from other objects using the :class:`str` 1453constructor. 1454 1455Since there is no separate "character" type, indexing a string produces 1456strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``. 1457 1458.. index:: 1459 object: io.StringIO 1460 1461There is also no mutable string type, but :meth:`str.join` or 1462:class:`io.StringIO` can be used to efficiently construct strings from 1463multiple fragments. 1464 1465.. versionchanged:: 3.3 1466 For backwards compatibility with the Python 2 series, the ``u`` prefix is 1467 once again permitted on string literals. It has no effect on the meaning 1468 of string literals and cannot be combined with the ``r`` prefix. 1469 1470 1471.. index:: 1472 single: string; str (built-in class) 1473 1474.. class:: str(object='') 1475 str(object=b'', encoding='utf-8', errors='strict') 1476 1477 Return a :ref:`string <textseq>` version of *object*. If *object* is not 1478 provided, returns the empty string. Otherwise, the behavior of ``str()`` 1479 depends on whether *encoding* or *errors* is given, as follows. 1480 1481 If neither *encoding* nor *errors* is given, ``str(object)`` returns 1482 :meth:`object.__str__() <object.__str__>`, which is the "informal" or nicely 1483 printable string representation of *object*. For string objects, this is 1484 the string itself. If *object* does not have a :meth:`~object.__str__` 1485 method, then :func:`str` falls back to returning 1486 :meth:`repr(object) <repr>`. 1487 1488 .. index:: 1489 single: buffer protocol; str (built-in class) 1490 single: bytes; str (built-in class) 1491 1492 If at least one of *encoding* or *errors* is given, *object* should be a 1493 :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In 1494 this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, 1495 then ``str(bytes, encoding, errors)`` is equivalent to 1496 :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes 1497 object underlying the buffer object is obtained before calling 1498 :meth:`bytes.decode`. See :ref:`binaryseq` and 1499 :ref:`bufferobjects` for information on buffer objects. 1500 1501 Passing a :class:`bytes` object to :func:`str` without the *encoding* 1502 or *errors* arguments falls under the first case of returning the informal 1503 string representation (see also the :option:`-b` command-line option to 1504 Python). For example:: 1505 1506 >>> str(b'Zoot!') 1507 "b'Zoot!'" 1508 1509 For more information on the ``str`` class and its methods, see 1510 :ref:`textseq` and the :ref:`string-methods` section below. To output 1511 formatted strings, see the :ref:`f-strings` and :ref:`formatstrings` 1512 sections. In addition, see the :ref:`stringservices` section. 1513 1514 1515.. index:: 1516 pair: string; methods 1517 1518.. _string-methods: 1519 1520String Methods 1521-------------- 1522 1523.. index:: 1524 module: re 1525 1526Strings implement all of the :ref:`common <typesseq-common>` sequence 1527operations, along with the additional methods described below. 1528 1529Strings also support two styles of string formatting, one providing a large 1530degree of flexibility and customization (see :meth:`str.format`, 1531:ref:`formatstrings` and :ref:`string-formatting`) and the other based on C 1532``printf`` style formatting that handles a narrower range of types and is 1533slightly harder to use correctly, but is often faster for the cases it can 1534handle (:ref:`old-string-formatting`). 1535 1536The :ref:`textservices` section of the standard library covers a number of 1537other modules that provide various text related utilities (including regular 1538expression support in the :mod:`re` module). 1539 1540.. method:: str.capitalize() 1541 1542 Return a copy of the string with its first character capitalized and the 1543 rest lowercased. 1544 1545 .. versionchanged:: 3.8 1546 The first character is now put into titlecase rather than uppercase. 1547 This means that characters like digraphs will only have their first 1548 letter capitalized, instead of the full character. 1549 1550.. method:: str.casefold() 1551 1552 Return a casefolded copy of the string. Casefolded strings may be used for 1553 caseless matching. 1554 1555 Casefolding is similar to lowercasing but more aggressive because it is 1556 intended to remove all case distinctions in a string. For example, the German 1557 lowercase letter ``'ß'`` is equivalent to ``"ss"``. Since it is already 1558 lowercase, :meth:`lower` would do nothing to ``'ß'``; :meth:`casefold` 1559 converts it to ``"ss"``. 1560 1561 The casefolding algorithm is described in section 3.13 of the Unicode 1562 Standard. 1563 1564 .. versionadded:: 3.3 1565 1566 1567.. method:: str.center(width[, fillchar]) 1568 1569 Return centered in a string of length *width*. Padding is done using the 1570 specified *fillchar* (default is an ASCII space). The original string is 1571 returned if *width* is less than or equal to ``len(s)``. 1572 1573 1574 1575.. method:: str.count(sub[, start[, end]]) 1576 1577 Return the number of non-overlapping occurrences of substring *sub* in the 1578 range [*start*, *end*]. Optional arguments *start* and *end* are 1579 interpreted as in slice notation. 1580 1581 1582.. method:: str.encode(encoding="utf-8", errors="strict") 1583 1584 Return an encoded version of the string as a bytes object. Default encoding 1585 is ``'utf-8'``. *errors* may be given to set a different error handling scheme. 1586 The default for *errors* is ``'strict'``, meaning that encoding errors raise 1587 a :exc:`UnicodeError`. Other possible 1588 values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, 1589 ``'backslashreplace'`` and any other name registered via 1590 :func:`codecs.register_error`, see section :ref:`error-handlers`. For a 1591 list of possible encodings, see section :ref:`standard-encodings`. 1592 1593 By default, the *errors* argument is not checked for best performances, but 1594 only used at the first encoding error. Enable the :ref:`Python Development 1595 Mode <devmode>`, or use a :ref:`debug build <debug-build>` to check 1596 *errors*. 1597 1598 .. versionchanged:: 3.1 1599 Support for keyword arguments added. 1600 1601 .. versionchanged:: 3.9 1602 The *errors* is now checked in development mode and 1603 in :ref:`debug mode <debug-build>`. 1604 1605 1606.. method:: str.endswith(suffix[, start[, end]]) 1607 1608 Return ``True`` if the string ends with the specified *suffix*, otherwise return 1609 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional 1610 *start*, test beginning at that position. With optional *end*, stop comparing 1611 at that position. 1612 1613 1614.. method:: str.expandtabs(tabsize=8) 1615 1616 Return a copy of the string where all tab characters are replaced by one or 1617 more spaces, depending on the current column and the given tab size. Tab 1618 positions occur every *tabsize* characters (default is 8, giving tab 1619 positions at columns 0, 8, 16 and so on). To expand the string, the current 1620 column is set to zero and the string is examined character by character. If 1621 the character is a tab (``\t``), one or more space characters are inserted 1622 in the result until the current column is equal to the next tab position. 1623 (The tab character itself is not copied.) If the character is a newline 1624 (``\n``) or return (``\r``), it is copied and the current column is reset to 1625 zero. Any other character is copied unchanged and the current column is 1626 incremented by one regardless of how the character is represented when 1627 printed. 1628 1629 >>> '01\t012\t0123\t01234'.expandtabs() 1630 '01 012 0123 01234' 1631 >>> '01\t012\t0123\t01234'.expandtabs(4) 1632 '01 012 0123 01234' 1633 1634 1635.. method:: str.find(sub[, start[, end]]) 1636 1637 Return the lowest index in the string where substring *sub* is found within 1638 the slice ``s[start:end]``. Optional arguments *start* and *end* are 1639 interpreted as in slice notation. Return ``-1`` if *sub* is not found. 1640 1641 .. note:: 1642 1643 The :meth:`~str.find` method should be used only if you need to know the 1644 position of *sub*. To check if *sub* is a substring or not, use the 1645 :keyword:`in` operator:: 1646 1647 >>> 'Py' in 'Python' 1648 True 1649 1650 1651.. method:: str.format(*args, **kwargs) 1652 1653 Perform a string formatting operation. The string on which this method is 1654 called can contain literal text or replacement fields delimited by braces 1655 ``{}``. Each replacement field contains either the numeric index of a 1656 positional argument, or the name of a keyword argument. Returns a copy of 1657 the string where each replacement field is replaced with the string value of 1658 the corresponding argument. 1659 1660 >>> "The sum of 1 + 2 is {0}".format(1+2) 1661 'The sum of 1 + 2 is 3' 1662 1663 See :ref:`formatstrings` for a description of the various formatting options 1664 that can be specified in format strings. 1665 1666 .. note:: 1667 When formatting a number (:class:`int`, :class:`float`, :class:`complex`, 1668 :class:`decimal.Decimal` and subclasses) with the ``n`` type 1669 (ex: ``'{:n}'.format(1234)``), the function temporarily sets the 1670 ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode 1671 ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if 1672 they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is 1673 different than the ``LC_CTYPE`` locale. This temporary change affects 1674 other threads. 1675 1676 .. versionchanged:: 3.7 1677 When formatting a number with the ``n`` type, the function sets 1678 temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some 1679 cases. 1680 1681 1682.. method:: str.format_map(mapping) 1683 1684 Similar to ``str.format(**mapping)``, except that ``mapping`` is 1685 used directly and not copied to a :class:`dict`. This is useful 1686 if for example ``mapping`` is a dict subclass: 1687 1688 >>> class Default(dict): 1689 ... def __missing__(self, key): 1690 ... return key 1691 ... 1692 >>> '{name} was born in {country}'.format_map(Default(name='Guido')) 1693 'Guido was born in country' 1694 1695 .. versionadded:: 3.2 1696 1697 1698.. method:: str.index(sub[, start[, end]]) 1699 1700 Like :meth:`~str.find`, but raise :exc:`ValueError` when the substring is 1701 not found. 1702 1703 1704.. method:: str.isalnum() 1705 1706 Return ``True`` if all characters in the string are alphanumeric and there is at 1707 least one character, ``False`` otherwise. A character ``c`` is alphanumeric if one 1708 of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``, 1709 ``c.isdigit()``, or ``c.isnumeric()``. 1710 1711 1712.. method:: str.isalpha() 1713 1714 Return ``True`` if all characters in the string are alphabetic and there is at least 1715 one character, ``False`` otherwise. Alphabetic characters are those characters defined 1716 in the Unicode character database as "Letter", i.e., those with general category 1717 property being one of "Lm", "Lt", "Lu", "Ll", or "Lo". Note that this is different 1718 from the "Alphabetic" property defined in the Unicode Standard. 1719 1720 1721.. method:: str.isascii() 1722 1723 Return ``True`` if the string is empty or all characters in the string are ASCII, 1724 ``False`` otherwise. 1725 ASCII characters have code points in the range U+0000-U+007F. 1726 1727 .. versionadded:: 3.7 1728 1729 1730.. method:: str.isdecimal() 1731 1732 Return ``True`` if all characters in the string are decimal 1733 characters and there is at least one character, ``False`` 1734 otherwise. Decimal characters are those that can be used to form 1735 numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT 1736 ZERO. Formally a decimal character is a character in the Unicode 1737 General Category "Nd". 1738 1739 1740.. method:: str.isdigit() 1741 1742 Return ``True`` if all characters in the string are digits and there is at least one 1743 character, ``False`` otherwise. Digits include decimal characters and digits that need 1744 special handling, such as the compatibility superscript digits. 1745 This covers digits which cannot be used to form numbers in base 10, 1746 like the Kharosthi numbers. Formally, a digit is a character that has the 1747 property value Numeric_Type=Digit or Numeric_Type=Decimal. 1748 1749 1750.. method:: str.isidentifier() 1751 1752 Return ``True`` if the string is a valid identifier according to the language 1753 definition, section :ref:`identifiers`. 1754 1755 Call :func:`keyword.iskeyword` to test whether string ``s`` is a reserved 1756 identifier, such as :keyword:`def` and :keyword:`class`. 1757 1758 Example: 1759 :: 1760 1761 >>> from keyword import iskeyword 1762 1763 >>> 'hello'.isidentifier(), iskeyword('hello') 1764 (True, False) 1765 >>> 'def'.isidentifier(), iskeyword('def') 1766 (True, True) 1767 1768 1769.. method:: str.islower() 1770 1771 Return ``True`` if all cased characters [4]_ in the string are lowercase and 1772 there is at least one cased character, ``False`` otherwise. 1773 1774 1775.. method:: str.isnumeric() 1776 1777 Return ``True`` if all characters in the string are numeric 1778 characters, and there is at least one character, ``False`` 1779 otherwise. Numeric characters include digit characters, and all characters 1780 that have the Unicode numeric value property, e.g. U+2155, 1781 VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property 1782 value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. 1783 1784 1785.. method:: str.isprintable() 1786 1787 Return ``True`` if all characters in the string are printable or the string is 1788 empty, ``False`` otherwise. Nonprintable characters are those characters defined 1789 in the Unicode character database as "Other" or "Separator", excepting the 1790 ASCII space (0x20) which is considered printable. (Note that printable 1791 characters in this context are those which should not be escaped when 1792 :func:`repr` is invoked on a string. It has no bearing on the handling of 1793 strings written to :data:`sys.stdout` or :data:`sys.stderr`.) 1794 1795 1796.. method:: str.isspace() 1797 1798 Return ``True`` if there are only whitespace characters in the string and there is 1799 at least one character, ``False`` otherwise. 1800 1801 A character is *whitespace* if in the Unicode character database 1802 (see :mod:`unicodedata`), either its general category is ``Zs`` 1803 ("Separator, space"), or its bidirectional class is one of ``WS``, 1804 ``B``, or ``S``. 1805 1806 1807.. method:: str.istitle() 1808 1809 Return ``True`` if the string is a titlecased string and there is at least one 1810 character, for example uppercase characters may only follow uncased characters 1811 and lowercase characters only cased ones. Return ``False`` otherwise. 1812 1813 1814.. method:: str.isupper() 1815 1816 Return ``True`` if all cased characters [4]_ in the string are uppercase and 1817 there is at least one cased character, ``False`` otherwise. 1818 1819 >>> 'BANANA'.isupper() 1820 True 1821 >>> 'banana'.isupper() 1822 False 1823 >>> 'baNana'.isupper() 1824 False 1825 >>> ' '.isupper() 1826 False 1827 1828 1829 1830.. method:: str.join(iterable) 1831 1832 Return a string which is the concatenation of the strings in *iterable*. 1833 A :exc:`TypeError` will be raised if there are any non-string values in 1834 *iterable*, including :class:`bytes` objects. The separator between 1835 elements is the string providing this method. 1836 1837 1838.. method:: str.ljust(width[, fillchar]) 1839 1840 Return the string left justified in a string of length *width*. Padding is 1841 done using the specified *fillchar* (default is an ASCII space). The 1842 original string is returned if *width* is less than or equal to ``len(s)``. 1843 1844 1845.. method:: str.lower() 1846 1847 Return a copy of the string with all the cased characters [4]_ converted to 1848 lowercase. 1849 1850 The lowercasing algorithm used is described in section 3.13 of the Unicode 1851 Standard. 1852 1853 1854.. method:: str.lstrip([chars]) 1855 1856 Return a copy of the string with leading characters removed. The *chars* 1857 argument is a string specifying the set of characters to be removed. If omitted 1858 or ``None``, the *chars* argument defaults to removing whitespace. The *chars* 1859 argument is not a prefix; rather, all combinations of its values are stripped:: 1860 1861 >>> ' spacious '.lstrip() 1862 'spacious ' 1863 >>> 'www.example.com'.lstrip('cmowz.') 1864 'example.com' 1865 1866 See :meth:`str.removeprefix` for a method that will remove a single prefix 1867 string rather than all of a set of characters. For example:: 1868 1869 >>> 'Arthur: three!'.lstrip('Arthur: ') 1870 'ee!' 1871 >>> 'Arthur: three!'.removeprefix('Arthur: ') 1872 'three!' 1873 1874 1875.. staticmethod:: str.maketrans(x[, y[, z]]) 1876 1877 This static method returns a translation table usable for :meth:`str.translate`. 1878 1879 If there is only one argument, it must be a dictionary mapping Unicode 1880 ordinals (integers) or characters (strings of length 1) to Unicode ordinals, 1881 strings (of arbitrary lengths) or ``None``. Character keys will then be 1882 converted to ordinals. 1883 1884 If there are two arguments, they must be strings of equal length, and in the 1885 resulting dictionary, each character in x will be mapped to the character at 1886 the same position in y. If there is a third argument, it must be a string, 1887 whose characters will be mapped to ``None`` in the result. 1888 1889 1890.. method:: str.partition(sep) 1891 1892 Split the string at the first occurrence of *sep*, and return a 3-tuple 1893 containing the part before the separator, the separator itself, and the part 1894 after the separator. If the separator is not found, return a 3-tuple containing 1895 the string itself, followed by two empty strings. 1896 1897 1898.. method:: str.removeprefix(prefix, /) 1899 1900 If the string starts with the *prefix* string, return 1901 ``string[len(prefix):]``. Otherwise, return a copy of the original 1902 string:: 1903 1904 >>> 'TestHook'.removeprefix('Test') 1905 'Hook' 1906 >>> 'BaseTestCase'.removeprefix('Test') 1907 'BaseTestCase' 1908 1909 .. versionadded:: 3.9 1910 1911 1912.. method:: str.removesuffix(suffix, /) 1913 1914 If the string ends with the *suffix* string and that *suffix* is not empty, 1915 return ``string[:-len(suffix)]``. Otherwise, return a copy of the 1916 original string:: 1917 1918 >>> 'MiscTests'.removesuffix('Tests') 1919 'Misc' 1920 >>> 'TmpDirMixin'.removesuffix('Tests') 1921 'TmpDirMixin' 1922 1923 .. versionadded:: 3.9 1924 1925 1926.. method:: str.replace(old, new[, count]) 1927 1928 Return a copy of the string with all occurrences of substring *old* replaced by 1929 *new*. If the optional argument *count* is given, only the first *count* 1930 occurrences are replaced. 1931 1932 1933.. method:: str.rfind(sub[, start[, end]]) 1934 1935 Return the highest index in the string where substring *sub* is found, such 1936 that *sub* is contained within ``s[start:end]``. Optional arguments *start* 1937 and *end* are interpreted as in slice notation. Return ``-1`` on failure. 1938 1939 1940.. method:: str.rindex(sub[, start[, end]]) 1941 1942 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not 1943 found. 1944 1945 1946.. method:: str.rjust(width[, fillchar]) 1947 1948 Return the string right justified in a string of length *width*. Padding is 1949 done using the specified *fillchar* (default is an ASCII space). The 1950 original string is returned if *width* is less than or equal to ``len(s)``. 1951 1952 1953.. method:: str.rpartition(sep) 1954 1955 Split the string at the last occurrence of *sep*, and return a 3-tuple 1956 containing the part before the separator, the separator itself, and the part 1957 after the separator. If the separator is not found, return a 3-tuple containing 1958 two empty strings, followed by the string itself. 1959 1960 1961.. method:: str.rsplit(sep=None, maxsplit=-1) 1962 1963 Return a list of the words in the string, using *sep* as the delimiter string. 1964 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* 1965 ones. If *sep* is not specified or ``None``, any whitespace string is a 1966 separator. Except for splitting from the right, :meth:`rsplit` behaves like 1967 :meth:`split` which is described in detail below. 1968 1969 1970.. method:: str.rstrip([chars]) 1971 1972 Return a copy of the string with trailing characters removed. The *chars* 1973 argument is a string specifying the set of characters to be removed. If omitted 1974 or ``None``, the *chars* argument defaults to removing whitespace. The *chars* 1975 argument is not a suffix; rather, all combinations of its values are stripped:: 1976 1977 >>> ' spacious '.rstrip() 1978 ' spacious' 1979 >>> 'mississippi'.rstrip('ipz') 1980 'mississ' 1981 1982 See :meth:`str.removesuffix` for a method that will remove a single suffix 1983 string rather than all of a set of characters. For example:: 1984 1985 >>> 'Monty Python'.rstrip(' Python') 1986 'M' 1987 >>> 'Monty Python'.removesuffix(' Python') 1988 'Monty' 1989 1990.. method:: str.split(sep=None, maxsplit=-1) 1991 1992 Return a list of the words in the string, using *sep* as the delimiter 1993 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, 1994 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not 1995 specified or ``-1``, then there is no limit on the number of splits 1996 (all possible splits are made). 1997 1998 If *sep* is given, consecutive delimiters are not grouped together and are 1999 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns 2000 ``['1', '', '2']``). The *sep* argument may consist of multiple characters 2001 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``). 2002 Splitting an empty string with a specified separator returns ``['']``. 2003 2004 For example:: 2005 2006 >>> '1,2,3'.split(',') 2007 ['1', '2', '3'] 2008 >>> '1,2,3'.split(',', maxsplit=1) 2009 ['1', '2,3'] 2010 >>> '1,2,,3,'.split(',') 2011 ['1', '2', '', '3', ''] 2012 2013 If *sep* is not specified or is ``None``, a different splitting algorithm is 2014 applied: runs of consecutive whitespace are regarded as a single separator, 2015 and the result will contain no empty strings at the start or end if the 2016 string has leading or trailing whitespace. Consequently, splitting an empty 2017 string or a string consisting of just whitespace with a ``None`` separator 2018 returns ``[]``. 2019 2020 For example:: 2021 2022 >>> '1 2 3'.split() 2023 ['1', '2', '3'] 2024 >>> '1 2 3'.split(maxsplit=1) 2025 ['1', '2 3'] 2026 >>> ' 1 2 3 '.split() 2027 ['1', '2', '3'] 2028 2029 2030.. index:: 2031 single: universal newlines; str.splitlines method 2032 2033.. method:: str.splitlines(keepends=False) 2034 2035 Return a list of the lines in the string, breaking at line boundaries. Line 2036 breaks are not included in the resulting list unless *keepends* is given and 2037 true. 2038 2039 This method splits on the following line boundaries. In particular, the 2040 boundaries are a superset of :term:`universal newlines`. 2041 2042 +-----------------------+-----------------------------+ 2043 | Representation | Description | 2044 +=======================+=============================+ 2045 | ``\n`` | Line Feed | 2046 +-----------------------+-----------------------------+ 2047 | ``\r`` | Carriage Return | 2048 +-----------------------+-----------------------------+ 2049 | ``\r\n`` | Carriage Return + Line Feed | 2050 +-----------------------+-----------------------------+ 2051 | ``\v`` or ``\x0b`` | Line Tabulation | 2052 +-----------------------+-----------------------------+ 2053 | ``\f`` or ``\x0c`` | Form Feed | 2054 +-----------------------+-----------------------------+ 2055 | ``\x1c`` | File Separator | 2056 +-----------------------+-----------------------------+ 2057 | ``\x1d`` | Group Separator | 2058 +-----------------------+-----------------------------+ 2059 | ``\x1e`` | Record Separator | 2060 +-----------------------+-----------------------------+ 2061 | ``\x85`` | Next Line (C1 Control Code) | 2062 +-----------------------+-----------------------------+ 2063 | ``\u2028`` | Line Separator | 2064 +-----------------------+-----------------------------+ 2065 | ``\u2029`` | Paragraph Separator | 2066 +-----------------------+-----------------------------+ 2067 2068 .. versionchanged:: 3.2 2069 2070 ``\v`` and ``\f`` added to list of line boundaries. 2071 2072 For example:: 2073 2074 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines() 2075 ['ab c', '', 'de fg', 'kl'] 2076 >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) 2077 ['ab c\n', '\n', 'de fg\r', 'kl\r\n'] 2078 2079 Unlike :meth:`~str.split` when a delimiter string *sep* is given, this 2080 method returns an empty list for the empty string, and a terminal line 2081 break does not result in an extra line:: 2082 2083 >>> "".splitlines() 2084 [] 2085 >>> "One line\n".splitlines() 2086 ['One line'] 2087 2088 For comparison, ``split('\n')`` gives:: 2089 2090 >>> ''.split('\n') 2091 [''] 2092 >>> 'Two lines\n'.split('\n') 2093 ['Two lines', ''] 2094 2095 2096.. method:: str.startswith(prefix[, start[, end]]) 2097 2098 Return ``True`` if string starts with the *prefix*, otherwise return ``False``. 2099 *prefix* can also be a tuple of prefixes to look for. With optional *start*, 2100 test string beginning at that position. With optional *end*, stop comparing 2101 string at that position. 2102 2103 2104.. method:: str.strip([chars]) 2105 2106 Return a copy of the string with the leading and trailing characters removed. 2107 The *chars* argument is a string specifying the set of characters to be removed. 2108 If omitted or ``None``, the *chars* argument defaults to removing whitespace. 2109 The *chars* argument is not a prefix or suffix; rather, all combinations of its 2110 values are stripped:: 2111 2112 >>> ' spacious '.strip() 2113 'spacious' 2114 >>> 'www.example.com'.strip('cmowz.') 2115 'example' 2116 2117 The outermost leading and trailing *chars* argument values are stripped 2118 from the string. Characters are removed from the leading end until 2119 reaching a string character that is not contained in the set of 2120 characters in *chars*. A similar action takes place on the trailing end. 2121 For example:: 2122 2123 >>> comment_string = '#....... Section 3.2.1 Issue #32 .......' 2124 >>> comment_string.strip('.#! ') 2125 'Section 3.2.1 Issue #32' 2126 2127 2128.. method:: str.swapcase() 2129 2130 Return a copy of the string with uppercase characters converted to lowercase and 2131 vice versa. Note that it is not necessarily true that 2132 ``s.swapcase().swapcase() == s``. 2133 2134 2135.. method:: str.title() 2136 2137 Return a titlecased version of the string where words start with an uppercase 2138 character and the remaining characters are lowercase. 2139 2140 For example:: 2141 2142 >>> 'Hello world'.title() 2143 'Hello World' 2144 2145 The algorithm uses a simple language-independent definition of a word as 2146 groups of consecutive letters. The definition works in many contexts but 2147 it means that apostrophes in contractions and possessives form word 2148 boundaries, which may not be the desired result:: 2149 2150 >>> "they're bill's friends from the UK".title() 2151 "They'Re Bill'S Friends From The Uk" 2152 2153 A workaround for apostrophes can be constructed using regular expressions:: 2154 2155 >>> import re 2156 >>> def titlecase(s): 2157 ... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", 2158 ... lambda mo: mo.group(0).capitalize(), 2159 ... s) 2160 ... 2161 >>> titlecase("they're bill's friends.") 2162 "They're Bill's Friends." 2163 2164 2165.. method:: str.translate(table) 2166 2167 Return a copy of the string in which each character has been mapped through 2168 the given translation table. The table must be an object that implements 2169 indexing via :meth:`__getitem__`, typically a :term:`mapping` or 2170 :term:`sequence`. When indexed by a Unicode ordinal (an integer), the 2171 table object can do any of the following: return a Unicode ordinal or a 2172 string, to map the character to one or more other characters; return 2173 ``None``, to delete the character from the return string; or raise a 2174 :exc:`LookupError` exception, to map the character to itself. 2175 2176 You can use :meth:`str.maketrans` to create a translation map from 2177 character-to-character mappings in different formats. 2178 2179 See also the :mod:`codecs` module for a more flexible approach to custom 2180 character mappings. 2181 2182 2183.. method:: str.upper() 2184 2185 Return a copy of the string with all the cased characters [4]_ converted to 2186 uppercase. Note that ``s.upper().isupper()`` might be ``False`` if ``s`` 2187 contains uncased characters or if the Unicode category of the resulting 2188 character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, 2189 titlecase). 2190 2191 The uppercasing algorithm used is described in section 3.13 of the Unicode 2192 Standard. 2193 2194 2195.. method:: str.zfill(width) 2196 2197 Return a copy of the string left filled with ASCII ``'0'`` digits to 2198 make a string of length *width*. A leading sign prefix (``'+'``/``'-'``) 2199 is handled by inserting the padding *after* the sign character rather 2200 than before. The original string is returned if *width* is less than 2201 or equal to ``len(s)``. 2202 2203 For example:: 2204 2205 >>> "42".zfill(5) 2206 '00042' 2207 >>> "-42".zfill(5) 2208 '-0042' 2209 2210 2211 2212.. _old-string-formatting: 2213 2214``printf``-style String Formatting 2215---------------------------------- 2216 2217.. index:: 2218 single: formatting, string (%) 2219 single: interpolation, string (%) 2220 single: string; formatting, printf 2221 single: string; interpolation, printf 2222 single: printf-style formatting 2223 single: sprintf-style formatting 2224 single: % (percent); printf-style formatting 2225 2226.. note:: 2227 2228 The formatting operations described here exhibit a variety of quirks that 2229 lead to a number of common errors (such as failing to display tuples and 2230 dictionaries correctly). Using the newer :ref:`formatted string literals 2231 <f-strings>`, the :meth:`str.format` interface, or :ref:`template strings 2232 <template-strings>` may help avoid these errors. Each of these 2233 alternatives provides their own trade-offs and benefits of simplicity, 2234 flexibility, and/or extensibility. 2235 2236String objects have one unique built-in operation: the ``%`` operator (modulo). 2237This is also known as the string *formatting* or *interpolation* operator. 2238Given ``format % values`` (where *format* is a string), ``%`` conversion 2239specifications in *format* are replaced with zero or more elements of *values*. 2240The effect is similar to using the :c:func:`sprintf` in the C language. 2241 2242If *format* requires a single argument, *values* may be a single non-tuple 2243object. [5]_ Otherwise, *values* must be a tuple with exactly the number of 2244items specified by the format string, or a single mapping object (for example, a 2245dictionary). 2246 2247.. index:: 2248 single: () (parentheses); in printf-style formatting 2249 single: * (asterisk); in printf-style formatting 2250 single: . (dot); in printf-style formatting 2251 2252A conversion specifier contains two or more characters and has the following 2253components, which must occur in this order: 2254 2255#. The ``'%'`` character, which marks the start of the specifier. 2256 2257#. Mapping key (optional), consisting of a parenthesised sequence of characters 2258 (for example, ``(somename)``). 2259 2260#. Conversion flags (optional), which affect the result of some conversion 2261 types. 2262 2263#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the 2264 actual width is read from the next element of the tuple in *values*, and the 2265 object to convert comes after the minimum field width and optional precision. 2266 2267#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If 2268 specified as ``'*'`` (an asterisk), the actual precision is read from the next 2269 element of the tuple in *values*, and the value to convert comes after the 2270 precision. 2271 2272#. Length modifier (optional). 2273 2274#. Conversion type. 2275 2276When the right argument is a dictionary (or other mapping type), then the 2277formats in the string *must* include a parenthesised mapping key into that 2278dictionary inserted immediately after the ``'%'`` character. The mapping key 2279selects the value to be formatted from the mapping. For example: 2280 2281 >>> print('%(language)s has %(number)03d quote types.' % 2282 ... {'language': "Python", "number": 2}) 2283 Python has 002 quote types. 2284 2285In this case no ``*`` specifiers may occur in a format (since they require a 2286sequential parameter list). 2287 2288The conversion flag characters are: 2289 2290.. index:: 2291 single: # (hash); in printf-style formatting 2292 single: - (minus); in printf-style formatting 2293 single: + (plus); in printf-style formatting 2294 single: space; in printf-style formatting 2295 2296+---------+---------------------------------------------------------------------+ 2297| Flag | Meaning | 2298+=========+=====================================================================+ 2299| ``'#'`` | The value conversion will use the "alternate form" (where defined | 2300| | below). | 2301+---------+---------------------------------------------------------------------+ 2302| ``'0'`` | The conversion will be zero padded for numeric values. | 2303+---------+---------------------------------------------------------------------+ 2304| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | 2305| | conversion if both are given). | 2306+---------+---------------------------------------------------------------------+ 2307| ``' '`` | (a space) A blank should be left before a positive number (or empty | 2308| | string) produced by a signed conversion. | 2309+---------+---------------------------------------------------------------------+ 2310| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | 2311| | (overrides a "space" flag). | 2312+---------+---------------------------------------------------------------------+ 2313 2314A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it 2315is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. 2316 2317The conversion types are: 2318 2319+------------+-----------------------------------------------------+-------+ 2320| Conversion | Meaning | Notes | 2321+============+=====================================================+=======+ 2322| ``'d'`` | Signed integer decimal. | | 2323+------------+-----------------------------------------------------+-------+ 2324| ``'i'`` | Signed integer decimal. | | 2325+------------+-----------------------------------------------------+-------+ 2326| ``'o'`` | Signed octal value. | \(1) | 2327+------------+-----------------------------------------------------+-------+ 2328| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(6) | 2329+------------+-----------------------------------------------------+-------+ 2330| ``'x'`` | Signed hexadecimal (lowercase). | \(2) | 2331+------------+-----------------------------------------------------+-------+ 2332| ``'X'`` | Signed hexadecimal (uppercase). | \(2) | 2333+------------+-----------------------------------------------------+-------+ 2334| ``'e'`` | Floating point exponential format (lowercase). | \(3) | 2335+------------+-----------------------------------------------------+-------+ 2336| ``'E'`` | Floating point exponential format (uppercase). | \(3) | 2337+------------+-----------------------------------------------------+-------+ 2338| ``'f'`` | Floating point decimal format. | \(3) | 2339+------------+-----------------------------------------------------+-------+ 2340| ``'F'`` | Floating point decimal format. | \(3) | 2341+------------+-----------------------------------------------------+-------+ 2342| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | 2343| | format if exponent is less than -4 or not less than | | 2344| | precision, decimal format otherwise. | | 2345+------------+-----------------------------------------------------+-------+ 2346| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | 2347| | format if exponent is less than -4 or not less than | | 2348| | precision, decimal format otherwise. | | 2349+------------+-----------------------------------------------------+-------+ 2350| ``'c'`` | Single character (accepts integer or single | | 2351| | character string). | | 2352+------------+-----------------------------------------------------+-------+ 2353| ``'r'`` | String (converts any Python object using | \(5) | 2354| | :func:`repr`). | | 2355+------------+-----------------------------------------------------+-------+ 2356| ``'s'`` | String (converts any Python object using | \(5) | 2357| | :func:`str`). | | 2358+------------+-----------------------------------------------------+-------+ 2359| ``'a'`` | String (converts any Python object using | \(5) | 2360| | :func:`ascii`). | | 2361+------------+-----------------------------------------------------+-------+ 2362| ``'%'`` | No argument is converted, results in a ``'%'`` | | 2363| | character in the result. | | 2364+------------+-----------------------------------------------------+-------+ 2365 2366Notes: 2367 2368(1) 2369 The alternate form causes a leading octal specifier (``'0o'``) to be 2370 inserted before the first digit. 2371 2372(2) 2373 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether 2374 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit. 2375 2376(3) 2377 The alternate form causes the result to always contain a decimal point, even if 2378 no digits follow it. 2379 2380 The precision determines the number of digits after the decimal point and 2381 defaults to 6. 2382 2383(4) 2384 The alternate form causes the result to always contain a decimal point, and 2385 trailing zeroes are not removed as they would otherwise be. 2386 2387 The precision determines the number of significant digits before and after the 2388 decimal point and defaults to 6. 2389 2390(5) 2391 If precision is ``N``, the output is truncated to ``N`` characters. 2392 2393(6) 2394 See :pep:`237`. 2395 2396Since Python strings have an explicit length, ``%s`` conversions do not assume 2397that ``'\0'`` is the end of the string. 2398 2399.. XXX Examples? 2400 2401.. versionchanged:: 3.1 2402 ``%f`` conversions for numbers whose absolute value is over 1e50 are no 2403 longer replaced by ``%g`` conversions. 2404 2405 2406.. index:: 2407 single: buffer protocol; binary sequence types 2408 2409.. _binaryseq: 2410 2411Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview` 2412================================================================================= 2413 2414.. index:: 2415 object: bytes 2416 object: bytearray 2417 object: memoryview 2418 module: array 2419 2420The core built-in types for manipulating binary data are :class:`bytes` and 2421:class:`bytearray`. They are supported by :class:`memoryview` which uses 2422the :ref:`buffer protocol <bufferobjects>` to access the memory of other 2423binary objects without needing to make a copy. 2424 2425The :mod:`array` module supports efficient storage of basic data types like 242632-bit integers and IEEE754 double-precision floating values. 2427 2428.. _typebytes: 2429 2430Bytes Objects 2431------------- 2432 2433.. index:: object: bytes 2434 2435Bytes objects are immutable sequences of single bytes. Since many major 2436binary protocols are based on the ASCII text encoding, bytes objects offer 2437several methods that are only valid when working with ASCII compatible 2438data and are closely related to string objects in a variety of other ways. 2439 2440.. class:: bytes([source[, encoding[, errors]]]) 2441 2442 Firstly, the syntax for bytes literals is largely the same as that for string 2443 literals, except that a ``b`` prefix is added: 2444 2445 * Single quotes: ``b'still allows embedded "double" quotes'`` 2446 * Double quotes: ``b"still allows embedded 'single' quotes"`` 2447 * Triple quoted: ``b'''3 single quotes'''``, ``b"""3 double quotes"""`` 2448 2449 Only ASCII characters are permitted in bytes literals (regardless of the 2450 declared source code encoding). Any binary values over 127 must be entered 2451 into bytes literals using the appropriate escape sequence. 2452 2453 As with string literals, bytes literals may also use a ``r`` prefix to disable 2454 processing of escape sequences. See :ref:`strings` for more about the various 2455 forms of bytes literal, including supported escape sequences. 2456 2457 While bytes literals and representations are based on ASCII text, bytes 2458 objects actually behave like immutable sequences of integers, with each 2459 value in the sequence restricted such that ``0 <= x < 256`` (attempts to 2460 violate this restriction will trigger :exc:`ValueError`). This is done 2461 deliberately to emphasise that while many binary formats include ASCII based 2462 elements and can be usefully manipulated with some text-oriented algorithms, 2463 this is not generally the case for arbitrary binary data (blindly applying 2464 text processing algorithms to binary data formats that are not ASCII 2465 compatible will usually lead to data corruption). 2466 2467 In addition to the literal forms, bytes objects can be created in a number of 2468 other ways: 2469 2470 * A zero-filled bytes object of a specified length: ``bytes(10)`` 2471 * From an iterable of integers: ``bytes(range(20))`` 2472 * Copying existing binary data via the buffer protocol: ``bytes(obj)`` 2473 2474 Also see the :ref:`bytes <func-bytes>` built-in. 2475 2476 Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal 2477 numbers are a commonly used format for describing binary data. Accordingly, 2478 the bytes type has an additional class method to read data in that format: 2479 2480 .. classmethod:: fromhex(string) 2481 2482 This :class:`bytes` class method returns a bytes object, decoding the 2483 given string object. The string must contain two hexadecimal digits per 2484 byte, with ASCII whitespace being ignored. 2485 2486 >>> bytes.fromhex('2Ef0 F1f2 ') 2487 b'.\xf0\xf1\xf2' 2488 2489 .. versionchanged:: 3.7 2490 :meth:`bytes.fromhex` now skips all ASCII whitespace in the string, 2491 not just spaces. 2492 2493 A reverse conversion function exists to transform a bytes object into its 2494 hexadecimal representation. 2495 2496 .. method:: hex([sep[, bytes_per_sep]]) 2497 2498 Return a string object containing two hexadecimal digits for each 2499 byte in the instance. 2500 2501 >>> b'\xf0\xf1\xf2'.hex() 2502 'f0f1f2' 2503 2504 If you want to make the hex string easier to read, you can specify a 2505 single character separator *sep* parameter to include in the output. 2506 By default between each byte. A second optional *bytes_per_sep* 2507 parameter controls the spacing. Positive values calculate the 2508 separator position from the right, negative values from the left. 2509 2510 >>> value = b'\xf0\xf1\xf2' 2511 >>> value.hex('-') 2512 'f0-f1-f2' 2513 >>> value.hex('_', 2) 2514 'f0_f1f2' 2515 >>> b'UUDDLRLRAB'.hex(' ', -4) 2516 '55554444 4c524c52 4142' 2517 2518 .. versionadded:: 3.5 2519 2520 .. versionchanged:: 3.8 2521 :meth:`bytes.hex` now supports optional *sep* and *bytes_per_sep* 2522 parameters to insert separators between bytes in the hex output. 2523 2524Since bytes objects are sequences of integers (akin to a tuple), for a bytes 2525object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes 2526object of length 1. (This contrasts with text strings, where both indexing 2527and slicing will produce a string of length 1) 2528 2529The representation of bytes objects uses the literal format (``b'...'``) 2530since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can 2531always convert a bytes object into a list of integers using ``list(b)``. 2532 2533.. note:: 2534 For Python 2.x users: In the Python 2.x series, a variety of implicit 2535 conversions between 8-bit strings (the closest thing 2.x offers to a 2536 built-in binary data type) and Unicode strings were permitted. This was a 2537 backwards compatibility workaround to account for the fact that Python 2538 originally only supported 8-bit text, and Unicode text was a later 2539 addition. In Python 3.x, those implicit conversions are gone - conversions 2540 between 8-bit binary data and Unicode text must be explicit, and bytes and 2541 string objects will always compare unequal. 2542 2543 2544.. _typebytearray: 2545 2546Bytearray Objects 2547----------------- 2548 2549.. index:: object: bytearray 2550 2551:class:`bytearray` objects are a mutable counterpart to :class:`bytes` 2552objects. 2553 2554.. class:: bytearray([source[, encoding[, errors]]]) 2555 2556 There is no dedicated literal syntax for bytearray objects, instead 2557 they are always created by calling the constructor: 2558 2559 * Creating an empty instance: ``bytearray()`` 2560 * Creating a zero-filled instance with a given length: ``bytearray(10)`` 2561 * From an iterable of integers: ``bytearray(range(20))`` 2562 * Copying existing binary data via the buffer protocol: ``bytearray(b'Hi!')`` 2563 2564 As bytearray objects are mutable, they support the 2565 :ref:`mutable <typesseq-mutable>` sequence operations in addition to the 2566 common bytes and bytearray operations described in :ref:`bytes-methods`. 2567 2568 Also see the :ref:`bytearray <func-bytearray>` built-in. 2569 2570 Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal 2571 numbers are a commonly used format for describing binary data. Accordingly, 2572 the bytearray type has an additional class method to read data in that format: 2573 2574 .. classmethod:: fromhex(string) 2575 2576 This :class:`bytearray` class method returns bytearray object, decoding 2577 the given string object. The string must contain two hexadecimal digits 2578 per byte, with ASCII whitespace being ignored. 2579 2580 >>> bytearray.fromhex('2Ef0 F1f2 ') 2581 bytearray(b'.\xf0\xf1\xf2') 2582 2583 .. versionchanged:: 3.7 2584 :meth:`bytearray.fromhex` now skips all ASCII whitespace in the string, 2585 not just spaces. 2586 2587 A reverse conversion function exists to transform a bytearray object into its 2588 hexadecimal representation. 2589 2590 .. method:: hex([sep[, bytes_per_sep]]) 2591 2592 Return a string object containing two hexadecimal digits for each 2593 byte in the instance. 2594 2595 >>> bytearray(b'\xf0\xf1\xf2').hex() 2596 'f0f1f2' 2597 2598 .. versionadded:: 3.5 2599 2600 .. versionchanged:: 3.8 2601 Similar to :meth:`bytes.hex`, :meth:`bytearray.hex` now supports 2602 optional *sep* and *bytes_per_sep* parameters to insert separators 2603 between bytes in the hex output. 2604 2605Since bytearray objects are sequences of integers (akin to a list), for a 2606bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be 2607a bytearray object of length 1. (This contrasts with text strings, where 2608both indexing and slicing will produce a string of length 1) 2609 2610The representation of bytearray objects uses the bytes literal format 2611(``bytearray(b'...')``) since it is often more useful than e.g. 2612``bytearray([46, 46, 46])``. You can always convert a bytearray object into 2613a list of integers using ``list(b)``. 2614 2615 2616.. _bytes-methods: 2617 2618Bytes and Bytearray Operations 2619------------------------------ 2620 2621.. index:: pair: bytes; methods 2622 pair: bytearray; methods 2623 2624Both bytes and bytearray objects support the :ref:`common <typesseq-common>` 2625sequence operations. They interoperate not just with operands of the same 2626type, but with any :term:`bytes-like object`. Due to this flexibility, they can be 2627freely mixed in operations without causing errors. However, the return type 2628of the result may depend on the order of operands. 2629 2630.. note:: 2631 2632 The methods on bytes and bytearray objects don't accept strings as their 2633 arguments, just as the methods on strings don't accept bytes as their 2634 arguments. For example, you have to write:: 2635 2636 a = "abc" 2637 b = a.replace("a", "f") 2638 2639 and:: 2640 2641 a = b"abc" 2642 b = a.replace(b"a", b"f") 2643 2644Some bytes and bytearray operations assume the use of ASCII compatible 2645binary formats, and hence should be avoided when working with arbitrary 2646binary data. These restrictions are covered below. 2647 2648.. note:: 2649 Using these ASCII based operations to manipulate binary data that is not 2650 stored in an ASCII based format may lead to data corruption. 2651 2652The following methods on bytes and bytearray objects can be used with 2653arbitrary binary data. 2654 2655.. method:: bytes.count(sub[, start[, end]]) 2656 bytearray.count(sub[, start[, end]]) 2657 2658 Return the number of non-overlapping occurrences of subsequence *sub* in 2659 the range [*start*, *end*]. Optional arguments *start* and *end* are 2660 interpreted as in slice notation. 2661 2662 The subsequence to search for may be any :term:`bytes-like object` or an 2663 integer in the range 0 to 255. 2664 2665 .. versionchanged:: 3.3 2666 Also accept an integer in the range 0 to 255 as the subsequence. 2667 2668 2669.. method:: bytes.removeprefix(prefix, /) 2670 bytearray.removeprefix(prefix, /) 2671 2672 If the binary data starts with the *prefix* string, return 2673 ``bytes[len(prefix):]``. Otherwise, return a copy of the original 2674 binary data:: 2675 2676 >>> b'TestHook'.removeprefix(b'Test') 2677 b'Hook' 2678 >>> b'BaseTestCase'.removeprefix(b'Test') 2679 b'BaseTestCase' 2680 2681 The *prefix* may be any :term:`bytes-like object`. 2682 2683 .. note:: 2684 2685 The bytearray version of this method does *not* operate in place - 2686 it always produces a new object, even if no changes were made. 2687 2688 .. versionadded:: 3.9 2689 2690 2691.. method:: bytes.removesuffix(suffix, /) 2692 bytearray.removesuffix(suffix, /) 2693 2694 If the binary data ends with the *suffix* string and that *suffix* is 2695 not empty, return ``bytes[:-len(suffix)]``. Otherwise, return a copy of 2696 the original binary data:: 2697 2698 >>> b'MiscTests'.removesuffix(b'Tests') 2699 b'Misc' 2700 >>> b'TmpDirMixin'.removesuffix(b'Tests') 2701 b'TmpDirMixin' 2702 2703 The *suffix* may be any :term:`bytes-like object`. 2704 2705 .. note:: 2706 2707 The bytearray version of this method does *not* operate in place - 2708 it always produces a new object, even if no changes were made. 2709 2710 .. versionadded:: 3.9 2711 2712 2713.. method:: bytes.decode(encoding="utf-8", errors="strict") 2714 bytearray.decode(encoding="utf-8", errors="strict") 2715 2716 Return a string decoded from the given bytes. Default encoding is 2717 ``'utf-8'``. *errors* may be given to set a different 2718 error handling scheme. The default for *errors* is ``'strict'``, meaning 2719 that encoding errors raise a :exc:`UnicodeError`. Other possible values are 2720 ``'ignore'``, ``'replace'`` and any other name registered via 2721 :func:`codecs.register_error`, see section :ref:`error-handlers`. For a 2722 list of possible encodings, see section :ref:`standard-encodings`. 2723 2724 By default, the *errors* argument is not checked for best performances, but 2725 only used at the first decoding error. Enable the :ref:`Python Development 2726 Mode <devmode>`, or use a :ref:`debug build <debug-build>` to check *errors*. 2727 2728 .. note:: 2729 2730 Passing the *encoding* argument to :class:`str` allows decoding any 2731 :term:`bytes-like object` directly, without needing to make a temporary 2732 bytes or bytearray object. 2733 2734 .. versionchanged:: 3.1 2735 Added support for keyword arguments. 2736 2737 .. versionchanged:: 3.9 2738 The *errors* is now checked in development mode and 2739 in :ref:`debug mode <debug-build>`. 2740 2741 2742.. method:: bytes.endswith(suffix[, start[, end]]) 2743 bytearray.endswith(suffix[, start[, end]]) 2744 2745 Return ``True`` if the binary data ends with the specified *suffix*, 2746 otherwise return ``False``. *suffix* can also be a tuple of suffixes to 2747 look for. With optional *start*, test beginning at that position. With 2748 optional *end*, stop comparing at that position. 2749 2750 The suffix(es) to search for may be any :term:`bytes-like object`. 2751 2752 2753.. method:: bytes.find(sub[, start[, end]]) 2754 bytearray.find(sub[, start[, end]]) 2755 2756 Return the lowest index in the data where the subsequence *sub* is found, 2757 such that *sub* is contained in the slice ``s[start:end]``. Optional 2758 arguments *start* and *end* are interpreted as in slice notation. Return 2759 ``-1`` if *sub* is not found. 2760 2761 The subsequence to search for may be any :term:`bytes-like object` or an 2762 integer in the range 0 to 255. 2763 2764 .. note:: 2765 2766 The :meth:`~bytes.find` method should be used only if you need to know the 2767 position of *sub*. To check if *sub* is a substring or not, use the 2768 :keyword:`in` operator:: 2769 2770 >>> b'Py' in b'Python' 2771 True 2772 2773 .. versionchanged:: 3.3 2774 Also accept an integer in the range 0 to 255 as the subsequence. 2775 2776 2777.. method:: bytes.index(sub[, start[, end]]) 2778 bytearray.index(sub[, start[, end]]) 2779 2780 Like :meth:`~bytes.find`, but raise :exc:`ValueError` when the 2781 subsequence is not found. 2782 2783 The subsequence to search for may be any :term:`bytes-like object` or an 2784 integer in the range 0 to 255. 2785 2786 .. versionchanged:: 3.3 2787 Also accept an integer in the range 0 to 255 as the subsequence. 2788 2789 2790.. method:: bytes.join(iterable) 2791 bytearray.join(iterable) 2792 2793 Return a bytes or bytearray object which is the concatenation of the 2794 binary data sequences in *iterable*. A :exc:`TypeError` will be raised 2795 if there are any values in *iterable* that are not :term:`bytes-like 2796 objects <bytes-like object>`, including :class:`str` objects. The 2797 separator between elements is the contents of the bytes or 2798 bytearray object providing this method. 2799 2800 2801.. staticmethod:: bytes.maketrans(from, to) 2802 bytearray.maketrans(from, to) 2803 2804 This static method returns a translation table usable for 2805 :meth:`bytes.translate` that will map each character in *from* into the 2806 character at the same position in *to*; *from* and *to* must both be 2807 :term:`bytes-like objects <bytes-like object>` and have the same length. 2808 2809 .. versionadded:: 3.1 2810 2811 2812.. method:: bytes.partition(sep) 2813 bytearray.partition(sep) 2814 2815 Split the sequence at the first occurrence of *sep*, and return a 3-tuple 2816 containing the part before the separator, the separator itself or its 2817 bytearray copy, and the part after the separator. 2818 If the separator is not found, return a 3-tuple 2819 containing a copy of the original sequence, followed by two empty bytes or 2820 bytearray objects. 2821 2822 The separator to search for may be any :term:`bytes-like object`. 2823 2824 2825.. method:: bytes.replace(old, new[, count]) 2826 bytearray.replace(old, new[, count]) 2827 2828 Return a copy of the sequence with all occurrences of subsequence *old* 2829 replaced by *new*. If the optional argument *count* is given, only the 2830 first *count* occurrences are replaced. 2831 2832 The subsequence to search for and its replacement may be any 2833 :term:`bytes-like object`. 2834 2835 .. note:: 2836 2837 The bytearray version of this method does *not* operate in place - it 2838 always produces a new object, even if no changes were made. 2839 2840 2841.. method:: bytes.rfind(sub[, start[, end]]) 2842 bytearray.rfind(sub[, start[, end]]) 2843 2844 Return the highest index in the sequence where the subsequence *sub* is 2845 found, such that *sub* is contained within ``s[start:end]``. Optional 2846 arguments *start* and *end* are interpreted as in slice notation. Return 2847 ``-1`` on failure. 2848 2849 The subsequence to search for may be any :term:`bytes-like object` or an 2850 integer in the range 0 to 255. 2851 2852 .. versionchanged:: 3.3 2853 Also accept an integer in the range 0 to 255 as the subsequence. 2854 2855 2856.. method:: bytes.rindex(sub[, start[, end]]) 2857 bytearray.rindex(sub[, start[, end]]) 2858 2859 Like :meth:`~bytes.rfind` but raises :exc:`ValueError` when the 2860 subsequence *sub* is not found. 2861 2862 The subsequence to search for may be any :term:`bytes-like object` or an 2863 integer in the range 0 to 255. 2864 2865 .. versionchanged:: 3.3 2866 Also accept an integer in the range 0 to 255 as the subsequence. 2867 2868 2869.. method:: bytes.rpartition(sep) 2870 bytearray.rpartition(sep) 2871 2872 Split the sequence at the last occurrence of *sep*, and return a 3-tuple 2873 containing the part before the separator, the separator itself or its 2874 bytearray copy, and the part after the separator. 2875 If the separator is not found, return a 3-tuple 2876 containing two empty bytes or bytearray objects, followed by a copy of the 2877 original sequence. 2878 2879 The separator to search for may be any :term:`bytes-like object`. 2880 2881 2882.. method:: bytes.startswith(prefix[, start[, end]]) 2883 bytearray.startswith(prefix[, start[, end]]) 2884 2885 Return ``True`` if the binary data starts with the specified *prefix*, 2886 otherwise return ``False``. *prefix* can also be a tuple of prefixes to 2887 look for. With optional *start*, test beginning at that position. With 2888 optional *end*, stop comparing at that position. 2889 2890 The prefix(es) to search for may be any :term:`bytes-like object`. 2891 2892 2893.. method:: bytes.translate(table, /, delete=b'') 2894 bytearray.translate(table, /, delete=b'') 2895 2896 Return a copy of the bytes or bytearray object where all bytes occurring in 2897 the optional argument *delete* are removed, and the remaining bytes have 2898 been mapped through the given translation table, which must be a bytes 2899 object of length 256. 2900 2901 You can use the :func:`bytes.maketrans` method to create a translation 2902 table. 2903 2904 Set the *table* argument to ``None`` for translations that only delete 2905 characters:: 2906 2907 >>> b'read this short text'.translate(None, b'aeiou') 2908 b'rd ths shrt txt' 2909 2910 .. versionchanged:: 3.6 2911 *delete* is now supported as a keyword argument. 2912 2913 2914The following methods on bytes and bytearray objects have default behaviours 2915that assume the use of ASCII compatible binary formats, but can still be used 2916with arbitrary binary data by passing appropriate arguments. Note that all of 2917the bytearray methods in this section do *not* operate in place, and instead 2918produce new objects. 2919 2920.. method:: bytes.center(width[, fillbyte]) 2921 bytearray.center(width[, fillbyte]) 2922 2923 Return a copy of the object centered in a sequence of length *width*. 2924 Padding is done using the specified *fillbyte* (default is an ASCII 2925 space). For :class:`bytes` objects, the original sequence is returned if 2926 *width* is less than or equal to ``len(s)``. 2927 2928 .. note:: 2929 2930 The bytearray version of this method does *not* operate in place - 2931 it always produces a new object, even if no changes were made. 2932 2933 2934.. method:: bytes.ljust(width[, fillbyte]) 2935 bytearray.ljust(width[, fillbyte]) 2936 2937 Return a copy of the object left justified in a sequence of length *width*. 2938 Padding is done using the specified *fillbyte* (default is an ASCII 2939 space). For :class:`bytes` objects, the original sequence is returned if 2940 *width* is less than or equal to ``len(s)``. 2941 2942 .. note:: 2943 2944 The bytearray version of this method does *not* operate in place - 2945 it always produces a new object, even if no changes were made. 2946 2947 2948.. method:: bytes.lstrip([chars]) 2949 bytearray.lstrip([chars]) 2950 2951 Return a copy of the sequence with specified leading bytes removed. The 2952 *chars* argument is a binary sequence specifying the set of byte values to 2953 be removed - the name refers to the fact this method is usually used with 2954 ASCII characters. If omitted or ``None``, the *chars* argument defaults 2955 to removing ASCII whitespace. The *chars* argument is not a prefix; 2956 rather, all combinations of its values are stripped:: 2957 2958 >>> b' spacious '.lstrip() 2959 b'spacious ' 2960 >>> b'www.example.com'.lstrip(b'cmowz.') 2961 b'example.com' 2962 2963 The binary sequence of byte values to remove may be any 2964 :term:`bytes-like object`. See :meth:`~bytes.removeprefix` for a method 2965 that will remove a single prefix string rather than all of a set of 2966 characters. For example:: 2967 2968 >>> b'Arthur: three!'.lstrip(b'Arthur: ') 2969 b'ee!' 2970 >>> b'Arthur: three!'.removeprefix(b'Arthur: ') 2971 b'three!' 2972 2973 .. note:: 2974 2975 The bytearray version of this method does *not* operate in place - 2976 it always produces a new object, even if no changes were made. 2977 2978 2979.. method:: bytes.rjust(width[, fillbyte]) 2980 bytearray.rjust(width[, fillbyte]) 2981 2982 Return a copy of the object right justified in a sequence of length *width*. 2983 Padding is done using the specified *fillbyte* (default is an ASCII 2984 space). For :class:`bytes` objects, the original sequence is returned if 2985 *width* is less than or equal to ``len(s)``. 2986 2987 .. note:: 2988 2989 The bytearray version of this method does *not* operate in place - 2990 it always produces a new object, even if no changes were made. 2991 2992 2993.. method:: bytes.rsplit(sep=None, maxsplit=-1) 2994 bytearray.rsplit(sep=None, maxsplit=-1) 2995 2996 Split the binary sequence into subsequences of the same type, using *sep* 2997 as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits 2998 are done, the *rightmost* ones. If *sep* is not specified or ``None``, 2999 any subsequence consisting solely of ASCII whitespace is a separator. 3000 Except for splitting from the right, :meth:`rsplit` behaves like 3001 :meth:`split` which is described in detail below. 3002 3003 3004.. method:: bytes.rstrip([chars]) 3005 bytearray.rstrip([chars]) 3006 3007 Return a copy of the sequence with specified trailing bytes removed. The 3008 *chars* argument is a binary sequence specifying the set of byte values to 3009 be removed - the name refers to the fact this method is usually used with 3010 ASCII characters. If omitted or ``None``, the *chars* argument defaults to 3011 removing ASCII whitespace. The *chars* argument is not a suffix; rather, 3012 all combinations of its values are stripped:: 3013 3014 >>> b' spacious '.rstrip() 3015 b' spacious' 3016 >>> b'mississippi'.rstrip(b'ipz') 3017 b'mississ' 3018 3019 The binary sequence of byte values to remove may be any 3020 :term:`bytes-like object`. See :meth:`~bytes.removesuffix` for a method 3021 that will remove a single suffix string rather than all of a set of 3022 characters. For example:: 3023 3024 >>> b'Monty Python'.rstrip(b' Python') 3025 b'M' 3026 >>> b'Monty Python'.removesuffix(b' Python') 3027 b'Monty' 3028 3029 .. note:: 3030 3031 The bytearray version of this method does *not* operate in place - 3032 it always produces a new object, even if no changes were made. 3033 3034 3035.. method:: bytes.split(sep=None, maxsplit=-1) 3036 bytearray.split(sep=None, maxsplit=-1) 3037 3038 Split the binary sequence into subsequences of the same type, using *sep* 3039 as the delimiter string. If *maxsplit* is given and non-negative, at most 3040 *maxsplit* splits are done (thus, the list will have at most ``maxsplit+1`` 3041 elements). If *maxsplit* is not specified or is ``-1``, then there is no 3042 limit on the number of splits (all possible splits are made). 3043 3044 If *sep* is given, consecutive delimiters are not grouped together and are 3045 deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')`` 3046 returns ``[b'1', b'', b'2']``). The *sep* argument may consist of a 3047 multibyte sequence (for example, ``b'1<>2<>3'.split(b'<>')`` returns 3048 ``[b'1', b'2', b'3']``). Splitting an empty sequence with a specified 3049 separator returns ``[b'']`` or ``[bytearray(b'')]`` depending on the type 3050 of object being split. The *sep* argument may be any 3051 :term:`bytes-like object`. 3052 3053 For example:: 3054 3055 >>> b'1,2,3'.split(b',') 3056 [b'1', b'2', b'3'] 3057 >>> b'1,2,3'.split(b',', maxsplit=1) 3058 [b'1', b'2,3'] 3059 >>> b'1,2,,3,'.split(b',') 3060 [b'1', b'2', b'', b'3', b''] 3061 3062 If *sep* is not specified or is ``None``, a different splitting algorithm 3063 is applied: runs of consecutive ASCII whitespace are regarded as a single 3064 separator, and the result will contain no empty strings at the start or 3065 end if the sequence has leading or trailing whitespace. Consequently, 3066 splitting an empty sequence or a sequence consisting solely of ASCII 3067 whitespace without a specified separator returns ``[]``. 3068 3069 For example:: 3070 3071 3072 >>> b'1 2 3'.split() 3073 [b'1', b'2', b'3'] 3074 >>> b'1 2 3'.split(maxsplit=1) 3075 [b'1', b'2 3'] 3076 >>> b' 1 2 3 '.split() 3077 [b'1', b'2', b'3'] 3078 3079 3080.. method:: bytes.strip([chars]) 3081 bytearray.strip([chars]) 3082 3083 Return a copy of the sequence with specified leading and trailing bytes 3084 removed. The *chars* argument is a binary sequence specifying the set of 3085 byte values to be removed - the name refers to the fact this method is 3086 usually used with ASCII characters. If omitted or ``None``, the *chars* 3087 argument defaults to removing ASCII whitespace. The *chars* argument is 3088 not a prefix or suffix; rather, all combinations of its values are 3089 stripped:: 3090 3091 >>> b' spacious '.strip() 3092 b'spacious' 3093 >>> b'www.example.com'.strip(b'cmowz.') 3094 b'example' 3095 3096 The binary sequence of byte values to remove may be any 3097 :term:`bytes-like object`. 3098 3099 .. note:: 3100 3101 The bytearray version of this method does *not* operate in place - 3102 it always produces a new object, even if no changes were made. 3103 3104 3105The following methods on bytes and bytearray objects assume the use of ASCII 3106compatible binary formats and should not be applied to arbitrary binary data. 3107Note that all of the bytearray methods in this section do *not* operate in 3108place, and instead produce new objects. 3109 3110.. method:: bytes.capitalize() 3111 bytearray.capitalize() 3112 3113 Return a copy of the sequence with each byte interpreted as an ASCII 3114 character, and the first byte capitalized and the rest lowercased. 3115 Non-ASCII byte values are passed through unchanged. 3116 3117 .. note:: 3118 3119 The bytearray version of this method does *not* operate in place - it 3120 always produces a new object, even if no changes were made. 3121 3122 3123.. method:: bytes.expandtabs(tabsize=8) 3124 bytearray.expandtabs(tabsize=8) 3125 3126 Return a copy of the sequence where all ASCII tab characters are replaced 3127 by one or more ASCII spaces, depending on the current column and the given 3128 tab size. Tab positions occur every *tabsize* bytes (default is 8, 3129 giving tab positions at columns 0, 8, 16 and so on). To expand the 3130 sequence, the current column is set to zero and the sequence is examined 3131 byte by byte. If the byte is an ASCII tab character (``b'\t'``), one or 3132 more space characters are inserted in the result until the current column 3133 is equal to the next tab position. (The tab character itself is not 3134 copied.) If the current byte is an ASCII newline (``b'\n'``) or 3135 carriage return (``b'\r'``), it is copied and the current column is reset 3136 to zero. Any other byte value is copied unchanged and the current column 3137 is incremented by one regardless of how the byte value is represented when 3138 printed:: 3139 3140 >>> b'01\t012\t0123\t01234'.expandtabs() 3141 b'01 012 0123 01234' 3142 >>> b'01\t012\t0123\t01234'.expandtabs(4) 3143 b'01 012 0123 01234' 3144 3145 .. note:: 3146 3147 The bytearray version of this method does *not* operate in place - it 3148 always produces a new object, even if no changes were made. 3149 3150 3151.. method:: bytes.isalnum() 3152 bytearray.isalnum() 3153 3154 Return ``True`` if all bytes in the sequence are alphabetical ASCII characters 3155 or ASCII decimal digits and the sequence is not empty, ``False`` otherwise. 3156 Alphabetic ASCII characters are those byte values in the sequence 3157 ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. ASCII decimal 3158 digits are those byte values in the sequence ``b'0123456789'``. 3159 3160 For example:: 3161 3162 >>> b'ABCabc1'.isalnum() 3163 True 3164 >>> b'ABC abc1'.isalnum() 3165 False 3166 3167 3168.. method:: bytes.isalpha() 3169 bytearray.isalpha() 3170 3171 Return ``True`` if all bytes in the sequence are alphabetic ASCII characters 3172 and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII 3173 characters are those byte values in the sequence 3174 ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3175 3176 For example:: 3177 3178 >>> b'ABCabc'.isalpha() 3179 True 3180 >>> b'ABCabc1'.isalpha() 3181 False 3182 3183 3184.. method:: bytes.isascii() 3185 bytearray.isascii() 3186 3187 Return ``True`` if the sequence is empty or all bytes in the sequence are ASCII, 3188 ``False`` otherwise. 3189 ASCII bytes are in the range 0-0x7F. 3190 3191 .. versionadded:: 3.7 3192 3193 3194.. method:: bytes.isdigit() 3195 bytearray.isdigit() 3196 3197 Return ``True`` if all bytes in the sequence are ASCII decimal digits 3198 and the sequence is not empty, ``False`` otherwise. ASCII decimal digits are 3199 those byte values in the sequence ``b'0123456789'``. 3200 3201 For example:: 3202 3203 >>> b'1234'.isdigit() 3204 True 3205 >>> b'1.23'.isdigit() 3206 False 3207 3208 3209.. method:: bytes.islower() 3210 bytearray.islower() 3211 3212 Return ``True`` if there is at least one lowercase ASCII character 3213 in the sequence and no uppercase ASCII characters, ``False`` otherwise. 3214 3215 For example:: 3216 3217 >>> b'hello world'.islower() 3218 True 3219 >>> b'Hello world'.islower() 3220 False 3221 3222 Lowercase ASCII characters are those byte values in the sequence 3223 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters 3224 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3225 3226 3227.. method:: bytes.isspace() 3228 bytearray.isspace() 3229 3230 Return ``True`` if all bytes in the sequence are ASCII whitespace and the 3231 sequence is not empty, ``False`` otherwise. ASCII whitespace characters are 3232 those byte values in the sequence ``b' \t\n\r\x0b\f'`` (space, tab, newline, 3233 carriage return, vertical tab, form feed). 3234 3235 3236.. method:: bytes.istitle() 3237 bytearray.istitle() 3238 3239 Return ``True`` if the sequence is ASCII titlecase and the sequence is not 3240 empty, ``False`` otherwise. See :meth:`bytes.title` for more details on the 3241 definition of "titlecase". 3242 3243 For example:: 3244 3245 >>> b'Hello World'.istitle() 3246 True 3247 >>> b'Hello world'.istitle() 3248 False 3249 3250 3251.. method:: bytes.isupper() 3252 bytearray.isupper() 3253 3254 Return ``True`` if there is at least one uppercase alphabetic ASCII character 3255 in the sequence and no lowercase ASCII characters, ``False`` otherwise. 3256 3257 For example:: 3258 3259 >>> b'HELLO WORLD'.isupper() 3260 True 3261 >>> b'Hello world'.isupper() 3262 False 3263 3264 Lowercase ASCII characters are those byte values in the sequence 3265 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters 3266 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3267 3268 3269.. method:: bytes.lower() 3270 bytearray.lower() 3271 3272 Return a copy of the sequence with all the uppercase ASCII characters 3273 converted to their corresponding lowercase counterpart. 3274 3275 For example:: 3276 3277 >>> b'Hello World'.lower() 3278 b'hello world' 3279 3280 Lowercase ASCII characters are those byte values in the sequence 3281 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters 3282 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3283 3284 .. note:: 3285 3286 The bytearray version of this method does *not* operate in place - it 3287 always produces a new object, even if no changes were made. 3288 3289 3290.. index:: 3291 single: universal newlines; bytes.splitlines method 3292 single: universal newlines; bytearray.splitlines method 3293 3294.. method:: bytes.splitlines(keepends=False) 3295 bytearray.splitlines(keepends=False) 3296 3297 Return a list of the lines in the binary sequence, breaking at ASCII 3298 line boundaries. This method uses the :term:`universal newlines` approach 3299 to splitting lines. Line breaks are not included in the resulting list 3300 unless *keepends* is given and true. 3301 3302 For example:: 3303 3304 >>> b'ab c\n\nde fg\rkl\r\n'.splitlines() 3305 [b'ab c', b'', b'de fg', b'kl'] 3306 >>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True) 3307 [b'ab c\n', b'\n', b'de fg\r', b'kl\r\n'] 3308 3309 Unlike :meth:`~bytes.split` when a delimiter string *sep* is given, this 3310 method returns an empty list for the empty string, and a terminal line 3311 break does not result in an extra line:: 3312 3313 >>> b"".split(b'\n'), b"Two lines\n".split(b'\n') 3314 ([b''], [b'Two lines', b'']) 3315 >>> b"".splitlines(), b"One line\n".splitlines() 3316 ([], [b'One line']) 3317 3318 3319.. method:: bytes.swapcase() 3320 bytearray.swapcase() 3321 3322 Return a copy of the sequence with all the lowercase ASCII characters 3323 converted to their corresponding uppercase counterpart and vice-versa. 3324 3325 For example:: 3326 3327 >>> b'Hello World'.swapcase() 3328 b'hELLO wORLD' 3329 3330 Lowercase ASCII characters are those byte values in the sequence 3331 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters 3332 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3333 3334 Unlike :func:`str.swapcase()`, it is always the case that 3335 ``bin.swapcase().swapcase() == bin`` for the binary versions. Case 3336 conversions are symmetrical in ASCII, even though that is not generally 3337 true for arbitrary Unicode code points. 3338 3339 .. note:: 3340 3341 The bytearray version of this method does *not* operate in place - it 3342 always produces a new object, even if no changes were made. 3343 3344 3345.. method:: bytes.title() 3346 bytearray.title() 3347 3348 Return a titlecased version of the binary sequence where words start with 3349 an uppercase ASCII character and the remaining characters are lowercase. 3350 Uncased byte values are left unmodified. 3351 3352 For example:: 3353 3354 >>> b'Hello world'.title() 3355 b'Hello World' 3356 3357 Lowercase ASCII characters are those byte values in the sequence 3358 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters 3359 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3360 All other byte values are uncased. 3361 3362 The algorithm uses a simple language-independent definition of a word as 3363 groups of consecutive letters. The definition works in many contexts but 3364 it means that apostrophes in contractions and possessives form word 3365 boundaries, which may not be the desired result:: 3366 3367 >>> b"they're bill's friends from the UK".title() 3368 b"They'Re Bill'S Friends From The Uk" 3369 3370 A workaround for apostrophes can be constructed using regular expressions:: 3371 3372 >>> import re 3373 >>> def titlecase(s): 3374 ... return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?", 3375 ... lambda mo: mo.group(0)[0:1].upper() + 3376 ... mo.group(0)[1:].lower(), 3377 ... s) 3378 ... 3379 >>> titlecase(b"they're bill's friends.") 3380 b"They're Bill's Friends." 3381 3382 .. note:: 3383 3384 The bytearray version of this method does *not* operate in place - it 3385 always produces a new object, even if no changes were made. 3386 3387 3388.. method:: bytes.upper() 3389 bytearray.upper() 3390 3391 Return a copy of the sequence with all the lowercase ASCII characters 3392 converted to their corresponding uppercase counterpart. 3393 3394 For example:: 3395 3396 >>> b'Hello World'.upper() 3397 b'HELLO WORLD' 3398 3399 Lowercase ASCII characters are those byte values in the sequence 3400 ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters 3401 are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. 3402 3403 .. note:: 3404 3405 The bytearray version of this method does *not* operate in place - it 3406 always produces a new object, even if no changes were made. 3407 3408 3409.. method:: bytes.zfill(width) 3410 bytearray.zfill(width) 3411 3412 Return a copy of the sequence left filled with ASCII ``b'0'`` digits to 3413 make a sequence of length *width*. A leading sign prefix (``b'+'``/ 3414 ``b'-'``) is handled by inserting the padding *after* the sign character 3415 rather than before. For :class:`bytes` objects, the original sequence is 3416 returned if *width* is less than or equal to ``len(seq)``. 3417 3418 For example:: 3419 3420 >>> b"42".zfill(5) 3421 b'00042' 3422 >>> b"-42".zfill(5) 3423 b'-0042' 3424 3425 .. note:: 3426 3427 The bytearray version of this method does *not* operate in place - it 3428 always produces a new object, even if no changes were made. 3429 3430 3431.. _bytes-formatting: 3432 3433``printf``-style Bytes Formatting 3434---------------------------------- 3435 3436.. index:: 3437 single: formatting; bytes (%) 3438 single: formatting; bytearray (%) 3439 single: interpolation; bytes (%) 3440 single: interpolation; bytearray (%) 3441 single: bytes; formatting 3442 single: bytearray; formatting 3443 single: bytes; interpolation 3444 single: bytearray; interpolation 3445 single: printf-style formatting 3446 single: sprintf-style formatting 3447 single: % (percent); printf-style formatting 3448 3449.. note:: 3450 3451 The formatting operations described here exhibit a variety of quirks that 3452 lead to a number of common errors (such as failing to display tuples and 3453 dictionaries correctly). If the value being printed may be a tuple or 3454 dictionary, wrap it in a tuple. 3455 3456Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: 3457the ``%`` operator (modulo). 3458This is also known as the bytes *formatting* or *interpolation* operator. 3459Given ``format % values`` (where *format* is a bytes object), ``%`` conversion 3460specifications in *format* are replaced with zero or more elements of *values*. 3461The effect is similar to using the :c:func:`sprintf` in the C language. 3462 3463If *format* requires a single argument, *values* may be a single non-tuple 3464object. [5]_ Otherwise, *values* must be a tuple with exactly the number of 3465items specified by the format bytes object, or a single mapping object (for 3466example, a dictionary). 3467 3468.. index:: 3469 single: () (parentheses); in printf-style formatting 3470 single: * (asterisk); in printf-style formatting 3471 single: . (dot); in printf-style formatting 3472 3473A conversion specifier contains two or more characters and has the following 3474components, which must occur in this order: 3475 3476#. The ``'%'`` character, which marks the start of the specifier. 3477 3478#. Mapping key (optional), consisting of a parenthesised sequence of characters 3479 (for example, ``(somename)``). 3480 3481#. Conversion flags (optional), which affect the result of some conversion 3482 types. 3483 3484#. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the 3485 actual width is read from the next element of the tuple in *values*, and the 3486 object to convert comes after the minimum field width and optional precision. 3487 3488#. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If 3489 specified as ``'*'`` (an asterisk), the actual precision is read from the next 3490 element of the tuple in *values*, and the value to convert comes after the 3491 precision. 3492 3493#. Length modifier (optional). 3494 3495#. Conversion type. 3496 3497When the right argument is a dictionary (or other mapping type), then the 3498formats in the bytes object *must* include a parenthesised mapping key into that 3499dictionary inserted immediately after the ``'%'`` character. The mapping key 3500selects the value to be formatted from the mapping. For example: 3501 3502 >>> print(b'%(language)s has %(number)03d quote types.' % 3503 ... {b'language': b"Python", b"number": 2}) 3504 b'Python has 002 quote types.' 3505 3506In this case no ``*`` specifiers may occur in a format (since they require a 3507sequential parameter list). 3508 3509The conversion flag characters are: 3510 3511.. index:: 3512 single: # (hash); in printf-style formatting 3513 single: - (minus); in printf-style formatting 3514 single: + (plus); in printf-style formatting 3515 single: space; in printf-style formatting 3516 3517+---------+---------------------------------------------------------------------+ 3518| Flag | Meaning | 3519+=========+=====================================================================+ 3520| ``'#'`` | The value conversion will use the "alternate form" (where defined | 3521| | below). | 3522+---------+---------------------------------------------------------------------+ 3523| ``'0'`` | The conversion will be zero padded for numeric values. | 3524+---------+---------------------------------------------------------------------+ 3525| ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` | 3526| | conversion if both are given). | 3527+---------+---------------------------------------------------------------------+ 3528| ``' '`` | (a space) A blank should be left before a positive number (or empty | 3529| | string) produced by a signed conversion. | 3530+---------+---------------------------------------------------------------------+ 3531| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion | 3532| | (overrides a "space" flag). | 3533+---------+---------------------------------------------------------------------+ 3534 3535A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it 3536is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``. 3537 3538The conversion types are: 3539 3540+------------+-----------------------------------------------------+-------+ 3541| Conversion | Meaning | Notes | 3542+============+=====================================================+=======+ 3543| ``'d'`` | Signed integer decimal. | | 3544+------------+-----------------------------------------------------+-------+ 3545| ``'i'`` | Signed integer decimal. | | 3546+------------+-----------------------------------------------------+-------+ 3547| ``'o'`` | Signed octal value. | \(1) | 3548+------------+-----------------------------------------------------+-------+ 3549| ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(8) | 3550+------------+-----------------------------------------------------+-------+ 3551| ``'x'`` | Signed hexadecimal (lowercase). | \(2) | 3552+------------+-----------------------------------------------------+-------+ 3553| ``'X'`` | Signed hexadecimal (uppercase). | \(2) | 3554+------------+-----------------------------------------------------+-------+ 3555| ``'e'`` | Floating point exponential format (lowercase). | \(3) | 3556+------------+-----------------------------------------------------+-------+ 3557| ``'E'`` | Floating point exponential format (uppercase). | \(3) | 3558+------------+-----------------------------------------------------+-------+ 3559| ``'f'`` | Floating point decimal format. | \(3) | 3560+------------+-----------------------------------------------------+-------+ 3561| ``'F'`` | Floating point decimal format. | \(3) | 3562+------------+-----------------------------------------------------+-------+ 3563| ``'g'`` | Floating point format. Uses lowercase exponential | \(4) | 3564| | format if exponent is less than -4 or not less than | | 3565| | precision, decimal format otherwise. | | 3566+------------+-----------------------------------------------------+-------+ 3567| ``'G'`` | Floating point format. Uses uppercase exponential | \(4) | 3568| | format if exponent is less than -4 or not less than | | 3569| | precision, decimal format otherwise. | | 3570+------------+-----------------------------------------------------+-------+ 3571| ``'c'`` | Single byte (accepts integer or single | | 3572| | byte objects). | | 3573+------------+-----------------------------------------------------+-------+ 3574| ``'b'`` | Bytes (any object that follows the | \(5) | 3575| | :ref:`buffer protocol <bufferobjects>` or has | | 3576| | :meth:`__bytes__`). | | 3577+------------+-----------------------------------------------------+-------+ 3578| ``'s'`` | ``'s'`` is an alias for ``'b'`` and should only | \(6) | 3579| | be used for Python2/3 code bases. | | 3580+------------+-----------------------------------------------------+-------+ 3581| ``'a'`` | Bytes (converts any Python object using | \(5) | 3582| | ``repr(obj).encode('ascii','backslashreplace)``). | | 3583+------------+-----------------------------------------------------+-------+ 3584| ``'r'`` | ``'r'`` is an alias for ``'a'`` and should only | \(7) | 3585| | be used for Python2/3 code bases. | | 3586+------------+-----------------------------------------------------+-------+ 3587| ``'%'`` | No argument is converted, results in a ``'%'`` | | 3588| | character in the result. | | 3589+------------+-----------------------------------------------------+-------+ 3590 3591Notes: 3592 3593(1) 3594 The alternate form causes a leading octal specifier (``'0o'``) to be 3595 inserted before the first digit. 3596 3597(2) 3598 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether 3599 the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit. 3600 3601(3) 3602 The alternate form causes the result to always contain a decimal point, even if 3603 no digits follow it. 3604 3605 The precision determines the number of digits after the decimal point and 3606 defaults to 6. 3607 3608(4) 3609 The alternate form causes the result to always contain a decimal point, and 3610 trailing zeroes are not removed as they would otherwise be. 3611 3612 The precision determines the number of significant digits before and after the 3613 decimal point and defaults to 6. 3614 3615(5) 3616 If precision is ``N``, the output is truncated to ``N`` characters. 3617 3618(6) 3619 ``b'%s'`` is deprecated, but will not be removed during the 3.x series. 3620 3621(7) 3622 ``b'%r'`` is deprecated, but will not be removed during the 3.x series. 3623 3624(8) 3625 See :pep:`237`. 3626 3627.. note:: 3628 3629 The bytearray version of this method does *not* operate in place - it 3630 always produces a new object, even if no changes were made. 3631 3632.. seealso:: 3633 3634 :pep:`461` - Adding % formatting to bytes and bytearray 3635 3636.. versionadded:: 3.5 3637 3638.. _typememoryview: 3639 3640Memory Views 3641------------ 3642 3643:class:`memoryview` objects allow Python code to access the internal data 3644of an object that supports the :ref:`buffer protocol <bufferobjects>` without 3645copying. 3646 3647.. class:: memoryview(object) 3648 3649 Create a :class:`memoryview` that references *object*. *object* must 3650 support the buffer protocol. Built-in objects that support the buffer 3651 protocol include :class:`bytes` and :class:`bytearray`. 3652 3653 A :class:`memoryview` has the notion of an *element*, which is the 3654 atomic memory unit handled by the originating *object*. For many simple 3655 types such as :class:`bytes` and :class:`bytearray`, an element is a single 3656 byte, but other types such as :class:`array.array` may have bigger elements. 3657 3658 ``len(view)`` is equal to the length of :class:`~memoryview.tolist`. 3659 If ``view.ndim = 0``, the length is 1. If ``view.ndim = 1``, the length 3660 is equal to the number of elements in the view. For higher dimensions, 3661 the length is equal to the length of the nested list representation of 3662 the view. The :class:`~memoryview.itemsize` attribute will give you the 3663 number of bytes in a single element. 3664 3665 A :class:`memoryview` supports slicing and indexing to expose its data. 3666 One-dimensional slicing will result in a subview:: 3667 3668 >>> v = memoryview(b'abcefg') 3669 >>> v[1] 3670 98 3671 >>> v[-1] 3672 103 3673 >>> v[1:4] 3674 <memory at 0x7f3ddc9f4350> 3675 >>> bytes(v[1:4]) 3676 b'bce' 3677 3678 If :class:`~memoryview.format` is one of the native format specifiers 3679 from the :mod:`struct` module, indexing with an integer or a tuple of 3680 integers is also supported and returns a single *element* with 3681 the correct type. One-dimensional memoryviews can be indexed 3682 with an integer or a one-integer tuple. Multi-dimensional memoryviews 3683 can be indexed with tuples of exactly *ndim* integers where *ndim* is 3684 the number of dimensions. Zero-dimensional memoryviews can be indexed 3685 with the empty tuple. 3686 3687 Here is an example with a non-byte format:: 3688 3689 >>> import array 3690 >>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444]) 3691 >>> m = memoryview(a) 3692 >>> m[0] 3693 -11111111 3694 >>> m[-1] 3695 44444444 3696 >>> m[::2].tolist() 3697 [-11111111, -33333333] 3698 3699 If the underlying object is writable, the memoryview supports 3700 one-dimensional slice assignment. Resizing is not allowed:: 3701 3702 >>> data = bytearray(b'abcefg') 3703 >>> v = memoryview(data) 3704 >>> v.readonly 3705 False 3706 >>> v[0] = ord(b'z') 3707 >>> data 3708 bytearray(b'zbcefg') 3709 >>> v[1:4] = b'123' 3710 >>> data 3711 bytearray(b'z123fg') 3712 >>> v[2:3] = b'spam' 3713 Traceback (most recent call last): 3714 File "<stdin>", line 1, in <module> 3715 ValueError: memoryview assignment: lvalue and rvalue have different structures 3716 >>> v[2:6] = b'spam' 3717 >>> data 3718 bytearray(b'z1spam') 3719 3720 One-dimensional memoryviews of hashable (read-only) types with formats 3721 'B', 'b' or 'c' are also hashable. The hash is defined as 3722 ``hash(m) == hash(m.tobytes())``:: 3723 3724 >>> v = memoryview(b'abcefg') 3725 >>> hash(v) == hash(b'abcefg') 3726 True 3727 >>> hash(v[2:4]) == hash(b'ce') 3728 True 3729 >>> hash(v[::-2]) == hash(b'abcefg'[::-2]) 3730 True 3731 3732 .. versionchanged:: 3.3 3733 One-dimensional memoryviews can now be sliced. 3734 One-dimensional memoryviews with formats 'B', 'b' or 'c' are now hashable. 3735 3736 .. versionchanged:: 3.4 3737 memoryview is now registered automatically with 3738 :class:`collections.abc.Sequence` 3739 3740 .. versionchanged:: 3.5 3741 memoryviews can now be indexed with tuple of integers. 3742 3743 :class:`memoryview` has several methods: 3744 3745 .. method:: __eq__(exporter) 3746 3747 A memoryview and a :pep:`3118` exporter are equal if their shapes are 3748 equivalent and if all corresponding values are equal when the operands' 3749 respective format codes are interpreted using :mod:`struct` syntax. 3750 3751 For the subset of :mod:`struct` format strings currently supported by 3752 :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``:: 3753 3754 >>> import array 3755 >>> a = array.array('I', [1, 2, 3, 4, 5]) 3756 >>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0]) 3757 >>> c = array.array('b', [5, 3, 1]) 3758 >>> x = memoryview(a) 3759 >>> y = memoryview(b) 3760 >>> x == a == y == b 3761 True 3762 >>> x.tolist() == a.tolist() == y.tolist() == b.tolist() 3763 True 3764 >>> z = y[::-2] 3765 >>> z == c 3766 True 3767 >>> z.tolist() == c.tolist() 3768 True 3769 3770 If either format string is not supported by the :mod:`struct` module, 3771 then the objects will always compare as unequal (even if the format 3772 strings and buffer contents are identical):: 3773 3774 >>> from ctypes import BigEndianStructure, c_long 3775 >>> class BEPoint(BigEndianStructure): 3776 ... _fields_ = [("x", c_long), ("y", c_long)] 3777 ... 3778 >>> point = BEPoint(100, 200) 3779 >>> a = memoryview(point) 3780 >>> b = memoryview(point) 3781 >>> a == point 3782 False 3783 >>> a == b 3784 False 3785 3786 Note that, as with floating point numbers, ``v is w`` does *not* imply 3787 ``v == w`` for memoryview objects. 3788 3789 .. versionchanged:: 3.3 3790 Previous versions compared the raw memory disregarding the item format 3791 and the logical array structure. 3792 3793 .. method:: tobytes(order=None) 3794 3795 Return the data in the buffer as a bytestring. This is equivalent to 3796 calling the :class:`bytes` constructor on the memoryview. :: 3797 3798 >>> m = memoryview(b"abc") 3799 >>> m.tobytes() 3800 b'abc' 3801 >>> bytes(m) 3802 b'abc' 3803 3804 For non-contiguous arrays the result is equal to the flattened list 3805 representation with all elements converted to bytes. :meth:`tobytes` 3806 supports all format strings, including those that are not in 3807 :mod:`struct` module syntax. 3808 3809 .. versionadded:: 3.8 3810 *order* can be {'C', 'F', 'A'}. When *order* is 'C' or 'F', the data 3811 of the original array is converted to C or Fortran order. For contiguous 3812 views, 'A' returns an exact copy of the physical memory. In particular, 3813 in-memory Fortran order is preserved. For non-contiguous views, the 3814 data is converted to C first. *order=None* is the same as *order='C'*. 3815 3816 .. method:: hex([sep[, bytes_per_sep]]) 3817 3818 Return a string object containing two hexadecimal digits for each 3819 byte in the buffer. :: 3820 3821 >>> m = memoryview(b"abc") 3822 >>> m.hex() 3823 '616263' 3824 3825 .. versionadded:: 3.5 3826 3827 .. versionchanged:: 3.8 3828 Similar to :meth:`bytes.hex`, :meth:`memoryview.hex` now supports 3829 optional *sep* and *bytes_per_sep* parameters to insert separators 3830 between bytes in the hex output. 3831 3832 .. method:: tolist() 3833 3834 Return the data in the buffer as a list of elements. :: 3835 3836 >>> memoryview(b'abc').tolist() 3837 [97, 98, 99] 3838 >>> import array 3839 >>> a = array.array('d', [1.1, 2.2, 3.3]) 3840 >>> m = memoryview(a) 3841 >>> m.tolist() 3842 [1.1, 2.2, 3.3] 3843 3844 .. versionchanged:: 3.3 3845 :meth:`tolist` now supports all single character native formats in 3846 :mod:`struct` module syntax as well as multi-dimensional 3847 representations. 3848 3849 .. method:: toreadonly() 3850 3851 Return a readonly version of the memoryview object. The original 3852 memoryview object is unchanged. :: 3853 3854 >>> m = memoryview(bytearray(b'abc')) 3855 >>> mm = m.toreadonly() 3856 >>> mm.tolist() 3857 [89, 98, 99] 3858 >>> mm[0] = 42 3859 Traceback (most recent call last): 3860 File "<stdin>", line 1, in <module> 3861 TypeError: cannot modify read-only memory 3862 >>> m[0] = 43 3863 >>> mm.tolist() 3864 [43, 98, 99] 3865 3866 .. versionadded:: 3.8 3867 3868 .. method:: release() 3869 3870 Release the underlying buffer exposed by the memoryview object. Many 3871 objects take special actions when a view is held on them (for example, 3872 a :class:`bytearray` would temporarily forbid resizing); therefore, 3873 calling release() is handy to remove these restrictions (and free any 3874 dangling resources) as soon as possible. 3875 3876 After this method has been called, any further operation on the view 3877 raises a :class:`ValueError` (except :meth:`release()` itself which can 3878 be called multiple times):: 3879 3880 >>> m = memoryview(b'abc') 3881 >>> m.release() 3882 >>> m[0] 3883 Traceback (most recent call last): 3884 File "<stdin>", line 1, in <module> 3885 ValueError: operation forbidden on released memoryview object 3886 3887 The context management protocol can be used for a similar effect, 3888 using the ``with`` statement:: 3889 3890 >>> with memoryview(b'abc') as m: 3891 ... m[0] 3892 ... 3893 97 3894 >>> m[0] 3895 Traceback (most recent call last): 3896 File "<stdin>", line 1, in <module> 3897 ValueError: operation forbidden on released memoryview object 3898 3899 .. versionadded:: 3.2 3900 3901 .. method:: cast(format[, shape]) 3902 3903 Cast a memoryview to a new format or shape. *shape* defaults to 3904 ``[byte_length//new_itemsize]``, which means that the result view 3905 will be one-dimensional. The return value is a new memoryview, but 3906 the buffer itself is not copied. Supported casts are 1D -> C-:term:`contiguous` 3907 and C-contiguous -> 1D. 3908 3909 The destination format is restricted to a single element native format in 3910 :mod:`struct` syntax. One of the formats must be a byte format 3911 ('B', 'b' or 'c'). The byte length of the result must be the same 3912 as the original length. 3913 3914 Cast 1D/long to 1D/unsigned bytes:: 3915 3916 >>> import array 3917 >>> a = array.array('l', [1,2,3]) 3918 >>> x = memoryview(a) 3919 >>> x.format 3920 'l' 3921 >>> x.itemsize 3922 8 3923 >>> len(x) 3924 3 3925 >>> x.nbytes 3926 24 3927 >>> y = x.cast('B') 3928 >>> y.format 3929 'B' 3930 >>> y.itemsize 3931 1 3932 >>> len(y) 3933 24 3934 >>> y.nbytes 3935 24 3936 3937 Cast 1D/unsigned bytes to 1D/char:: 3938 3939 >>> b = bytearray(b'zyz') 3940 >>> x = memoryview(b) 3941 >>> x[0] = b'a' 3942 Traceback (most recent call last): 3943 File "<stdin>", line 1, in <module> 3944 ValueError: memoryview: invalid value for format "B" 3945 >>> y = x.cast('c') 3946 >>> y[0] = b'a' 3947 >>> b 3948 bytearray(b'ayz') 3949 3950 Cast 1D/bytes to 3D/ints to 1D/signed char:: 3951 3952 >>> import struct 3953 >>> buf = struct.pack("i"*12, *list(range(12))) 3954 >>> x = memoryview(buf) 3955 >>> y = x.cast('i', shape=[2,2,3]) 3956 >>> y.tolist() 3957 [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]] 3958 >>> y.format 3959 'i' 3960 >>> y.itemsize 3961 4 3962 >>> len(y) 3963 2 3964 >>> y.nbytes 3965 48 3966 >>> z = y.cast('b') 3967 >>> z.format 3968 'b' 3969 >>> z.itemsize 3970 1 3971 >>> len(z) 3972 48 3973 >>> z.nbytes 3974 48 3975 3976 Cast 1D/unsigned long to 2D/unsigned long:: 3977 3978 >>> buf = struct.pack("L"*6, *list(range(6))) 3979 >>> x = memoryview(buf) 3980 >>> y = x.cast('L', shape=[2,3]) 3981 >>> len(y) 3982 2 3983 >>> y.nbytes 3984 48 3985 >>> y.tolist() 3986 [[0, 1, 2], [3, 4, 5]] 3987 3988 .. versionadded:: 3.3 3989 3990 .. versionchanged:: 3.5 3991 The source format is no longer restricted when casting to a byte view. 3992 3993 There are also several readonly attributes available: 3994 3995 .. attribute:: obj 3996 3997 The underlying object of the memoryview:: 3998 3999 >>> b = bytearray(b'xyz') 4000 >>> m = memoryview(b) 4001 >>> m.obj is b 4002 True 4003 4004 .. versionadded:: 3.3 4005 4006 .. attribute:: nbytes 4007 4008 ``nbytes == product(shape) * itemsize == len(m.tobytes())``. This is 4009 the amount of space in bytes that the array would use in a contiguous 4010 representation. It is not necessarily equal to ``len(m)``:: 4011 4012 >>> import array 4013 >>> a = array.array('i', [1,2,3,4,5]) 4014 >>> m = memoryview(a) 4015 >>> len(m) 4016 5 4017 >>> m.nbytes 4018 20 4019 >>> y = m[::2] 4020 >>> len(y) 4021 3 4022 >>> y.nbytes 4023 12 4024 >>> len(y.tobytes()) 4025 12 4026 4027 Multi-dimensional arrays:: 4028 4029 >>> import struct 4030 >>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)]) 4031 >>> x = memoryview(buf) 4032 >>> y = x.cast('d', shape=[3,4]) 4033 >>> y.tolist() 4034 [[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]] 4035 >>> len(y) 4036 3 4037 >>> y.nbytes 4038 96 4039 4040 .. versionadded:: 3.3 4041 4042 .. attribute:: readonly 4043 4044 A bool indicating whether the memory is read only. 4045 4046 .. attribute:: format 4047 4048 A string containing the format (in :mod:`struct` module style) for each 4049 element in the view. A memoryview can be created from exporters with 4050 arbitrary format strings, but some methods (e.g. :meth:`tolist`) are 4051 restricted to native single element formats. 4052 4053 .. versionchanged:: 3.3 4054 format ``'B'`` is now handled according to the struct module syntax. 4055 This means that ``memoryview(b'abc')[0] == b'abc'[0] == 97``. 4056 4057 .. attribute:: itemsize 4058 4059 The size in bytes of each element of the memoryview:: 4060 4061 >>> import array, struct 4062 >>> m = memoryview(array.array('H', [32000, 32001, 32002])) 4063 >>> m.itemsize 4064 2 4065 >>> m[0] 4066 32000 4067 >>> struct.calcsize('H') == m.itemsize 4068 True 4069 4070 .. attribute:: ndim 4071 4072 An integer indicating how many dimensions of a multi-dimensional array the 4073 memory represents. 4074 4075 .. attribute:: shape 4076 4077 A tuple of integers the length of :attr:`ndim` giving the shape of the 4078 memory as an N-dimensional array. 4079 4080 .. versionchanged:: 3.3 4081 An empty tuple instead of ``None`` when ndim = 0. 4082 4083 .. attribute:: strides 4084 4085 A tuple of integers the length of :attr:`ndim` giving the size in bytes to 4086 access each element for each dimension of the array. 4087 4088 .. versionchanged:: 3.3 4089 An empty tuple instead of ``None`` when ndim = 0. 4090 4091 .. attribute:: suboffsets 4092 4093 Used internally for PIL-style arrays. The value is informational only. 4094 4095 .. attribute:: c_contiguous 4096 4097 A bool indicating whether the memory is C-:term:`contiguous`. 4098 4099 .. versionadded:: 3.3 4100 4101 .. attribute:: f_contiguous 4102 4103 A bool indicating whether the memory is Fortran :term:`contiguous`. 4104 4105 .. versionadded:: 3.3 4106 4107 .. attribute:: contiguous 4108 4109 A bool indicating whether the memory is :term:`contiguous`. 4110 4111 .. versionadded:: 3.3 4112 4113 4114.. _types-set: 4115 4116Set Types --- :class:`set`, :class:`frozenset` 4117============================================== 4118 4119.. index:: object: set 4120 4121A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. 4122Common uses include membership testing, removing duplicates from a sequence, and 4123computing mathematical operations such as intersection, union, difference, and 4124symmetric difference. 4125(For other containers see the built-in :class:`dict`, :class:`list`, 4126and :class:`tuple` classes, and the :mod:`collections` module.) 4127 4128Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in 4129set``. Being an unordered collection, sets do not record element position or 4130order of insertion. Accordingly, sets do not support indexing, slicing, or 4131other sequence-like behavior. 4132 4133There are currently two built-in set types, :class:`set` and :class:`frozenset`. 4134The :class:`set` type is mutable --- the contents can be changed using methods 4135like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no 4136hash value and cannot be used as either a dictionary key or as an element of 4137another set. The :class:`frozenset` type is immutable and :term:`hashable` --- 4138its contents cannot be altered after it is created; it can therefore be used as 4139a dictionary key or as an element of another set. 4140 4141Non-empty sets (not frozensets) can be created by placing a comma-separated list 4142of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the 4143:class:`set` constructor. 4144 4145The constructors for both classes work the same: 4146 4147.. class:: set([iterable]) 4148 frozenset([iterable]) 4149 4150 Return a new set or frozenset object whose elements are taken from 4151 *iterable*. The elements of a set must be :term:`hashable`. To 4152 represent sets of sets, the inner sets must be :class:`frozenset` 4153 objects. If *iterable* is not specified, a new empty set is 4154 returned. 4155 4156 Sets can be created by several means: 4157 4158 * Use a comma-separated list of elements within braces: ``{'jack', 'sjoerd'}`` 4159 * Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}`` 4160 * Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])`` 4161 4162 Instances of :class:`set` and :class:`frozenset` provide the following 4163 operations: 4164 4165 .. describe:: len(s) 4166 4167 Return the number of elements in set *s* (cardinality of *s*). 4168 4169 .. describe:: x in s 4170 4171 Test *x* for membership in *s*. 4172 4173 .. describe:: x not in s 4174 4175 Test *x* for non-membership in *s*. 4176 4177 .. method:: isdisjoint(other) 4178 4179 Return ``True`` if the set has no elements in common with *other*. Sets are 4180 disjoint if and only if their intersection is the empty set. 4181 4182 .. method:: issubset(other) 4183 set <= other 4184 4185 Test whether every element in the set is in *other*. 4186 4187 .. method:: set < other 4188 4189 Test whether the set is a proper subset of *other*, that is, 4190 ``set <= other and set != other``. 4191 4192 .. method:: issuperset(other) 4193 set >= other 4194 4195 Test whether every element in *other* is in the set. 4196 4197 .. method:: set > other 4198 4199 Test whether the set is a proper superset of *other*, that is, ``set >= 4200 other and set != other``. 4201 4202 .. method:: union(*others) 4203 set | other | ... 4204 4205 Return a new set with elements from the set and all others. 4206 4207 .. method:: intersection(*others) 4208 set & other & ... 4209 4210 Return a new set with elements common to the set and all others. 4211 4212 .. method:: difference(*others) 4213 set - other - ... 4214 4215 Return a new set with elements in the set that are not in the others. 4216 4217 .. method:: symmetric_difference(other) 4218 set ^ other 4219 4220 Return a new set with elements in either the set or *other* but not both. 4221 4222 .. method:: copy() 4223 4224 Return a shallow copy of the set. 4225 4226 4227 Note, the non-operator versions of :meth:`union`, :meth:`intersection`, 4228 :meth:`difference`, :meth:`symmetric_difference`, :meth:`issubset`, and 4229 :meth:`issuperset` methods will accept any iterable as an argument. In 4230 contrast, their operator based counterparts require their arguments to be 4231 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` 4232 in favor of the more readable ``set('abc').intersection('cbs')``. 4233 4234 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two 4235 sets are equal if and only if every element of each set is contained in the 4236 other (each is a subset of the other). A set is less than another set if and 4237 only if the first set is a proper subset of the second set (is a subset, but 4238 is not equal). A set is greater than another set if and only if the first set 4239 is a proper superset of the second set (is a superset, but is not equal). 4240 4241 Instances of :class:`set` are compared to instances of :class:`frozenset` 4242 based on their members. For example, ``set('abc') == frozenset('abc')`` 4243 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``. 4244 4245 The subset and equality comparisons do not generalize to a total ordering 4246 function. For example, any two nonempty disjoint sets are not equal and are not 4247 subsets of each other, so *all* of the following return ``False``: ``a<b``, 4248 ``a==b``, or ``a>b``. 4249 4250 Since sets only define partial ordering (subset relationships), the output of 4251 the :meth:`list.sort` method is undefined for lists of sets. 4252 4253 Set elements, like dictionary keys, must be :term:`hashable`. 4254 4255 Binary operations that mix :class:`set` instances with :class:`frozenset` 4256 return the type of the first operand. For example: ``frozenset('ab') | 4257 set('bc')`` returns an instance of :class:`frozenset`. 4258 4259 The following table lists operations available for :class:`set` that do not 4260 apply to immutable instances of :class:`frozenset`: 4261 4262 .. method:: update(*others) 4263 set |= other | ... 4264 4265 Update the set, adding elements from all others. 4266 4267 .. method:: intersection_update(*others) 4268 set &= other & ... 4269 4270 Update the set, keeping only elements found in it and all others. 4271 4272 .. method:: difference_update(*others) 4273 set -= other | ... 4274 4275 Update the set, removing elements found in others. 4276 4277 .. method:: symmetric_difference_update(other) 4278 set ^= other 4279 4280 Update the set, keeping only elements found in either set, but not in both. 4281 4282 .. method:: add(elem) 4283 4284 Add element *elem* to the set. 4285 4286 .. method:: remove(elem) 4287 4288 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is 4289 not contained in the set. 4290 4291 .. method:: discard(elem) 4292 4293 Remove element *elem* from the set if it is present. 4294 4295 .. method:: pop() 4296 4297 Remove and return an arbitrary element from the set. Raises 4298 :exc:`KeyError` if the set is empty. 4299 4300 .. method:: clear() 4301 4302 Remove all elements from the set. 4303 4304 4305 Note, the non-operator versions of the :meth:`update`, 4306 :meth:`intersection_update`, :meth:`difference_update`, and 4307 :meth:`symmetric_difference_update` methods will accept any iterable as an 4308 argument. 4309 4310 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and 4311 :meth:`discard` methods may be a set. To support searching for an equivalent 4312 frozenset, a temporary one is created from *elem*. 4313 4314 4315.. _typesmapping: 4316 4317Mapping Types --- :class:`dict` 4318=============================== 4319 4320.. index:: 4321 object: mapping 4322 object: dictionary 4323 triple: operations on; mapping; types 4324 triple: operations on; dictionary; type 4325 statement: del 4326 builtin: len 4327 4328A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. 4329Mappings are mutable objects. There is currently only one standard mapping 4330type, the :dfn:`dictionary`. (For other containers see the built-in 4331:class:`list`, :class:`set`, and :class:`tuple` classes, and the 4332:mod:`collections` module.) 4333 4334A dictionary's keys are *almost* arbitrary values. Values that are not 4335:term:`hashable`, that is, values containing lists, dictionaries or other 4336mutable types (that are compared by value rather than by object identity) may 4337not be used as keys. Numeric types used for keys obey the normal rules for 4338numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``) 4339then they can be used interchangeably to index the same dictionary entry. (Note 4340however, that since computers store floating-point numbers as approximations it 4341is usually unwise to use them as dictionary keys.) 4342 4343Dictionaries can be created by placing a comma-separated list of ``key: value`` 4344pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: 4345'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor. 4346 4347.. class:: dict(**kwargs) 4348 dict(mapping, **kwargs) 4349 dict(iterable, **kwargs) 4350 4351 Return a new dictionary initialized from an optional positional argument 4352 and a possibly empty set of keyword arguments. 4353 4354 Dictionaries can be created by several means: 4355 4356 * Use a comma-separated list of ``key: value`` pairs within braces: 4357 ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: 'jack', 4127: 'sjoerd'}`` 4358 * Use a dict comprehension: ``{}``, ``{x: x ** 2 for x in range(10)}`` 4359 * Use the type constructor: ``dict()``, 4360 ``dict([('foo', 100), ('bar', 200)])``, ``dict(foo=100, bar=200)`` 4361 4362 If no positional argument is given, an empty dictionary is created. 4363 If a positional argument is given and it is a mapping object, a dictionary 4364 is created with the same key-value pairs as the mapping object. Otherwise, 4365 the positional argument must be an :term:`iterable` object. Each item in 4366 the iterable must itself be an iterable with exactly two objects. The 4367 first object of each item becomes a key in the new dictionary, and the 4368 second object the corresponding value. If a key occurs more than once, the 4369 last value for that key becomes the corresponding value in the new 4370 dictionary. 4371 4372 If keyword arguments are given, the keyword arguments and their values are 4373 added to the dictionary created from the positional argument. If a key 4374 being added is already present, the value from the keyword argument 4375 replaces the value from the positional argument. 4376 4377 To illustrate, the following examples all return a dictionary equal to 4378 ``{"one": 1, "two": 2, "three": 3}``:: 4379 4380 >>> a = dict(one=1, two=2, three=3) 4381 >>> b = {'one': 1, 'two': 2, 'three': 3} 4382 >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) 4383 >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) 4384 >>> e = dict({'three': 3, 'one': 1, 'two': 2}) 4385 >>> f = dict({'one': 1, 'three': 3}, two=2) 4386 >>> a == b == c == d == e == f 4387 True 4388 4389 Providing keyword arguments as in the first example only works for keys that 4390 are valid Python identifiers. Otherwise, any valid keys can be used. 4391 4392 4393 These are the operations that dictionaries support (and therefore, custom 4394 mapping types should support too): 4395 4396 .. describe:: list(d) 4397 4398 Return a list of all the keys used in the dictionary *d*. 4399 4400 .. describe:: len(d) 4401 4402 Return the number of items in the dictionary *d*. 4403 4404 .. describe:: d[key] 4405 4406 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is 4407 not in the map. 4408 4409 .. index:: __missing__() 4410 4411 If a subclass of dict defines a method :meth:`__missing__` and *key* 4412 is not present, the ``d[key]`` operation calls that method with the key *key* 4413 as argument. The ``d[key]`` operation then returns or raises whatever is 4414 returned or raised by the ``__missing__(key)`` call. 4415 No other operations or methods invoke :meth:`__missing__`. If 4416 :meth:`__missing__` is not defined, :exc:`KeyError` is raised. 4417 :meth:`__missing__` must be a method; it cannot be an instance variable:: 4418 4419 >>> class Counter(dict): 4420 ... def __missing__(self, key): 4421 ... return 0 4422 >>> c = Counter() 4423 >>> c['red'] 4424 0 4425 >>> c['red'] += 1 4426 >>> c['red'] 4427 1 4428 4429 The example above shows part of the implementation of 4430 :class:`collections.Counter`. A different ``__missing__`` method is used 4431 by :class:`collections.defaultdict`. 4432 4433 .. describe:: d[key] = value 4434 4435 Set ``d[key]`` to *value*. 4436 4437 .. describe:: del d[key] 4438 4439 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the 4440 map. 4441 4442 .. describe:: key in d 4443 4444 Return ``True`` if *d* has a key *key*, else ``False``. 4445 4446 .. describe:: key not in d 4447 4448 Equivalent to ``not key in d``. 4449 4450 .. describe:: iter(d) 4451 4452 Return an iterator over the keys of the dictionary. This is a shortcut 4453 for ``iter(d.keys())``. 4454 4455 .. method:: clear() 4456 4457 Remove all items from the dictionary. 4458 4459 .. method:: copy() 4460 4461 Return a shallow copy of the dictionary. 4462 4463 .. classmethod:: fromkeys(iterable[, value]) 4464 4465 Create a new dictionary with keys from *iterable* and values set to *value*. 4466 4467 :meth:`fromkeys` is a class method that returns a new dictionary. *value* 4468 defaults to ``None``. All of the values refer to just a single instance, 4469 so it generally doesn't make sense for *value* to be a mutable object 4470 such as an empty list. To get distinct values, use a :ref:`dict 4471 comprehension <dict>` instead. 4472 4473 .. method:: get(key[, default]) 4474 4475 Return the value for *key* if *key* is in the dictionary, else *default*. 4476 If *default* is not given, it defaults to ``None``, so that this method 4477 never raises a :exc:`KeyError`. 4478 4479 .. method:: items() 4480 4481 Return a new view of the dictionary's items (``(key, value)`` pairs). 4482 See the :ref:`documentation of view objects <dict-views>`. 4483 4484 .. method:: keys() 4485 4486 Return a new view of the dictionary's keys. See the :ref:`documentation 4487 of view objects <dict-views>`. 4488 4489 .. method:: pop(key[, default]) 4490 4491 If *key* is in the dictionary, remove it and return its value, else return 4492 *default*. If *default* is not given and *key* is not in the dictionary, 4493 a :exc:`KeyError` is raised. 4494 4495 .. method:: popitem() 4496 4497 Remove and return a ``(key, value)`` pair from the dictionary. 4498 Pairs are returned in :abbr:`LIFO (last-in, first-out)` order. 4499 4500 :meth:`popitem` is useful to destructively iterate over a dictionary, as 4501 often used in set algorithms. If the dictionary is empty, calling 4502 :meth:`popitem` raises a :exc:`KeyError`. 4503 4504 .. versionchanged:: 3.7 4505 LIFO order is now guaranteed. In prior versions, :meth:`popitem` would 4506 return an arbitrary key/value pair. 4507 4508 .. describe:: reversed(d) 4509 4510 Return a reverse iterator over the keys of the dictionary. This is a 4511 shortcut for ``reversed(d.keys())``. 4512 4513 .. versionadded:: 3.8 4514 4515 .. method:: setdefault(key[, default]) 4516 4517 If *key* is in the dictionary, return its value. If not, insert *key* 4518 with a value of *default* and return *default*. *default* defaults to 4519 ``None``. 4520 4521 .. method:: update([other]) 4522 4523 Update the dictionary with the key/value pairs from *other*, overwriting 4524 existing keys. Return ``None``. 4525 4526 :meth:`update` accepts either another dictionary object or an iterable of 4527 key/value pairs (as tuples or other iterables of length two). If keyword 4528 arguments are specified, the dictionary is then updated with those 4529 key/value pairs: ``d.update(red=1, blue=2)``. 4530 4531 .. method:: values() 4532 4533 Return a new view of the dictionary's values. See the 4534 :ref:`documentation of view objects <dict-views>`. 4535 4536 An equality comparison between one ``dict.values()`` view and another 4537 will always return ``False``. This also applies when comparing 4538 ``dict.values()`` to itself:: 4539 4540 >>> d = {'a': 1} 4541 >>> d.values() == d.values() 4542 False 4543 4544 .. describe:: d | other 4545 4546 Create a new dictionary with the merged keys and values of *d* and 4547 *other*, which must both be dictionaries. The values of *other* take 4548 priority when *d* and *other* share keys. 4549 4550 .. versionadded:: 3.9 4551 4552 .. describe:: d |= other 4553 4554 Update the dictionary *d* with keys and values from *other*, which may be 4555 either a :term:`mapping` or an :term:`iterable` of key/value pairs. The 4556 values of *other* take priority when *d* and *other* share keys. 4557 4558 .. versionadded:: 3.9 4559 4560 Dictionaries compare equal if and only if they have the same ``(key, 4561 value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise 4562 :exc:`TypeError`. 4563 4564 Dictionaries preserve insertion order. Note that updating a key does not 4565 affect the order. Keys added after deletion are inserted at the end. :: 4566 4567 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} 4568 >>> d 4569 {'one': 1, 'two': 2, 'three': 3, 'four': 4} 4570 >>> list(d) 4571 ['one', 'two', 'three', 'four'] 4572 >>> list(d.values()) 4573 [1, 2, 3, 4] 4574 >>> d["one"] = 42 4575 >>> d 4576 {'one': 42, 'two': 2, 'three': 3, 'four': 4} 4577 >>> del d["two"] 4578 >>> d["two"] = None 4579 >>> d 4580 {'one': 42, 'three': 3, 'four': 4, 'two': None} 4581 4582 .. versionchanged:: 3.7 4583 Dictionary order is guaranteed to be insertion order. This behavior was 4584 an implementation detail of CPython from 3.6. 4585 4586 Dictionaries and dictionary views are reversible. :: 4587 4588 >>> d = {"one": 1, "two": 2, "three": 3, "four": 4} 4589 >>> d 4590 {'one': 1, 'two': 2, 'three': 3, 'four': 4} 4591 >>> list(reversed(d)) 4592 ['four', 'three', 'two', 'one'] 4593 >>> list(reversed(d.values())) 4594 [4, 3, 2, 1] 4595 >>> list(reversed(d.items())) 4596 [('four', 4), ('three', 3), ('two', 2), ('one', 1)] 4597 4598 .. versionchanged:: 3.8 4599 Dictionaries are now reversible. 4600 4601 4602.. seealso:: 4603 :class:`types.MappingProxyType` can be used to create a read-only view 4604 of a :class:`dict`. 4605 4606 4607.. _dict-views: 4608 4609Dictionary view objects 4610----------------------- 4611 4612The objects returned by :meth:`dict.keys`, :meth:`dict.values` and 4613:meth:`dict.items` are *view objects*. They provide a dynamic view on the 4614dictionary's entries, which means that when the dictionary changes, the view 4615reflects these changes. 4616 4617Dictionary views can be iterated over to yield their respective data, and 4618support membership tests: 4619 4620.. describe:: len(dictview) 4621 4622 Return the number of entries in the dictionary. 4623 4624.. describe:: iter(dictview) 4625 4626 Return an iterator over the keys, values or items (represented as tuples of 4627 ``(key, value)``) in the dictionary. 4628 4629 Keys and values are iterated over in insertion order. 4630 This allows the creation of ``(value, key)`` pairs 4631 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to 4632 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. 4633 4634 Iterating views while adding or deleting entries in the dictionary may raise 4635 a :exc:`RuntimeError` or fail to iterate over all entries. 4636 4637 .. versionchanged:: 3.7 4638 Dictionary order is guaranteed to be insertion order. 4639 4640.. describe:: x in dictview 4641 4642 Return ``True`` if *x* is in the underlying dictionary's keys, values or 4643 items (in the latter case, *x* should be a ``(key, value)`` tuple). 4644 4645.. describe:: reversed(dictview) 4646 4647 Return a reverse iterator over the keys, values or items of the dictionary. 4648 The view will be iterated in reverse order of the insertion. 4649 4650 .. versionchanged:: 3.8 4651 Dictionary views are now reversible. 4652 4653.. describe:: dictview.mapping 4654 4655 Return a :class:`types.MappingProxyType` that wraps the original 4656 dictionary to which the view refers. 4657 4658 .. versionadded:: 3.10 4659 4660Keys views are set-like since their entries are unique and hashable. If all 4661values are hashable, so that ``(key, value)`` pairs are unique and hashable, 4662then the items view is also set-like. (Values views are not treated as set-like 4663since the entries are generally not unique.) For set-like views, all of the 4664operations defined for the abstract base class :class:`collections.abc.Set` are 4665available (for example, ``==``, ``<``, or ``^``). 4666 4667An example of dictionary view usage:: 4668 4669 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} 4670 >>> keys = dishes.keys() 4671 >>> values = dishes.values() 4672 4673 >>> # iteration 4674 >>> n = 0 4675 >>> for val in values: 4676 ... n += val 4677 >>> print(n) 4678 504 4679 4680 >>> # keys and values are iterated over in the same order (insertion order) 4681 >>> list(keys) 4682 ['eggs', 'sausage', 'bacon', 'spam'] 4683 >>> list(values) 4684 [2, 1, 1, 500] 4685 4686 >>> # view objects are dynamic and reflect dict changes 4687 >>> del dishes['eggs'] 4688 >>> del dishes['sausage'] 4689 >>> list(keys) 4690 ['bacon', 'spam'] 4691 4692 >>> # set operations 4693 >>> keys & {'eggs', 'bacon', 'salad'} 4694 {'bacon'} 4695 >>> keys ^ {'sausage', 'juice'} 4696 {'juice', 'sausage', 'bacon', 'spam'} 4697 4698 >>> # get back a read-only proxy for the original dictionary 4699 >>> values.mapping 4700 mappingproxy({'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}) 4701 >>> values.mapping['spam'] 4702 500 4703 4704 4705.. _typecontextmanager: 4706 4707Context Manager Types 4708===================== 4709 4710.. index:: 4711 single: context manager 4712 single: context management protocol 4713 single: protocol; context management 4714 4715Python's :keyword:`with` statement supports the concept of a runtime context 4716defined by a context manager. This is implemented using a pair of methods 4717that allow user-defined classes to define a runtime context that is entered 4718before the statement body is executed and exited when the statement ends: 4719 4720 4721.. method:: contextmanager.__enter__() 4722 4723 Enter the runtime context and return either this object or another object 4724 related to the runtime context. The value returned by this method is bound to 4725 the identifier in the :keyword:`!as` clause of :keyword:`with` statements using 4726 this context manager. 4727 4728 An example of a context manager that returns itself is a :term:`file object`. 4729 File objects return themselves from __enter__() to allow :func:`open` to be 4730 used as the context expression in a :keyword:`with` statement. 4731 4732 An example of a context manager that returns a related object is the one 4733 returned by :func:`decimal.localcontext`. These managers set the active 4734 decimal context to a copy of the original decimal context and then return the 4735 copy. This allows changes to be made to the current decimal context in the body 4736 of the :keyword:`with` statement without affecting code outside the 4737 :keyword:`!with` statement. 4738 4739 4740.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb) 4741 4742 Exit the runtime context and return a Boolean flag indicating if any exception 4743 that occurred should be suppressed. If an exception occurred while executing the 4744 body of the :keyword:`with` statement, the arguments contain the exception type, 4745 value and traceback information. Otherwise, all three arguments are ``None``. 4746 4747 Returning a true value from this method will cause the :keyword:`with` statement 4748 to suppress the exception and continue execution with the statement immediately 4749 following the :keyword:`!with` statement. Otherwise the exception continues 4750 propagating after this method has finished executing. Exceptions that occur 4751 during execution of this method will replace any exception that occurred in the 4752 body of the :keyword:`!with` statement. 4753 4754 The exception passed in should never be reraised explicitly - instead, this 4755 method should return a false value to indicate that the method completed 4756 successfully and does not want to suppress the raised exception. This allows 4757 context management code to easily detect whether or not an :meth:`__exit__` 4758 method has actually failed. 4759 4760Python defines several context managers to support easy thread synchronisation, 4761prompt closure of files or other objects, and simpler manipulation of the active 4762decimal arithmetic context. The specific types are not treated specially beyond 4763their implementation of the context management protocol. See the 4764:mod:`contextlib` module for some examples. 4765 4766Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator 4767provide a convenient way to implement these protocols. If a generator function is 4768decorated with the :class:`contextlib.contextmanager` decorator, it will return a 4769context manager implementing the necessary :meth:`~contextmanager.__enter__` and 4770:meth:`~contextmanager.__exit__` methods, rather than the iterator produced by an 4771undecorated generator function. 4772 4773Note that there is no specific slot for any of these methods in the type 4774structure for Python objects in the Python/C API. Extension types wanting to 4775define these methods must provide them as a normal Python accessible method. 4776Compared to the overhead of setting up the runtime context, the overhead of a 4777single class dictionary lookup is negligible. 4778 4779 4780Type Annotation Types --- :ref:`Generic Alias <types-genericalias>`, :ref:`Union <types-union>` 4781=============================================================================================== 4782 4783.. index:: 4784 single: annotation; type annotation; type hint 4785 4786The core built-in types for :term:`type annotations <annotation>` are 4787:ref:`Generic Alias <types-genericalias>` and :ref:`Union <types-union>`. 4788 4789 4790.. _types-genericalias: 4791 4792Generic Alias Type 4793------------------ 4794 4795.. index:: 4796 object: GenericAlias 4797 pair: Generic; Alias 4798 4799``GenericAlias`` objects are created by subscripting a class (usually a 4800container), such as ``list[int]``. They are intended primarily for 4801:term:`type annotations <annotation>`. 4802 4803Usually, the :ref:`subscription <subscriptions>` of container objects calls the 4804method :meth:`__getitem__` of the object. However, the subscription of some 4805containers' classes may call the classmethod :meth:`__class_getitem__` of the 4806class instead. The classmethod :meth:`__class_getitem__` should return a 4807``GenericAlias`` object. 4808 4809.. note:: 4810 If the :meth:`__getitem__` of the class' metaclass is present, it will take 4811 precedence over the :meth:`__class_getitem__` defined in the class (see 4812 :pep:`560` for more details). 4813 4814The ``GenericAlias`` object acts as a proxy for :term:`generic types 4815<generic type>`, implementing *parameterized generics* - a specific instance 4816of a generic which provides the types for container elements. 4817 4818The user-exposed type for the ``GenericAlias`` object can be accessed from 4819:class:`types.GenericAlias` and used for :func:`isinstance` checks. It can 4820also be used to create ``GenericAlias`` objects directly. 4821 4822.. describe:: T[X, Y, ...] 4823 4824 Creates a ``GenericAlias`` representing a type ``T`` containing elements 4825 of types *X*, *Y*, and more depending on the ``T`` used. 4826 For example, a function expecting a :class:`list` containing 4827 :class:`float` elements:: 4828 4829 def average(values: list[float]) -> float: 4830 return sum(values) / len(values) 4831 4832 Another example for :term:`mapping` objects, using a :class:`dict`, which 4833 is a generic type expecting two type parameters representing the key type 4834 and the value type. In this example, the function expects a ``dict`` with 4835 keys of type :class:`str` and values of type :class:`int`:: 4836 4837 def send_post_request(url: str, body: dict[str, int]) -> None: 4838 ... 4839 4840The builtin functions :func:`isinstance` and :func:`issubclass` do not accept 4841``GenericAlias`` types for their second argument:: 4842 4843 >>> isinstance([1, 2], list[str]) 4844 Traceback (most recent call last): 4845 File "<stdin>", line 1, in <module> 4846 TypeError: isinstance() argument 2 cannot be a parameterized generic 4847 4848The Python runtime does not enforce :term:`type annotations <annotation>`. 4849This extends to generic types and their type parameters. When creating 4850an object from a ``GenericAlias``, container elements are not checked 4851against their type. For example, the following code is discouraged, but will 4852run without errors:: 4853 4854 >>> t = list[str] 4855 >>> t([1, 2, 3]) 4856 [1, 2, 3] 4857 4858Furthermore, parameterized generics erase type parameters during object 4859creation:: 4860 4861 >>> t = list[str] 4862 >>> type(t) 4863 <class 'types.GenericAlias'> 4864 4865 >>> l = t() 4866 >>> type(l) 4867 <class 'list'> 4868 4869Calling :func:`repr` or :func:`str` on a generic shows the parameterized type:: 4870 4871 >>> repr(list[int]) 4872 'list[int]' 4873 4874 >>> str(list[int]) 4875 'list[int]' 4876 4877The :meth:`__getitem__` method of generics will raise an exception to disallow 4878mistakes like ``dict[str][str]``:: 4879 4880 >>> dict[str][str] 4881 Traceback (most recent call last): 4882 File "<stdin>", line 1, in <module> 4883 TypeError: There are no type variables left in dict[str] 4884 4885However, such expressions are valid when :ref:`type variables <generics>` are 4886used. The index must have as many elements as there are type variable items 4887in the ``GenericAlias`` object's :attr:`__args__ <genericalias.__args__>`. :: 4888 4889 >>> from typing import TypeVar 4890 >>> Y = TypeVar('Y') 4891 >>> dict[str, Y][int] 4892 dict[str, int] 4893 4894 4895Standard Generic Collections 4896^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4897 4898These standard library collections support parameterized generics. 4899 4900* :class:`tuple` 4901* :class:`list` 4902* :class:`dict` 4903* :class:`set` 4904* :class:`frozenset` 4905* :class:`type` 4906* :class:`collections.deque` 4907* :class:`collections.defaultdict` 4908* :class:`collections.OrderedDict` 4909* :class:`collections.Counter` 4910* :class:`collections.ChainMap` 4911* :class:`collections.abc.Awaitable` 4912* :class:`collections.abc.Coroutine` 4913* :class:`collections.abc.AsyncIterable` 4914* :class:`collections.abc.AsyncIterator` 4915* :class:`collections.abc.AsyncGenerator` 4916* :class:`collections.abc.Iterable` 4917* :class:`collections.abc.Iterator` 4918* :class:`collections.abc.Generator` 4919* :class:`collections.abc.Reversible` 4920* :class:`collections.abc.Container` 4921* :class:`collections.abc.Collection` 4922* :class:`collections.abc.Callable` 4923* :class:`collections.abc.Set` 4924* :class:`collections.abc.MutableSet` 4925* :class:`collections.abc.Mapping` 4926* :class:`collections.abc.MutableMapping` 4927* :class:`collections.abc.Sequence` 4928* :class:`collections.abc.MutableSequence` 4929* :class:`collections.abc.ByteString` 4930* :class:`collections.abc.MappingView` 4931* :class:`collections.abc.KeysView` 4932* :class:`collections.abc.ItemsView` 4933* :class:`collections.abc.ValuesView` 4934* :class:`contextlib.AbstractContextManager` 4935* :class:`contextlib.AbstractAsyncContextManager` 4936* :ref:`re.Pattern <re-objects>` 4937* :ref:`re.Match <match-objects>` 4938 4939 4940Special Attributes of Generic Alias 4941^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4942 4943All parameterized generics implement special read-only attributes. 4944 4945.. attribute:: genericalias.__origin__ 4946 4947 This attribute points at the non-parameterized generic class:: 4948 4949 >>> list[int].__origin__ 4950 <class 'list'> 4951 4952 4953.. attribute:: genericalias.__args__ 4954 4955 This attribute is a :class:`tuple` (possibly of length 1) of generic 4956 types passed to the original :meth:`__class_getitem__` 4957 of the generic container:: 4958 4959 >>> dict[str, list[int]].__args__ 4960 (<class 'str'>, list[int]) 4961 4962 4963.. attribute:: genericalias.__parameters__ 4964 4965 This attribute is a lazily computed tuple (possibly empty) of unique type 4966 variables found in ``__args__``:: 4967 4968 >>> from typing import TypeVar 4969 4970 >>> T = TypeVar('T') 4971 >>> list[T].__parameters__ 4972 (~T,) 4973 4974 4975 .. note:: 4976 A ``GenericAlias`` object with :class:`typing.ParamSpec` parameters may not 4977 have correct ``__parameters__`` after substitution because 4978 :class:`typing.ParamSpec` is intended primarily for static type checking. 4979 4980.. seealso:: 4981 4982 * :pep:`585` -- "Type Hinting Generics In Standard Collections" 4983 * :meth:`__class_getitem__` -- Used to implement parameterized generics. 4984 * :ref:`generics` -- Generics in the :mod:`typing` module. 4985 4986.. versionadded:: 3.9 4987 4988 4989.. _types-union: 4990 4991Union Type 4992---------- 4993 4994.. index:: 4995 object: Union 4996 pair: union; type 4997 4998A union object holds the value of the ``|`` (bitwise or) operation on 4999multiple :ref:`type objects <bltin-type-objects>`. These types are intended 5000primarily for :term:`type annotations <annotation>`. The union type expression 5001enables cleaner type hinting syntax compared to :data:`typing.Union`. 5002 5003.. describe:: X | Y | ... 5004 5005 Defines a union object which holds types *X*, *Y*, and so forth. ``X | Y`` 5006 means either X or Y. It is equivalent to ``typing.Union[X, Y]``. 5007 For example, the following function expects an argument of type 5008 :class:`int` or :class:`float`:: 5009 5010 def square(number: int | float) -> int | float: 5011 return number ** 2 5012 5013.. describe:: union_object == other 5014 5015 Union objects can be tested for equality with other union objects. Details: 5016 5017 * Unions of unions are flattened:: 5018 5019 (int | str) | float == int | str | float 5020 5021 * Redundant types are removed:: 5022 5023 int | str | int == int | str 5024 5025 * When comparing unions, the order is ignored:: 5026 5027 int | str == str | int 5028 5029 * It is compatible with :data:`typing.Union`:: 5030 5031 int | str == typing.Union[int, str] 5032 5033 * Optional types can be spelled as a union with ``None``:: 5034 5035 str | None == typing.Optional[str] 5036 5037.. describe:: isinstance(obj, union_object) 5038.. describe:: issubclass(obj, union_object) 5039 5040 Calls to :func:`isinstance` and :func:`issubclass` are also supported with a 5041 union object:: 5042 5043 >>> isinstance("", int | str) 5044 True 5045 5046 However, union objects containing :ref:`parameterized generics 5047 <types-genericalias>` cannot be used:: 5048 5049 >>> isinstance(1, int | list[int]) 5050 Traceback (most recent call last): 5051 File "<stdin>", line 1, in <module> 5052 TypeError: isinstance() argument 2 cannot contain a parameterized generic 5053 5054The user-exposed type for the union object can be accessed from 5055:data:`types.UnionType` and used for :func:`isinstance` checks. An object cannot be 5056instantiated from the type:: 5057 5058 >>> import types 5059 >>> isinstance(int | str, types.UnionType) 5060 True 5061 >>> types.UnionType() 5062 Traceback (most recent call last): 5063 File "<stdin>", line 1, in <module> 5064 TypeError: cannot create 'types.UnionType' instances 5065 5066.. note:: 5067 The :meth:`__or__` method for type objects was added to support the syntax 5068 ``X | Y``. If a metaclass implements :meth:`__or__`, the Union may 5069 override it:: 5070 5071 >>> class M(type): 5072 ... def __or__(self, other): 5073 ... return "Hello" 5074 ... 5075 >>> class C(metaclass=M): 5076 ... pass 5077 ... 5078 >>> C | int 5079 'Hello' 5080 >>> int | C 5081 int | __main__.C 5082 5083.. seealso:: 5084 5085 :pep:`604` -- PEP proposing the ``X | Y`` syntax and the Union type. 5086 5087.. versionadded:: 3.10 5088 5089 5090.. _typesother: 5091 5092Other Built-in Types 5093==================== 5094 5095The interpreter supports several other kinds of objects. Most of these support 5096only one or two operations. 5097 5098 5099.. _typesmodules: 5100 5101Modules 5102------- 5103 5104The only special operation on a module is attribute access: ``m.name``, where 5105*m* is a module and *name* accesses a name defined in *m*'s symbol table. 5106Module attributes can be assigned to. (Note that the :keyword:`import` 5107statement is not, strictly speaking, an operation on a module object; ``import 5108foo`` does not require a module object named *foo* to exist, rather it requires 5109an (external) *definition* for a module named *foo* somewhere.) 5110 5111A special attribute of every module is :attr:`~object.__dict__`. This is the 5112dictionary containing the module's symbol table. Modifying this dictionary will 5113actually change the module's symbol table, but direct assignment to the 5114:attr:`~object.__dict__` attribute is not possible (you can write 5115``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write 5116``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is 5117not recommended. 5118 5119Modules built into the interpreter are written like this: ``<module 'sys' 5120(built-in)>``. If loaded from a file, they are written as ``<module 'os' from 5121'/usr/local/lib/pythonX.Y/os.pyc'>``. 5122 5123 5124.. _typesobjects: 5125 5126Classes and Class Instances 5127--------------------------- 5128 5129See :ref:`objects` and :ref:`class` for these. 5130 5131 5132.. _typesfunctions: 5133 5134Functions 5135--------- 5136 5137Function objects are created by function definitions. The only operation on a 5138function object is to call it: ``func(argument-list)``. 5139 5140There are really two flavors of function objects: built-in functions and 5141user-defined functions. Both support the same operation (to call the function), 5142but the implementation is different, hence the different object types. 5143 5144See :ref:`function` for more information. 5145 5146 5147.. _typesmethods: 5148 5149Methods 5150------- 5151 5152.. index:: object: method 5153 5154Methods are functions that are called using the attribute notation. There are 5155two flavors: built-in methods (such as :meth:`append` on lists) and class 5156instance methods. Built-in methods are described with the types that support 5157them. 5158 5159If you access a method (a function defined in a class namespace) through an 5160instance, you get a special object: a :dfn:`bound method` (also called 5161:dfn:`instance method`) object. When called, it will add the ``self`` argument 5162to the argument list. Bound methods have two special read-only attributes: 5163``m.__self__`` is the object on which the method operates, and ``m.__func__`` is 5164the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` 5165is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., 5166arg-n)``. 5167 5168Like function objects, bound method objects support getting arbitrary 5169attributes. However, since method attributes are actually stored on the 5170underlying function object (``meth.__func__``), setting method attributes on 5171bound methods is disallowed. Attempting to set an attribute on a method 5172results in an :exc:`AttributeError` being raised. In order to set a method 5173attribute, you need to explicitly set it on the underlying function object:: 5174 5175 >>> class C: 5176 ... def method(self): 5177 ... pass 5178 ... 5179 >>> c = C() 5180 >>> c.method.whoami = 'my name is method' # can't set on the method 5181 Traceback (most recent call last): 5182 File "<stdin>", line 1, in <module> 5183 AttributeError: 'method' object has no attribute 'whoami' 5184 >>> c.method.__func__.whoami = 'my name is method' 5185 >>> c.method.whoami 5186 'my name is method' 5187 5188See :ref:`types` for more information. 5189 5190 5191.. index:: object; code, code object 5192 5193.. _bltin-code-objects: 5194 5195Code Objects 5196------------ 5197 5198.. index:: 5199 builtin: compile 5200 single: __code__ (function object attribute) 5201 5202Code objects are used by the implementation to represent "pseudo-compiled" 5203executable Python code such as a function body. They differ from function 5204objects because they don't contain a reference to their global execution 5205environment. Code objects are returned by the built-in :func:`compile` function 5206and can be extracted from function objects through their :attr:`__code__` 5207attribute. See also the :mod:`code` module. 5208 5209Accessing ``__code__`` raises an :ref:`auditing event <auditing>` 5210``object.__getattr__`` with arguments ``obj`` and ``"__code__"``. 5211 5212.. index:: 5213 builtin: exec 5214 builtin: eval 5215 5216A code object can be executed or evaluated by passing it (instead of a source 5217string) to the :func:`exec` or :func:`eval` built-in functions. 5218 5219See :ref:`types` for more information. 5220 5221 5222.. _bltin-type-objects: 5223 5224Type Objects 5225------------ 5226 5227.. index:: 5228 builtin: type 5229 module: types 5230 5231Type objects represent the various object types. An object's type is accessed 5232by the built-in function :func:`type`. There are no special operations on 5233types. The standard module :mod:`types` defines names for all standard built-in 5234types. 5235 5236Types are written like this: ``<class 'int'>``. 5237 5238 5239.. _bltin-null-object: 5240 5241The Null Object 5242--------------- 5243 5244This object is returned by functions that don't explicitly return a value. It 5245supports no special operations. There is exactly one null object, named 5246``None`` (a built-in name). ``type(None)()`` produces the same singleton. 5247 5248It is written as ``None``. 5249 5250 5251.. index:: single: ...; ellipsis literal 5252.. _bltin-ellipsis-object: 5253 5254The Ellipsis Object 5255------------------- 5256 5257This object is commonly used by slicing (see :ref:`slicings`). It supports no 5258special operations. There is exactly one ellipsis object, named 5259:const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the 5260:const:`Ellipsis` singleton. 5261 5262It is written as ``Ellipsis`` or ``...``. 5263 5264 5265.. _bltin-notimplemented-object: 5266 5267The NotImplemented Object 5268------------------------- 5269 5270This object is returned from comparisons and binary operations when they are 5271asked to operate on types they don't support. See :ref:`comparisons` for more 5272information. There is exactly one ``NotImplemented`` object. 5273``type(NotImplemented)()`` produces the singleton instance. 5274 5275It is written as ``NotImplemented``. 5276 5277 5278.. _bltin-boolean-values: 5279 5280Boolean Values 5281-------------- 5282 5283Boolean values are the two constant objects ``False`` and ``True``. They are 5284used to represent truth values (although other values can also be considered 5285false or true). In numeric contexts (for example when used as the argument to 5286an arithmetic operator), they behave like the integers 0 and 1, respectively. 5287The built-in function :func:`bool` can be used to convert any value to a 5288Boolean, if the value can be interpreted as a truth value (see section 5289:ref:`truth` above). 5290 5291.. index:: 5292 single: False 5293 single: True 5294 pair: Boolean; values 5295 5296They are written as ``False`` and ``True``, respectively. 5297 5298 5299.. _typesinternal: 5300 5301Internal Objects 5302---------------- 5303 5304See :ref:`types` for this information. It describes stack frame objects, 5305traceback objects, and slice objects. 5306 5307 5308.. _specialattrs: 5309 5310Special Attributes 5311================== 5312 5313The implementation adds a few special read-only attributes to several object 5314types, where they are relevant. Some of these are not reported by the 5315:func:`dir` built-in function. 5316 5317 5318.. attribute:: object.__dict__ 5319 5320 A dictionary or other mapping object used to store an object's (writable) 5321 attributes. 5322 5323 5324.. attribute:: instance.__class__ 5325 5326 The class to which a class instance belongs. 5327 5328 5329.. attribute:: class.__bases__ 5330 5331 The tuple of base classes of a class object. 5332 5333 5334.. attribute:: definition.__name__ 5335 5336 The name of the class, function, method, descriptor, or 5337 generator instance. 5338 5339 5340.. attribute:: definition.__qualname__ 5341 5342 The :term:`qualified name` of the class, function, method, descriptor, 5343 or generator instance. 5344 5345 .. versionadded:: 3.3 5346 5347 5348.. attribute:: class.__mro__ 5349 5350 This attribute is a tuple of classes that are considered when looking for 5351 base classes during method resolution. 5352 5353 5354.. method:: class.mro() 5355 5356 This method can be overridden by a metaclass to customize the method 5357 resolution order for its instances. It is called at class instantiation, and 5358 its result is stored in :attr:`~class.__mro__`. 5359 5360 5361.. method:: class.__subclasses__ 5362 5363 Each class keeps a list of weak references to its immediate subclasses. This 5364 method returns a list of all those references still alive. The list is in 5365 definition order. Example:: 5366 5367 >>> int.__subclasses__() 5368 [<class 'bool'>] 5369 5370 5371.. rubric:: Footnotes 5372 5373.. [1] Additional information on these special methods may be found in the Python 5374 Reference Manual (:ref:`customization`). 5375 5376.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and 5377 similarly for tuples. 5378 5379.. [3] They must have since the parser can't tell the type of the operands. 5380 5381.. [4] Cased characters are those with general category property being one of 5382 "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase). 5383 5384.. [5] To format only a tuple you should therefore provide a singleton tuple whose only 5385 element is the tuple to be formatted. 5386