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