1 2.. _expressions: 3 4*********** 5Expressions 6*********** 7 8.. index:: expression, BNF 9 10This chapter explains the meaning of the elements of expressions in Python. 11 12**Syntax Notes:** In this and the following chapters, extended BNF notation will 13be used to describe syntax, not lexical analysis. When (one alternative of) a 14syntax rule has the form 15 16.. productionlist:: python-grammar 17 name: `othername` 18 19and no semantics are given, the semantics of this form of ``name`` are the same 20as for ``othername``. 21 22 23.. _conversions: 24 25Arithmetic conversions 26====================== 27 28.. index:: pair: arithmetic; conversion 29 30When a description of an arithmetic operator below uses the phrase "the numeric 31arguments are converted to a common type", this means that the operator 32implementation for built-in types works as follows: 33 34* If either argument is a complex number, the other is converted to complex; 35 36* otherwise, if either argument is a floating point number, the other is 37 converted to floating point; 38 39* otherwise, both must be integers and no conversion is necessary. 40 41Some additional rules apply for certain operators (e.g., a string as a left 42argument to the '%' operator). Extensions must define their own conversion 43behavior. 44 45 46.. _atoms: 47 48Atoms 49===== 50 51.. index:: atom 52 53Atoms are the most basic elements of expressions. The simplest atoms are 54identifiers or literals. Forms enclosed in parentheses, brackets or braces are 55also categorized syntactically as atoms. The syntax for atoms is: 56 57.. productionlist:: python-grammar 58 atom: `identifier` | `literal` | `enclosure` 59 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display` 60 : | `generator_expression` | `yield_atom` 61 62 63.. _atom-identifiers: 64 65Identifiers (Names) 66------------------- 67 68.. index:: name, identifier 69 70An identifier occurring as an atom is a name. See section :ref:`identifiers` 71for lexical definition and section :ref:`naming` for documentation of naming and 72binding. 73 74.. index:: pair: exception; NameError 75 76When the name is bound to an object, evaluation of the atom yields that object. 77When a name is not bound, an attempt to evaluate it raises a :exc:`NameError` 78exception. 79 80.. _private-name-mangling: 81 82.. index:: 83 pair: name; mangling 84 pair: private; names 85 86**Private name mangling:** When an identifier that textually occurs in a class 87definition begins with two or more underscore characters and does not end in two 88or more underscores, it is considered a :dfn:`private name` of that class. 89Private names are transformed to a longer form before code is generated for 90them. The transformation inserts the class name, with leading underscores 91removed and a single underscore inserted, in front of the name. For example, 92the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed 93to ``_Ham__spam``. This transformation is independent of the syntactical 94context in which the identifier is used. If the transformed name is extremely 95long (longer than 255 characters), implementation defined truncation may happen. 96If the class name consists only of underscores, no transformation is done. 97 98 99.. _atom-literals: 100 101Literals 102-------- 103 104.. index:: single: literal 105 106Python supports string and bytes literals and various numeric literals: 107 108.. productionlist:: python-grammar 109 literal: `stringliteral` | `bytesliteral` 110 : | `integer` | `floatnumber` | `imagnumber` 111 112Evaluation of a literal yields an object of the given type (string, bytes, 113integer, floating point number, complex number) with the given value. The value 114may be approximated in the case of floating point and imaginary (complex) 115literals. See section :ref:`literals` for details. 116 117.. index:: 118 triple: immutable; data; type 119 pair: immutable; object 120 121All literals correspond to immutable data types, and hence the object's identity 122is less important than its value. Multiple evaluations of literals with the 123same value (either the same occurrence in the program text or a different 124occurrence) may obtain the same object or a different object with the same 125value. 126 127 128.. _parenthesized: 129 130Parenthesized forms 131------------------- 132 133.. index:: 134 single: parenthesized form 135 single: () (parentheses); tuple display 136 137A parenthesized form is an optional expression list enclosed in parentheses: 138 139.. productionlist:: python-grammar 140 parenth_form: "(" [`starred_expression`] ")" 141 142A parenthesized expression list yields whatever that expression list yields: if 143the list contains at least one comma, it yields a tuple; otherwise, it yields 144the single expression that makes up the expression list. 145 146.. index:: pair: empty; tuple 147 148An empty pair of parentheses yields an empty tuple object. Since tuples are 149immutable, the same rules as for literals apply (i.e., two occurrences of the empty 150tuple may or may not yield the same object). 151 152.. index:: 153 single: comma 154 single: , (comma) 155 156Note that tuples are not formed by the parentheses, but rather by use of the 157comma. The exception is the empty tuple, for which parentheses *are* 158required --- allowing unparenthesized "nothing" in expressions would cause 159ambiguities and allow common typos to pass uncaught. 160 161 162.. _comprehensions: 163 164Displays for lists, sets and dictionaries 165----------------------------------------- 166 167.. index:: single: comprehensions 168 169For constructing a list, a set or a dictionary Python provides special syntax 170called "displays", each of them in two flavors: 171 172* either the container contents are listed explicitly, or 173 174* they are computed via a set of looping and filtering instructions, called a 175 :dfn:`comprehension`. 176 177.. index:: 178 single: for; in comprehensions 179 single: if; in comprehensions 180 single: async for; in comprehensions 181 182Common syntax elements for comprehensions are: 183 184.. productionlist:: python-grammar 185 comprehension: `assignment_expression` `comp_for` 186 comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`] 187 comp_iter: `comp_for` | `comp_if` 188 comp_if: "if" `or_test` [`comp_iter`] 189 190The comprehension consists of a single expression followed by at least one 191:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses. 192In this case, the elements of the new container are those that would be produced 193by considering each of the :keyword:`!for` or :keyword:`!if` clauses a block, 194nesting from left to right, and evaluating the expression to produce an element 195each time the innermost block is reached. 196 197However, aside from the iterable expression in the leftmost :keyword:`!for` clause, 198the comprehension is executed in a separate implicitly nested scope. This ensures 199that names assigned to in the target list don't "leak" into the enclosing scope. 200 201The iterable expression in the leftmost :keyword:`!for` clause is evaluated 202directly in the enclosing scope and then passed as an argument to the implicitly 203nested scope. Subsequent :keyword:`!for` clauses and any filter condition in the 204leftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as 205they may depend on the values obtained from the leftmost iterable. For example: 206``[x*y for x in range(10) for y in range(x, x+10)]``. 207 208To ensure the comprehension always results in a container of the appropriate 209type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly 210nested scope. 211 212.. index:: 213 single: await; in comprehensions 214 215Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for` 216clause may be used to iterate over a :term:`asynchronous iterator`. 217A comprehension in an :keyword:`!async def` function may consist of either a 218:keyword:`!for` or :keyword:`!async for` clause following the leading 219expression, may contain additional :keyword:`!for` or :keyword:`!async for` 220clauses, and may also use :keyword:`await` expressions. 221If a comprehension contains either :keyword:`!async for` clauses or 222:keyword:`!await` expressions or other asynchronous comprehensions it is called 223an :dfn:`asynchronous comprehension`. An asynchronous comprehension may 224suspend the execution of the coroutine function in which it appears. 225See also :pep:`530`. 226 227.. versionadded:: 3.6 228 Asynchronous comprehensions were introduced. 229 230.. versionchanged:: 3.8 231 ``yield`` and ``yield from`` prohibited in the implicitly nested scope. 232 233.. versionchanged:: 3.11 234 Asynchronous comprehensions are now allowed inside comprehensions in 235 asynchronous functions. Outer comprehensions implicitly become 236 asynchronous. 237 238 239.. _lists: 240 241List displays 242------------- 243 244.. index:: 245 pair: list; display 246 pair: list; comprehensions 247 pair: empty; list 248 pair: object; list 249 single: [] (square brackets); list expression 250 single: , (comma); expression list 251 252A list display is a possibly empty series of expressions enclosed in square 253brackets: 254 255.. productionlist:: python-grammar 256 list_display: "[" [`starred_list` | `comprehension`] "]" 257 258A list display yields a new list object, the contents being specified by either 259a list of expressions or a comprehension. When a comma-separated list of 260expressions is supplied, its elements are evaluated from left to right and 261placed into the list object in that order. When a comprehension is supplied, 262the list is constructed from the elements resulting from the comprehension. 263 264 265.. _set: 266 267Set displays 268------------ 269 270.. index:: 271 pair: set; display 272 pair: set; comprehensions 273 pair: object; set 274 single: {} (curly brackets); set expression 275 single: , (comma); expression list 276 277A set display is denoted by curly braces and distinguishable from dictionary 278displays by the lack of colons separating keys and values: 279 280.. productionlist:: python-grammar 281 set_display: "{" (`starred_list` | `comprehension`) "}" 282 283A set display yields a new mutable set object, the contents being specified by 284either a sequence of expressions or a comprehension. When a comma-separated 285list of expressions is supplied, its elements are evaluated from left to right 286and added to the set object. When a comprehension is supplied, the set is 287constructed from the elements resulting from the comprehension. 288 289An empty set cannot be constructed with ``{}``; this literal constructs an empty 290dictionary. 291 292 293.. _dict: 294 295Dictionary displays 296------------------- 297 298.. index:: 299 pair: dictionary; display 300 pair: dictionary; comprehensions 301 key, datum, key/datum pair 302 pair: object; dictionary 303 single: {} (curly brackets); dictionary expression 304 single: : (colon); in dictionary expressions 305 single: , (comma); in dictionary displays 306 307A dictionary display is a possibly empty series of key/datum pairs enclosed in 308curly braces: 309 310.. productionlist:: python-grammar 311 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}" 312 key_datum_list: `key_datum` ("," `key_datum`)* [","] 313 key_datum: `expression` ":" `expression` | "**" `or_expr` 314 dict_comprehension: `expression` ":" `expression` `comp_for` 315 316A dictionary display yields a new dictionary object. 317 318If a comma-separated sequence of key/datum pairs is given, they are evaluated 319from left to right to define the entries of the dictionary: each key object is 320used as a key into the dictionary to store the corresponding datum. This means 321that you can specify the same key multiple times in the key/datum list, and the 322final dictionary's value for that key will be the last one given. 323 324.. index:: 325 unpacking; dictionary 326 single: **; in dictionary displays 327 328A double asterisk ``**`` denotes :dfn:`dictionary unpacking`. 329Its operand must be a :term:`mapping`. Each mapping item is added 330to the new dictionary. Later values replace values already set by 331earlier key/datum pairs and earlier dictionary unpackings. 332 333.. versionadded:: 3.5 334 Unpacking into dictionary displays, originally proposed by :pep:`448`. 335 336A dict comprehension, in contrast to list and set comprehensions, needs two 337expressions separated with a colon followed by the usual "for" and "if" clauses. 338When the comprehension is run, the resulting key and value elements are inserted 339in the new dictionary in the order they are produced. 340 341.. index:: pair: immutable; object 342 hashable 343 344Restrictions on the types of the key values are listed earlier in section 345:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes 346all mutable objects.) Clashes between duplicate keys are not detected; the last 347datum (textually rightmost in the display) stored for a given key value 348prevails. 349 350.. versionchanged:: 3.8 351 Prior to Python 3.8, in dict comprehensions, the evaluation order of key 352 and value was not well-defined. In CPython, the value was evaluated before 353 the key. Starting with 3.8, the key is evaluated before the value, as 354 proposed by :pep:`572`. 355 356 357.. _genexpr: 358 359Generator expressions 360--------------------- 361 362.. index:: 363 pair: generator; expression 364 pair: object; generator 365 single: () (parentheses); generator expression 366 367A generator expression is a compact generator notation in parentheses: 368 369.. productionlist:: python-grammar 370 generator_expression: "(" `expression` `comp_for` ")" 371 372A generator expression yields a new generator object. Its syntax is the same as 373for comprehensions, except that it is enclosed in parentheses instead of 374brackets or curly braces. 375 376Variables used in the generator expression are evaluated lazily when the 377:meth:`~generator.__next__` method is called for the generator object (in the same 378fashion as normal generators). However, the iterable expression in the 379leftmost :keyword:`!for` clause is immediately evaluated, so that an error 380produced by it will be emitted at the point where the generator expression 381is defined, rather than at the point where the first value is retrieved. 382Subsequent :keyword:`!for` clauses and any filter condition in the leftmost 383:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may 384depend on the values obtained from the leftmost iterable. For example: 385``(x*y for x in range(10) for y in range(x, x+10))``. 386 387The parentheses can be omitted on calls with only one argument. See section 388:ref:`calls` for details. 389 390To avoid interfering with the expected operation of the generator expression 391itself, ``yield`` and ``yield from`` expressions are prohibited in the 392implicitly defined generator. 393 394If a generator expression contains either :keyword:`!async for` 395clauses or :keyword:`await` expressions it is called an 396:dfn:`asynchronous generator expression`. An asynchronous generator 397expression returns a new asynchronous generator object, 398which is an asynchronous iterator (see :ref:`async-iterators`). 399 400.. versionadded:: 3.6 401 Asynchronous generator expressions were introduced. 402 403.. versionchanged:: 3.7 404 Prior to Python 3.7, asynchronous generator expressions could 405 only appear in :keyword:`async def` coroutines. Starting 406 with 3.7, any function can use asynchronous generator expressions. 407 408.. versionchanged:: 3.8 409 ``yield`` and ``yield from`` prohibited in the implicitly nested scope. 410 411 412.. _yieldexpr: 413 414Yield expressions 415----------------- 416 417.. index:: 418 pair: keyword; yield 419 pair: keyword; from 420 pair: yield; expression 421 pair: generator; function 422 423.. productionlist:: python-grammar 424 yield_atom: "(" `yield_expression` ")" 425 yield_expression: "yield" [`expression_list` | "from" `expression`] 426 427The yield expression is used when defining a :term:`generator` function 428or an :term:`asynchronous generator` function and 429thus can only be used in the body of a function definition. Using a yield 430expression in a function's body causes that function to be a generator function, 431and using it in an :keyword:`async def` function's body causes that 432coroutine function to be an asynchronous generator function. For example:: 433 434 def gen(): # defines a generator function 435 yield 123 436 437 async def agen(): # defines an asynchronous generator function 438 yield 123 439 440Due to their side effects on the containing scope, ``yield`` expressions 441are not permitted as part of the implicitly defined scopes used to 442implement comprehensions and generator expressions. 443 444.. versionchanged:: 3.8 445 Yield expressions prohibited in the implicitly nested scopes used to 446 implement comprehensions and generator expressions. 447 448Generator functions are described below, while asynchronous generator 449functions are described separately in section 450:ref:`asynchronous-generator-functions`. 451 452When a generator function is called, it returns an iterator known as a 453generator. That generator then controls the execution of the generator 454function. The execution starts when one of the generator's methods is called. 455At that time, the execution proceeds to the first yield expression, where it is 456suspended again, returning the value of :token:`~python-grammar:expression_list` 457to the generator's caller, 458or ``None`` if :token:`~python-grammar:expression_list` is omitted. 459By suspended, we mean that all local state is 460retained, including the current bindings of local variables, the instruction 461pointer, the internal evaluation stack, and the state of any exception handling. 462When the execution is resumed by calling one of the generator's methods, the 463function can proceed exactly as if the yield expression were just another 464external call. The value of the yield expression after resuming depends on the 465method which resumed the execution. If :meth:`~generator.__next__` is used 466(typically via either a :keyword:`for` or the :func:`next` builtin) then the 467result is :const:`None`. Otherwise, if :meth:`~generator.send` is used, then 468the result will be the value passed in to that method. 469 470.. index:: single: coroutine 471 472All of this makes generator functions quite similar to coroutines; they yield 473multiple times, they have more than one entry point and their execution can be 474suspended. The only difference is that a generator function cannot control 475where the execution should continue after it yields; the control is always 476transferred to the generator's caller. 477 478Yield expressions are allowed anywhere in a :keyword:`try` construct. If the 479generator is not resumed before it is 480finalized (by reaching a zero reference count or by being garbage collected), 481the generator-iterator's :meth:`~generator.close` method will be called, 482allowing any pending :keyword:`finally` clauses to execute. 483 484.. index:: 485 single: from; yield from expression 486 487When ``yield from <expr>`` is used, the supplied expression must be an 488iterable. The values produced by iterating that iterable are passed directly 489to the caller of the current generator's methods. Any values passed in with 490:meth:`~generator.send` and any exceptions passed in with 491:meth:`~generator.throw` are passed to the underlying iterator if it has the 492appropriate methods. If this is not the case, then :meth:`~generator.send` 493will raise :exc:`AttributeError` or :exc:`TypeError`, while 494:meth:`~generator.throw` will just raise the passed in exception immediately. 495 496When the underlying iterator is complete, the :attr:`~StopIteration.value` 497attribute of the raised :exc:`StopIteration` instance becomes the value of 498the yield expression. It can be either set explicitly when raising 499:exc:`StopIteration`, or automatically when the subiterator is a generator 500(by returning a value from the subgenerator). 501 502 .. versionchanged:: 3.3 503 Added ``yield from <expr>`` to delegate control flow to a subiterator. 504 505The parentheses may be omitted when the yield expression is the sole expression 506on the right hand side of an assignment statement. 507 508.. seealso:: 509 510 :pep:`255` - Simple Generators 511 The proposal for adding generators and the :keyword:`yield` statement to Python. 512 513 :pep:`342` - Coroutines via Enhanced Generators 514 The proposal to enhance the API and syntax of generators, making them 515 usable as simple coroutines. 516 517 :pep:`380` - Syntax for Delegating to a Subgenerator 518 The proposal to introduce the :token:`~python-grammar:yield_from` syntax, 519 making delegation to subgenerators easy. 520 521 :pep:`525` - Asynchronous Generators 522 The proposal that expanded on :pep:`492` by adding generator capabilities to 523 coroutine functions. 524 525.. index:: pair: object; generator 526.. _generator-methods: 527 528Generator-iterator methods 529^^^^^^^^^^^^^^^^^^^^^^^^^^ 530 531This subsection describes the methods of a generator iterator. They can 532be used to control the execution of a generator function. 533 534Note that calling any of the generator methods below when the generator 535is already executing raises a :exc:`ValueError` exception. 536 537.. index:: pair: exception; StopIteration 538 539 540.. method:: generator.__next__() 541 542 Starts the execution of a generator function or resumes it at the last 543 executed yield expression. When a generator function is resumed with a 544 :meth:`~generator.__next__` method, the current yield expression always 545 evaluates to :const:`None`. The execution then continues to the next yield 546 expression, where the generator is suspended again, and the value of the 547 :token:`~python-grammar:expression_list` is returned to :meth:`__next__`'s 548 caller. If the generator exits without yielding another value, a 549 :exc:`StopIteration` exception is raised. 550 551 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or 552 by the built-in :func:`next` function. 553 554 555.. method:: generator.send(value) 556 557 Resumes the execution and "sends" a value into the generator function. The 558 *value* argument becomes the result of the current yield expression. The 559 :meth:`send` method returns the next value yielded by the generator, or 560 raises :exc:`StopIteration` if the generator exits without yielding another 561 value. When :meth:`send` is called to start the generator, it must be called 562 with :const:`None` as the argument, because there is no yield expression that 563 could receive the value. 564 565 566.. method:: generator.throw(value) 567 generator.throw(type[, value[, traceback]]) 568 569 Raises an exception at the point where the generator was paused, 570 and returns the next value yielded by the generator function. If the generator 571 exits without yielding another value, a :exc:`StopIteration` exception is 572 raised. If the generator function does not catch the passed-in exception, or 573 raises a different exception, then that exception propagates to the caller. 574 575 In typical use, this is called with a single exception instance similar to the 576 way the :keyword:`raise` keyword is used. 577 578 For backwards compatibility, however, the second signature is 579 supported, following a convention from older versions of Python. 580 The *type* argument should be an exception class, and *value* 581 should be an exception instance. If the *value* is not provided, the 582 *type* constructor is called to get an instance. If *traceback* 583 is provided, it is set on the exception, otherwise any existing 584 :attr:`~BaseException.__traceback__` attribute stored in *value* may 585 be cleared. 586 587.. index:: pair: exception; GeneratorExit 588 589 590.. method:: generator.close() 591 592 Raises a :exc:`GeneratorExit` at the point where the generator function was 593 paused. If the generator function then exits gracefully, is already closed, 594 or raises :exc:`GeneratorExit` (by not catching the exception), close 595 returns to its caller. If the generator yields a value, a 596 :exc:`RuntimeError` is raised. If the generator raises any other exception, 597 it is propagated to the caller. :meth:`close` does nothing if the generator 598 has already exited due to an exception or normal exit. 599 600.. index:: single: yield; examples 601 602Examples 603^^^^^^^^ 604 605Here is a simple example that demonstrates the behavior of generators and 606generator functions:: 607 608 >>> def echo(value=None): 609 ... print("Execution starts when 'next()' is called for the first time.") 610 ... try: 611 ... while True: 612 ... try: 613 ... value = (yield value) 614 ... except Exception as e: 615 ... value = e 616 ... finally: 617 ... print("Don't forget to clean up when 'close()' is called.") 618 ... 619 >>> generator = echo(1) 620 >>> print(next(generator)) 621 Execution starts when 'next()' is called for the first time. 622 1 623 >>> print(next(generator)) 624 None 625 >>> print(generator.send(2)) 626 2 627 >>> generator.throw(TypeError, "spam") 628 TypeError('spam',) 629 >>> generator.close() 630 Don't forget to clean up when 'close()' is called. 631 632For examples using ``yield from``, see :ref:`pep-380` in "What's New in 633Python." 634 635.. _asynchronous-generator-functions: 636 637Asynchronous generator functions 638^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 639 640The presence of a yield expression in a function or method defined using 641:keyword:`async def` further defines the function as an 642:term:`asynchronous generator` function. 643 644When an asynchronous generator function is called, it returns an 645asynchronous iterator known as an asynchronous generator object. 646That object then controls the execution of the generator function. 647An asynchronous generator object is typically used in an 648:keyword:`async for` statement in a coroutine function analogously to 649how a generator object would be used in a :keyword:`for` statement. 650 651Calling one of the asynchronous generator's methods returns an :term:`awaitable` 652object, and the execution starts when this object is awaited on. At that time, 653the execution proceeds to the first yield expression, where it is suspended 654again, returning the value of :token:`~python-grammar:expression_list` to the 655awaiting coroutine. As with a generator, suspension means that all local state 656is retained, including the current bindings of local variables, the instruction 657pointer, the internal evaluation stack, and the state of any exception handling. 658When the execution is resumed by awaiting on the next object returned by the 659asynchronous generator's methods, the function can proceed exactly as if the 660yield expression were just another external call. The value of the yield 661expression after resuming depends on the method which resumed the execution. If 662:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if 663:meth:`~agen.asend` is used, then the result will be the value passed in to that 664method. 665 666If an asynchronous generator happens to exit early by :keyword:`break`, the caller 667task being cancelled, or other exceptions, the generator's async cleanup code 668will run and possibly raise exceptions or access context variables in an 669unexpected context--perhaps after the lifetime of tasks it depends, or 670during the event loop shutdown when the async-generator garbage collection hook 671is called. 672To prevent this, the caller must explicitly close the async generator by calling 673:meth:`~agen.aclose` method to finalize the generator and ultimately detach it 674from the event loop. 675 676In an asynchronous generator function, yield expressions are allowed anywhere 677in a :keyword:`try` construct. However, if an asynchronous generator is not 678resumed before it is finalized (by reaching a zero reference count or by 679being garbage collected), then a yield expression within a :keyword:`!try` 680construct could result in a failure to execute pending :keyword:`finally` 681clauses. In this case, it is the responsibility of the event loop or 682scheduler running the asynchronous generator to call the asynchronous 683generator-iterator's :meth:`~agen.aclose` method and run the resulting 684coroutine object, thus allowing any pending :keyword:`!finally` clauses 685to execute. 686 687To take care of finalization upon event loop termination, an event loop should 688define a *finalizer* function which takes an asynchronous generator-iterator and 689presumably calls :meth:`~agen.aclose` and executes the coroutine. 690This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. 691When first iterated over, an asynchronous generator-iterator will store the 692registered *finalizer* to be called upon finalization. For a reference example 693of a *finalizer* method see the implementation of 694``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`. 695 696The expression ``yield from <expr>`` is a syntax error when used in an 697asynchronous generator function. 698 699.. index:: pair: object; asynchronous-generator 700.. _asynchronous-generator-methods: 701 702Asynchronous generator-iterator methods 703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 704 705This subsection describes the methods of an asynchronous generator iterator, 706which are used to control the execution of a generator function. 707 708 709.. index:: pair: exception; StopAsyncIteration 710 711.. coroutinemethod:: agen.__anext__() 712 713 Returns an awaitable which when run starts to execute the asynchronous 714 generator or resumes it at the last executed yield expression. When an 715 asynchronous generator function is resumed with an :meth:`~agen.__anext__` 716 method, the current yield expression always evaluates to :const:`None` in the 717 returned awaitable, which when run will continue to the next yield 718 expression. The value of the :token:`~python-grammar:expression_list` of the 719 yield expression is the value of the :exc:`StopIteration` exception raised by 720 the completing coroutine. If the asynchronous generator exits without 721 yielding another value, the awaitable instead raises a 722 :exc:`StopAsyncIteration` exception, signalling that the asynchronous 723 iteration has completed. 724 725 This method is normally called implicitly by a :keyword:`async for` loop. 726 727 728.. coroutinemethod:: agen.asend(value) 729 730 Returns an awaitable which when run resumes the execution of the 731 asynchronous generator. As with the :meth:`~generator.send()` method for a 732 generator, this "sends" a value into the asynchronous generator function, 733 and the *value* argument becomes the result of the current yield expression. 734 The awaitable returned by the :meth:`asend` method will return the next 735 value yielded by the generator as the value of the raised 736 :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the 737 asynchronous generator exits without yielding another value. When 738 :meth:`asend` is called to start the asynchronous 739 generator, it must be called with :const:`None` as the argument, 740 because there is no yield expression that could receive the value. 741 742 743.. coroutinemethod:: agen.athrow(type[, value[, traceback]]) 744 745 Returns an awaitable that raises an exception of type ``type`` at the point 746 where the asynchronous generator was paused, and returns the next value 747 yielded by the generator function as the value of the raised 748 :exc:`StopIteration` exception. If the asynchronous generator exits 749 without yielding another value, a :exc:`StopAsyncIteration` exception is 750 raised by the awaitable. 751 If the generator function does not catch the passed-in exception, or 752 raises a different exception, then when the awaitable is run that exception 753 propagates to the caller of the awaitable. 754 755.. index:: pair: exception; GeneratorExit 756 757 758.. coroutinemethod:: agen.aclose() 759 760 Returns an awaitable that when run will throw a :exc:`GeneratorExit` into 761 the asynchronous generator function at the point where it was paused. 762 If the asynchronous generator function then exits gracefully, is already 763 closed, or raises :exc:`GeneratorExit` (by not catching the exception), 764 then the returned awaitable will raise a :exc:`StopIteration` exception. 765 Any further awaitables returned by subsequent calls to the asynchronous 766 generator will raise a :exc:`StopAsyncIteration` exception. If the 767 asynchronous generator yields a value, a :exc:`RuntimeError` is raised 768 by the awaitable. If the asynchronous generator raises any other exception, 769 it is propagated to the caller of the awaitable. If the asynchronous 770 generator has already exited due to an exception or normal exit, then 771 further calls to :meth:`aclose` will return an awaitable that does nothing. 772 773.. _primaries: 774 775Primaries 776========= 777 778.. index:: single: primary 779 780Primaries represent the most tightly bound operations of the language. Their 781syntax is: 782 783.. productionlist:: python-grammar 784 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call` 785 786 787.. _attribute-references: 788 789Attribute references 790-------------------- 791 792.. index:: 793 pair: attribute; reference 794 single: . (dot); attribute reference 795 796An attribute reference is a primary followed by a period and a name: 797 798.. productionlist:: python-grammar 799 attributeref: `primary` "." `identifier` 800 801.. index:: 802 pair: exception; AttributeError 803 pair: object; module 804 pair: object; list 805 806The primary must evaluate to an object of a type that supports attribute 807references, which most objects do. This object is then asked to produce the 808attribute whose name is the identifier. This production can be customized by 809overriding the :meth:`__getattr__` method. If this attribute is not available, 810the exception :exc:`AttributeError` is raised. Otherwise, the type and value of 811the object produced is determined by the object. Multiple evaluations of the 812same attribute reference may yield different objects. 813 814 815.. _subscriptions: 816 817Subscriptions 818------------- 819 820.. index:: 821 single: subscription 822 single: [] (square brackets); subscription 823 824.. index:: 825 pair: object; sequence 826 pair: object; mapping 827 pair: object; string 828 pair: object; tuple 829 pair: object; list 830 pair: object; dictionary 831 pair: sequence; item 832 833The subscription of an instance of a :ref:`container class <sequence-types>` 834will generally select an element from the container. The subscription of a 835:term:`generic class <generic type>` will generally return a 836:ref:`GenericAlias <types-genericalias>` object. 837 838.. productionlist:: python-grammar 839 subscription: `primary` "[" `expression_list` "]" 840 841When an object is subscripted, the interpreter will evaluate the primary and 842the expression list. 843 844The primary must evaluate to an object that supports subscription. An object 845may support subscription through defining one or both of 846:meth:`~object.__getitem__` and :meth:`~object.__class_getitem__`. When the 847primary is subscripted, the evaluated result of the expression list will be 848passed to one of these methods. For more details on when ``__class_getitem__`` 849is called instead of ``__getitem__``, see :ref:`classgetitem-versus-getitem`. 850 851If the expression list contains at least one comma, it will evaluate to a 852:class:`tuple` containing the items of the expression list. Otherwise, the 853expression list will evaluate to the value of the list's sole member. 854 855For built-in objects, there are two types of objects that support subscription 856via :meth:`~object.__getitem__`: 857 8581. Mappings. If the primary is a :term:`mapping`, the expression list must 859 evaluate to an object whose value is one of the keys of the mapping, and the 860 subscription selects the value in the mapping that corresponds to that key. 861 An example of a builtin mapping class is the :class:`dict` class. 8622. Sequences. If the primary is a :term:`sequence`, the expression list must 863 evaluate to an :class:`int` or a :class:`slice` (as discussed in the 864 following section). Examples of builtin sequence classes include the 865 :class:`str`, :class:`list` and :class:`tuple` classes. 866 867The formal syntax makes no special provision for negative indices in 868:term:`sequences <sequence>`. However, built-in sequences all provide a :meth:`~object.__getitem__` 869method that interprets negative indices by adding the length of the sequence 870to the index so that, for example, ``x[-1]`` selects the last item of ``x``. The 871resulting value must be a nonnegative integer less than the number of items in 872the sequence, and the subscription selects the item whose index is that value 873(counting from zero). Since the support for negative indices and slicing 874occurs in the object's :meth:`__getitem__` method, subclasses overriding 875this method will need to explicitly add that support. 876 877.. index:: 878 single: character 879 pair: string; item 880 881A :class:`string <str>` is a special kind of sequence whose items are 882*characters*. A character is not a separate data type but a 883string of exactly one character. 884 885 886.. _slicings: 887 888Slicings 889-------- 890 891.. index:: 892 single: slicing 893 single: slice 894 single: : (colon); slicing 895 single: , (comma); slicing 896 897.. index:: 898 pair: object; sequence 899 pair: object; string 900 pair: object; tuple 901 pair: object; list 902 903A slicing selects a range of items in a sequence object (e.g., a string, tuple 904or list). Slicings may be used as expressions or as targets in assignment or 905:keyword:`del` statements. The syntax for a slicing: 906 907.. productionlist:: python-grammar 908 slicing: `primary` "[" `slice_list` "]" 909 slice_list: `slice_item` ("," `slice_item`)* [","] 910 slice_item: `expression` | `proper_slice` 911 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] 912 lower_bound: `expression` 913 upper_bound: `expression` 914 stride: `expression` 915 916There is ambiguity in the formal syntax here: anything that looks like an 917expression list also looks like a slice list, so any subscription can be 918interpreted as a slicing. Rather than further complicating the syntax, this is 919disambiguated by defining that in this case the interpretation as a subscription 920takes priority over the interpretation as a slicing (this is the case if the 921slice list contains no proper slice). 922 923.. index:: 924 single: start (slice object attribute) 925 single: stop (slice object attribute) 926 single: step (slice object attribute) 927 928The semantics for a slicing are as follows. The primary is indexed (using the 929same :meth:`__getitem__` method as 930normal subscription) with a key that is constructed from the slice list, as 931follows. If the slice list contains at least one comma, the key is a tuple 932containing the conversion of the slice items; otherwise, the conversion of the 933lone slice item is the key. The conversion of a slice item that is an 934expression is that expression. The conversion of a proper slice is a slice 935object (see section :ref:`types`) whose :attr:`~slice.start`, 936:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the 937expressions given as lower bound, upper bound and stride, respectively, 938substituting ``None`` for missing expressions. 939 940 941.. index:: 942 pair: object; callable 943 single: call 944 single: argument; call semantics 945 single: () (parentheses); call 946 single: , (comma); argument list 947 single: = (equals); in function calls 948 949.. _calls: 950 951Calls 952----- 953 954A call calls a callable object (e.g., a :term:`function`) with a possibly empty 955series of :term:`arguments <argument>`: 956 957.. productionlist:: python-grammar 958 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")" 959 argument_list: `positional_arguments` ["," `starred_and_keywords`] 960 : ["," `keywords_arguments`] 961 : | `starred_and_keywords` ["," `keywords_arguments`] 962 : | `keywords_arguments` 963 positional_arguments: positional_item ("," positional_item)* 964 positional_item: `assignment_expression` | "*" `expression` 965 starred_and_keywords: ("*" `expression` | `keyword_item`) 966 : ("," "*" `expression` | "," `keyword_item`)* 967 keywords_arguments: (`keyword_item` | "**" `expression`) 968 : ("," `keyword_item` | "," "**" `expression`)* 969 keyword_item: `identifier` "=" `expression` 970 971An optional trailing comma may be present after the positional and keyword arguments 972but does not affect the semantics. 973 974.. index:: 975 single: parameter; call semantics 976 977The primary must evaluate to a callable object (user-defined functions, built-in 978functions, methods of built-in objects, class objects, methods of class 979instances, and all objects having a :meth:`__call__` method are callable). All 980argument expressions are evaluated before the call is attempted. Please refer 981to section :ref:`function` for the syntax of formal :term:`parameter` lists. 982 983.. XXX update with kwonly args PEP 984 985If keyword arguments are present, they are first converted to positional 986arguments, as follows. First, a list of unfilled slots is created for the 987formal parameters. If there are N positional arguments, they are placed in the 988first N slots. Next, for each keyword argument, the identifier is used to 989determine the corresponding slot (if the identifier is the same as the first 990formal parameter name, the first slot is used, and so on). If the slot is 991already filled, a :exc:`TypeError` exception is raised. Otherwise, the 992argument is placed in the slot, filling it (even if the expression is 993``None``, it fills the slot). When all arguments have been processed, the slots 994that are still unfilled are filled with the corresponding default value from the 995function definition. (Default values are calculated, once, when the function is 996defined; thus, a mutable object such as a list or dictionary used as default 997value will be shared by all calls that don't specify an argument value for the 998corresponding slot; this should usually be avoided.) If there are any unfilled 999slots for which no default value is specified, a :exc:`TypeError` exception is 1000raised. Otherwise, the list of filled slots is used as the argument list for 1001the call. 1002 1003.. impl-detail:: 1004 1005 An implementation may provide built-in functions whose positional parameters 1006 do not have names, even if they are 'named' for the purpose of documentation, 1007 and which therefore cannot be supplied by keyword. In CPython, this is the 1008 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to 1009 parse their arguments. 1010 1011If there are more positional arguments than there are formal parameter slots, a 1012:exc:`TypeError` exception is raised, unless a formal parameter using the syntax 1013``*identifier`` is present; in this case, that formal parameter receives a tuple 1014containing the excess positional arguments (or an empty tuple if there were no 1015excess positional arguments). 1016 1017If any keyword argument does not correspond to a formal parameter name, a 1018:exc:`TypeError` exception is raised, unless a formal parameter using the syntax 1019``**identifier`` is present; in this case, that formal parameter receives a 1020dictionary containing the excess keyword arguments (using the keywords as keys 1021and the argument values as corresponding values), or a (new) empty dictionary if 1022there were no excess keyword arguments. 1023 1024.. index:: 1025 single: * (asterisk); in function calls 1026 single: unpacking; in function calls 1027 1028If the syntax ``*expression`` appears in the function call, ``expression`` must 1029evaluate to an :term:`iterable`. Elements from these iterables are 1030treated as if they were additional positional arguments. For the call 1031``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*, 1032this is equivalent to a call with M+4 positional arguments *x1*, *x2*, 1033*y1*, ..., *yM*, *x3*, *x4*. 1034 1035A consequence of this is that although the ``*expression`` syntax may appear 1036*after* explicit keyword arguments, it is processed *before* the 1037keyword arguments (and any ``**expression`` arguments -- see below). So:: 1038 1039 >>> def f(a, b): 1040 ... print(a, b) 1041 ... 1042 >>> f(b=1, *(2,)) 1043 2 1 1044 >>> f(a=1, *(2,)) 1045 Traceback (most recent call last): 1046 File "<stdin>", line 1, in <module> 1047 TypeError: f() got multiple values for keyword argument 'a' 1048 >>> f(1, *(2,)) 1049 1 2 1050 1051It is unusual for both keyword arguments and the ``*expression`` syntax to be 1052used in the same call, so in practice this confusion does not often arise. 1053 1054.. index:: 1055 single: **; in function calls 1056 1057If the syntax ``**expression`` appears in the function call, ``expression`` must 1058evaluate to a :term:`mapping`, the contents of which are treated as 1059additional keyword arguments. If a parameter matching a key has already been 1060given a value (by an explicit keyword argument, or from another unpacking), 1061a :exc:`TypeError` exception is raised. 1062 1063When ``**expression`` is used, each key in this mapping must be 1064a string. 1065Each value from the mapping is assigned to the first formal parameter 1066eligible for keyword assignment whose name is equal to the key. 1067A key need not be a Python identifier (e.g. ``"max-temp °F"`` is acceptable, 1068although it will not match any formal parameter that could be declared). 1069If there is no match to a formal parameter 1070the key-value pair is collected by the ``**`` parameter, if there is one, 1071or if there is not, a :exc:`TypeError` exception is raised. 1072 1073Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be 1074used as positional argument slots or as keyword argument names. 1075 1076.. versionchanged:: 3.5 1077 Function calls accept any number of ``*`` and ``**`` unpackings, 1078 positional arguments may follow iterable unpackings (``*``), 1079 and keyword arguments may follow dictionary unpackings (``**``). 1080 Originally proposed by :pep:`448`. 1081 1082A call always returns some value, possibly ``None``, unless it raises an 1083exception. How this value is computed depends on the type of the callable 1084object. 1085 1086If it is--- 1087 1088a user-defined function: 1089 .. index:: 1090 pair: function; call 1091 triple: user-defined; function; call 1092 pair: object; user-defined function 1093 pair: object; function 1094 1095 The code block for the function is executed, passing it the argument list. The 1096 first thing the code block will do is bind the formal parameters to the 1097 arguments; this is described in section :ref:`function`. When the code block 1098 executes a :keyword:`return` statement, this specifies the return value of the 1099 function call. 1100 1101a built-in function or method: 1102 .. index:: 1103 pair: function; call 1104 pair: built-in function; call 1105 pair: method; call 1106 pair: built-in method; call 1107 pair: object; built-in method 1108 pair: object; built-in function 1109 pair: object; method 1110 pair: object; function 1111 1112 The result is up to the interpreter; see :ref:`built-in-funcs` for the 1113 descriptions of built-in functions and methods. 1114 1115a class object: 1116 .. index:: 1117 pair: object; class 1118 pair: class object; call 1119 1120 A new instance of that class is returned. 1121 1122a class instance method: 1123 .. index:: 1124 pair: object; class instance 1125 pair: object; instance 1126 pair: class instance; call 1127 1128 The corresponding user-defined function is called, with an argument list that is 1129 one longer than the argument list of the call: the instance becomes the first 1130 argument. 1131 1132a class instance: 1133 .. index:: 1134 pair: instance; call 1135 single: __call__() (object method) 1136 1137 The class must define a :meth:`__call__` method; the effect is then the same as 1138 if that method was called. 1139 1140 1141.. index:: pair: keyword; await 1142.. _await: 1143 1144Await expression 1145================ 1146 1147Suspend the execution of :term:`coroutine` on an :term:`awaitable` object. 1148Can only be used inside a :term:`coroutine function`. 1149 1150.. productionlist:: python-grammar 1151 await_expr: "await" `primary` 1152 1153.. versionadded:: 3.5 1154 1155 1156.. _power: 1157 1158The power operator 1159================== 1160 1161.. index:: 1162 pair: power; operation 1163 pair: operator; ** 1164 1165The power operator binds more tightly than unary operators on its left; it binds 1166less tightly than unary operators on its right. The syntax is: 1167 1168.. productionlist:: python-grammar 1169 power: (`await_expr` | `primary`) ["**" `u_expr`] 1170 1171Thus, in an unparenthesized sequence of power and unary operators, the operators 1172are evaluated from right to left (this does not constrain the evaluation order 1173for the operands): ``-1**2`` results in ``-1``. 1174 1175The power operator has the same semantics as the built-in :func:`pow` function, 1176when called with two arguments: it yields its left argument raised to the power 1177of its right argument. The numeric arguments are first converted to a common 1178type, and the result is of that type. 1179 1180For int operands, the result has the same type as the operands unless the second 1181argument is negative; in that case, all arguments are converted to float and a 1182float result is delivered. For example, ``10**2`` returns ``100``, but 1183``10**-2`` returns ``0.01``. 1184 1185Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. 1186Raising a negative number to a fractional power results in a :class:`complex` 1187number. (In earlier versions it raised a :exc:`ValueError`.) 1188 1189This operation can be customized using the special :meth:`__pow__` method. 1190 1191.. _unary: 1192 1193Unary arithmetic and bitwise operations 1194======================================= 1195 1196.. index:: 1197 triple: unary; arithmetic; operation 1198 triple: unary; bitwise; operation 1199 1200All unary arithmetic and bitwise operations have the same priority: 1201 1202.. productionlist:: python-grammar 1203 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` 1204 1205.. index:: 1206 single: negation 1207 single: minus 1208 single: operator; - (minus) 1209 single: - (minus); unary operator 1210 1211The unary ``-`` (minus) operator yields the negation of its numeric argument; the 1212operation can be overridden with the :meth:`__neg__` special method. 1213 1214.. index:: 1215 single: plus 1216 single: operator; + (plus) 1217 single: + (plus); unary operator 1218 1219The unary ``+`` (plus) operator yields its numeric argument unchanged; the 1220operation can be overridden with the :meth:`__pos__` special method. 1221 1222.. index:: 1223 single: inversion 1224 pair: operator; ~ (tilde) 1225 1226The unary ``~`` (invert) operator yields the bitwise inversion of its integer 1227argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only 1228applies to integral numbers or to custom objects that override the 1229:meth:`__invert__` special method. 1230 1231 1232 1233.. index:: pair: exception; TypeError 1234 1235In all three cases, if the argument does not have the proper type, a 1236:exc:`TypeError` exception is raised. 1237 1238 1239.. _binary: 1240 1241Binary arithmetic operations 1242============================ 1243 1244.. index:: triple: binary; arithmetic; operation 1245 1246The binary arithmetic operations have the conventional priority levels. Note 1247that some of these operations also apply to certain non-numeric types. Apart 1248from the power operator, there are only two levels, one for multiplicative 1249operators and one for additive operators: 1250 1251.. productionlist:: python-grammar 1252 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` | 1253 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` | 1254 : `m_expr` "%" `u_expr` 1255 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr` 1256 1257.. index:: 1258 single: multiplication 1259 pair: operator; * (asterisk) 1260 1261The ``*`` (multiplication) operator yields the product of its arguments. The 1262arguments must either both be numbers, or one argument must be an integer and 1263the other must be a sequence. In the former case, the numbers are converted to a 1264common type and then multiplied together. In the latter case, sequence 1265repetition is performed; a negative repetition factor yields an empty sequence. 1266 1267This operation can be customized using the special :meth:`__mul__` and 1268:meth:`__rmul__` methods. 1269 1270.. index:: 1271 single: matrix multiplication 1272 pair: operator; @ (at) 1273 1274The ``@`` (at) operator is intended to be used for matrix multiplication. No 1275builtin Python types implement this operator. 1276 1277.. versionadded:: 3.5 1278 1279.. index:: 1280 pair: exception; ZeroDivisionError 1281 single: division 1282 pair: operator; / (slash) 1283 pair: operator; // 1284 1285The ``/`` (division) and ``//`` (floor division) operators yield the quotient of 1286their arguments. The numeric arguments are first converted to a common type. 1287Division of integers yields a float, while floor division of integers results in an 1288integer; the result is that of mathematical division with the 'floor' function 1289applied to the result. Division by zero raises the :exc:`ZeroDivisionError` 1290exception. 1291 1292This operation can be customized using the special :meth:`__truediv__` and 1293:meth:`__floordiv__` methods. 1294 1295.. index:: 1296 single: modulo 1297 pair: operator; % (percent) 1298 1299The ``%`` (modulo) operator yields the remainder from the division of the first 1300argument by the second. The numeric arguments are first converted to a common 1301type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The 1302arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34`` 1303(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a 1304result with the same sign as its second operand (or zero); the absolute value of 1305the result is strictly smaller than the absolute value of the second operand 1306[#]_. 1307 1308The floor division and modulo operators are connected by the following 1309identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also 1310connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, 1311x%y)``. [#]_. 1312 1313In addition to performing the modulo operation on numbers, the ``%`` operator is 1314also overloaded by string objects to perform old-style string formatting (also 1315known as interpolation). The syntax for string formatting is described in the 1316Python Library Reference, section :ref:`old-string-formatting`. 1317 1318The *modulo* operation can be customized using the special :meth:`__mod__` method. 1319 1320The floor division operator, the modulo operator, and the :func:`divmod` 1321function are not defined for complex numbers. Instead, convert to a floating 1322point number using the :func:`abs` function if appropriate. 1323 1324.. index:: 1325 single: addition 1326 single: operator; + (plus) 1327 single: + (plus); binary operator 1328 1329The ``+`` (addition) operator yields the sum of its arguments. The arguments 1330must either both be numbers or both be sequences of the same type. In the 1331former case, the numbers are converted to a common type and then added together. 1332In the latter case, the sequences are concatenated. 1333 1334This operation can be customized using the special :meth:`__add__` and 1335:meth:`__radd__` methods. 1336 1337.. index:: 1338 single: subtraction 1339 single: operator; - (minus) 1340 single: - (minus); binary operator 1341 1342The ``-`` (subtraction) operator yields the difference of its arguments. The 1343numeric arguments are first converted to a common type. 1344 1345This operation can be customized using the special :meth:`__sub__` method. 1346 1347 1348.. _shifting: 1349 1350Shifting operations 1351=================== 1352 1353.. index:: 1354 pair: shifting; operation 1355 pair: operator; << 1356 pair: operator; >> 1357 1358The shifting operations have lower priority than the arithmetic operations: 1359 1360.. productionlist:: python-grammar 1361 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr` 1362 1363These operators accept integers as arguments. They shift the first argument to 1364the left or right by the number of bits given by the second argument. 1365 1366This operation can be customized using the special :meth:`__lshift__` and 1367:meth:`__rshift__` methods. 1368 1369.. index:: pair: exception; ValueError 1370 1371A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left 1372shift by *n* bits is defined as multiplication with ``pow(2,n)``. 1373 1374 1375.. _bitwise: 1376 1377Binary bitwise operations 1378========================= 1379 1380.. index:: triple: binary; bitwise; operation 1381 1382Each of the three bitwise operations has a different priority level: 1383 1384.. productionlist:: python-grammar 1385 and_expr: `shift_expr` | `and_expr` "&" `shift_expr` 1386 xor_expr: `and_expr` | `xor_expr` "^" `and_expr` 1387 or_expr: `xor_expr` | `or_expr` "|" `xor_expr` 1388 1389.. index:: 1390 pair: bitwise; and 1391 pair: operator; & (ampersand) 1392 1393The ``&`` operator yields the bitwise AND of its arguments, which must be 1394integers or one of them must be a custom object overriding :meth:`__and__` or 1395:meth:`__rand__` special methods. 1396 1397.. index:: 1398 pair: bitwise; xor 1399 pair: exclusive; or 1400 pair: operator; ^ (caret) 1401 1402The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which 1403must be integers or one of them must be a custom object overriding :meth:`__xor__` or 1404:meth:`__rxor__` special methods. 1405 1406.. index:: 1407 pair: bitwise; or 1408 pair: inclusive; or 1409 pair: operator; | (vertical bar) 1410 1411The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which 1412must be integers or one of them must be a custom object overriding :meth:`__or__` or 1413:meth:`__ror__` special methods. 1414 1415 1416.. _comparisons: 1417 1418Comparisons 1419=========== 1420 1421.. index:: 1422 single: comparison 1423 pair: C; language 1424 pair: operator; < (less) 1425 pair: operator; > (greater) 1426 pair: operator; <= 1427 pair: operator; >= 1428 pair: operator; == 1429 pair: operator; != 1430 1431Unlike C, all comparison operations in Python have the same priority, which is 1432lower than that of any arithmetic, shifting or bitwise operation. Also unlike 1433C, expressions like ``a < b < c`` have the interpretation that is conventional 1434in mathematics: 1435 1436.. productionlist:: python-grammar 1437 comparison: `or_expr` (`comp_operator` `or_expr`)* 1438 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!=" 1439 : | "is" ["not"] | ["not"] "in" 1440 1441Comparisons yield boolean values: ``True`` or ``False``. Custom 1442:dfn:`rich comparison methods` may return non-boolean values. In this case 1443Python will call :func:`bool` on such value in boolean contexts. 1444 1445.. index:: pair: chaining; comparisons 1446 1447Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to 1448``x < y and y <= z``, except that ``y`` is evaluated only once (but in both 1449cases ``z`` is not evaluated at all when ``x < y`` is found to be false). 1450 1451Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., 1452*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent 1453to ``a op1 b and b op2 c and ... y opN z``, except that each expression is 1454evaluated at most once. 1455 1456Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and 1457*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not 1458pretty). 1459 1460.. _expressions-value-comparisons: 1461 1462Value comparisons 1463----------------- 1464 1465The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the 1466values of two objects. The objects do not need to have the same type. 1467 1468Chapter :ref:`objects` states that objects have a value (in addition to type 1469and identity). The value of an object is a rather abstract notion in Python: 1470For example, there is no canonical access method for an object's value. Also, 1471there is no requirement that the value of an object should be constructed in a 1472particular way, e.g. comprised of all its data attributes. Comparison operators 1473implement a particular notion of what the value of an object is. One can think 1474of them as defining the value of an object indirectly, by means of their 1475comparison implementation. 1476 1477Because all types are (direct or indirect) subtypes of :class:`object`, they 1478inherit the default comparison behavior from :class:`object`. Types can 1479customize their comparison behavior by implementing 1480:dfn:`rich comparison methods` like :meth:`__lt__`, described in 1481:ref:`customization`. 1482 1483The default behavior for equality comparison (``==`` and ``!=``) is based on 1484the identity of the objects. Hence, equality comparison of instances with the 1485same identity results in equality, and equality comparison of instances with 1486different identities results in inequality. A motivation for this default 1487behavior is the desire that all objects should be reflexive (i.e. ``x is y`` 1488implies ``x == y``). 1489 1490A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; 1491an attempt raises :exc:`TypeError`. A motivation for this default behavior is 1492the lack of a similar invariant as for equality. 1493 1494The behavior of the default equality comparison, that instances with different 1495identities are always unequal, may be in contrast to what types will need that 1496have a sensible definition of object value and value-based equality. Such 1497types will need to customize their comparison behavior, and in fact, a number 1498of built-in types have done that. 1499 1500The following list describes the comparison behavior of the most important 1501built-in types. 1502 1503* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard 1504 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be 1505 compared within and across their types, with the restriction that complex 1506 numbers do not support order comparison. Within the limits of the types 1507 involved, they compare mathematically (algorithmically) correct without loss 1508 of precision. 1509 1510 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are 1511 special. Any ordered comparison of a number to a not-a-number value is false. 1512 A counter-intuitive implication is that not-a-number values are not equal to 1513 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and 1514 ``x == x`` are all false, while ``x != x`` is true. This behavior is 1515 compliant with IEEE 754. 1516 1517* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that 1518 comparisons for singletons should always be done with ``is`` or ``is not``, 1519 never the equality operators. 1520 1521* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be 1522 compared within and across their types. They compare lexicographically using 1523 the numeric values of their elements. 1524 1525* Strings (instances of :class:`str`) compare lexicographically using the 1526 numerical Unicode code points (the result of the built-in function 1527 :func:`ord`) of their characters. [#]_ 1528 1529 Strings and binary sequences cannot be directly compared. 1530 1531* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can 1532 be compared only within each of their types, with the restriction that ranges 1533 do not support order comparison. Equality comparison across these types 1534 results in inequality, and ordering comparison across these types raises 1535 :exc:`TypeError`. 1536 1537 Sequences compare lexicographically using comparison of corresponding 1538 elements. The built-in containers typically assume identical objects are 1539 equal to themselves. That lets them bypass equality tests for identical 1540 objects to improve performance and to maintain their internal invariants. 1541 1542 Lexicographical comparison between built-in collections works as follows: 1543 1544 - For two collections to compare equal, they must be of the same type, have 1545 the same length, and each pair of corresponding elements must compare 1546 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the 1547 same). 1548 1549 - Collections that support order comparison are ordered the same as their 1550 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same 1551 value as ``x <= y``). If a corresponding element does not exist, the 1552 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is 1553 true). 1554 1555* Mappings (instances of :class:`dict`) compare equal if and only if they have 1556 equal ``(key, value)`` pairs. Equality comparison of the keys and values 1557 enforces reflexivity. 1558 1559 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`. 1560 1561* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within 1562 and across their types. 1563 1564 They define order 1565 comparison operators to mean subset and superset tests. Those relations do 1566 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` 1567 are not equal, nor subsets of one another, nor supersets of one 1568 another). Accordingly, sets are not appropriate arguments for functions 1569 which depend on total ordering (for example, :func:`min`, :func:`max`, and 1570 :func:`sorted` produce undefined results given a list of sets as inputs). 1571 1572 Comparison of sets enforces reflexivity of its elements. 1573 1574* Most other built-in types have no comparison methods implemented, so they 1575 inherit the default comparison behavior. 1576 1577User-defined classes that customize their comparison behavior should follow 1578some consistency rules, if possible: 1579 1580* Equality comparison should be reflexive. 1581 In other words, identical objects should compare equal: 1582 1583 ``x is y`` implies ``x == y`` 1584 1585* Comparison should be symmetric. 1586 In other words, the following expressions should have the same result: 1587 1588 ``x == y`` and ``y == x`` 1589 1590 ``x != y`` and ``y != x`` 1591 1592 ``x < y`` and ``y > x`` 1593 1594 ``x <= y`` and ``y >= x`` 1595 1596* Comparison should be transitive. 1597 The following (non-exhaustive) examples illustrate that: 1598 1599 ``x > y and y > z`` implies ``x > z`` 1600 1601 ``x < y and y <= z`` implies ``x < z`` 1602 1603* Inverse comparison should result in the boolean negation. 1604 In other words, the following expressions should have the same result: 1605 1606 ``x == y`` and ``not x != y`` 1607 1608 ``x < y`` and ``not x >= y`` (for total ordering) 1609 1610 ``x > y`` and ``not x <= y`` (for total ordering) 1611 1612 The last two expressions apply to totally ordered collections (e.g. to 1613 sequences, but not to sets or mappings). See also the 1614 :func:`~functools.total_ordering` decorator. 1615 1616* The :func:`hash` result should be consistent with equality. 1617 Objects that are equal should either have the same hash value, 1618 or be marked as unhashable. 1619 1620Python does not enforce these consistency rules. In fact, the not-a-number 1621values are an example for not following these rules. 1622 1623 1624.. _in: 1625.. _not in: 1626.. _membership-test-details: 1627 1628Membership test operations 1629-------------------------- 1630 1631The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in 1632s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. 1633``x not in s`` returns the negation of ``x in s``. All built-in sequences and 1634set types support this as well as dictionary, for which :keyword:`!in` tests 1635whether the dictionary has a given key. For container types such as list, tuple, 1636set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent 1637to ``any(x is e or x == e for e in y)``. 1638 1639For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a 1640substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are 1641always considered to be a substring of any other string, so ``"" in "abc"`` will 1642return ``True``. 1643 1644For user-defined classes which define the :meth:`__contains__` method, ``x in 1645y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and 1646``False`` otherwise. 1647 1648For user-defined classes which do not define :meth:`__contains__` but do define 1649:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the 1650expression ``x is z or x == z`` is true, is produced while iterating over ``y``. 1651If an exception is raised during the iteration, it is as if :keyword:`in` raised 1652that exception. 1653 1654Lastly, the old-style iteration protocol is tried: if a class defines 1655:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative 1656integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index 1657raises the :exc:`IndexError` exception. (If any other exception is raised, it is as 1658if :keyword:`in` raised that exception). 1659 1660.. index:: 1661 pair: operator; in 1662 pair: operator; not in 1663 pair: membership; test 1664 pair: object; sequence 1665 1666The operator :keyword:`not in` is defined to have the inverse truth value of 1667:keyword:`in`. 1668 1669.. index:: 1670 pair: operator; is 1671 pair: operator; is not 1672 pair: identity; test 1673 1674 1675.. _is: 1676.. _is not: 1677 1678Identity comparisons 1679-------------------- 1680 1681The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x 1682is y`` is true if and only if *x* and *y* are the same object. An Object's identity 1683is determined using the :meth:`id` function. ``x is not y`` yields the inverse 1684truth value. [#]_ 1685 1686 1687.. _booleans: 1688.. _and: 1689.. _or: 1690.. _not: 1691 1692Boolean operations 1693================== 1694 1695.. index:: 1696 pair: Conditional; expression 1697 pair: Boolean; operation 1698 1699.. productionlist:: python-grammar 1700 or_test: `and_test` | `or_test` "or" `and_test` 1701 and_test: `not_test` | `and_test` "and" `not_test` 1702 not_test: `comparison` | "not" `not_test` 1703 1704In the context of Boolean operations, and also when expressions are used by 1705control flow statements, the following values are interpreted as false: 1706``False``, ``None``, numeric zero of all types, and empty strings and containers 1707(including strings, tuples, lists, dictionaries, sets and frozensets). All 1708other values are interpreted as true. User-defined objects can customize their 1709truth value by providing a :meth:`__bool__` method. 1710 1711.. index:: pair: operator; not 1712 1713The operator :keyword:`not` yields ``True`` if its argument is false, ``False`` 1714otherwise. 1715 1716.. index:: pair: operator; and 1717 1718The expression ``x and y`` first evaluates *x*; if *x* is false, its value is 1719returned; otherwise, *y* is evaluated and the resulting value is returned. 1720 1721.. index:: pair: operator; or 1722 1723The expression ``x or y`` first evaluates *x*; if *x* is true, its value is 1724returned; otherwise, *y* is evaluated and the resulting value is returned. 1725 1726Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type 1727they return to ``False`` and ``True``, but rather return the last evaluated 1728argument. This is sometimes useful, e.g., if ``s`` is a string that should be 1729replaced by a default value if it is empty, the expression ``s or 'foo'`` yields 1730the desired value. Because :keyword:`not` has to create a new value, it 1731returns a boolean value regardless of the type of its argument 1732(for example, ``not 'foo'`` produces ``False`` rather than ``''``.) 1733 1734 1735.. index:: 1736 single: := (colon equals) 1737 single: assignment expression 1738 single: walrus operator 1739 single: named expression 1740 1741Assignment expressions 1742====================== 1743 1744.. productionlist:: python-grammar 1745 assignment_expression: [`identifier` ":="] `expression` 1746 1747An assignment expression (sometimes also called a "named expression" or 1748"walrus") assigns an :token:`~python-grammar:expression` to an 1749:token:`~python-grammar:identifier`, while also returning the value of the 1750:token:`~python-grammar:expression`. 1751 1752One common use case is when handling matched regular expressions: 1753 1754.. code-block:: python 1755 1756 if matching := pattern.search(data): 1757 do_something(matching) 1758 1759Or, when processing a file stream in chunks: 1760 1761.. code-block:: python 1762 1763 while chunk := file.read(9000): 1764 process(chunk) 1765 1766Assignment expressions must be surrounded by parentheses when used 1767as sub-expressions in slicing, conditional, lambda, 1768keyword-argument, and comprehension-if expressions 1769and in ``assert`` and ``with`` statements. 1770In all other places where they can be used, parentheses are not required, 1771including in ``if`` and ``while`` statements. 1772 1773.. versionadded:: 3.8 1774 See :pep:`572` for more details about assignment expressions. 1775 1776 1777.. _if_expr: 1778 1779Conditional expressions 1780======================= 1781 1782.. index:: 1783 pair: conditional; expression 1784 pair: ternary; operator 1785 single: if; conditional expression 1786 single: else; conditional expression 1787 1788.. productionlist:: python-grammar 1789 conditional_expression: `or_test` ["if" `or_test` "else" `expression`] 1790 expression: `conditional_expression` | `lambda_expr` 1791 1792Conditional expressions (sometimes called a "ternary operator") have the lowest 1793priority of all Python operations. 1794 1795The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*. 1796If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is 1797evaluated and its value is returned. 1798 1799See :pep:`308` for more details about conditional expressions. 1800 1801 1802.. _lambdas: 1803.. _lambda: 1804 1805Lambdas 1806======= 1807 1808.. index:: 1809 pair: lambda; expression 1810 pair: lambda; form 1811 pair: anonymous; function 1812 single: : (colon); lambda expression 1813 1814.. productionlist:: python-grammar 1815 lambda_expr: "lambda" [`parameter_list`] ":" `expression` 1816 1817Lambda expressions (sometimes called lambda forms) are used to create anonymous 1818functions. The expression ``lambda parameters: expression`` yields a function 1819object. The unnamed object behaves like a function object defined with: 1820 1821.. code-block:: none 1822 1823 def <lambda>(parameters): 1824 return expression 1825 1826See section :ref:`function` for the syntax of parameter lists. Note that 1827functions created with lambda expressions cannot contain statements or 1828annotations. 1829 1830 1831.. _exprlists: 1832 1833Expression lists 1834================ 1835 1836.. index:: 1837 pair: expression; list 1838 single: , (comma); expression list 1839 1840.. productionlist:: python-grammar 1841 expression_list: `expression` ("," `expression`)* [","] 1842 starred_list: `starred_item` ("," `starred_item`)* [","] 1843 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`] 1844 starred_item: `assignment_expression` | "*" `or_expr` 1845 1846.. index:: pair: object; tuple 1847 1848Except when part of a list or set display, an expression list 1849containing at least one comma yields a tuple. The length of 1850the tuple is the number of expressions in the list. The expressions are 1851evaluated from left to right. 1852 1853.. index:: 1854 pair: iterable; unpacking 1855 single: * (asterisk); in expression lists 1856 1857An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be 1858an :term:`iterable`. The iterable is expanded into a sequence of items, 1859which are included in the new tuple, list, or set, at the site of 1860the unpacking. 1861 1862.. versionadded:: 3.5 1863 Iterable unpacking in expression lists, originally proposed by :pep:`448`. 1864 1865.. index:: pair: trailing; comma 1866 1867The trailing comma is required only to create a single tuple (a.k.a. a 1868*singleton*); it is optional in all other cases. A single expression without a 1869trailing comma doesn't create a tuple, but rather yields the value of that 1870expression. (To create an empty tuple, use an empty pair of parentheses: 1871``()``.) 1872 1873 1874.. _evalorder: 1875 1876Evaluation order 1877================ 1878 1879.. index:: pair: evaluation; order 1880 1881Python evaluates expressions from left to right. Notice that while evaluating 1882an assignment, the right-hand side is evaluated before the left-hand side. 1883 1884In the following lines, expressions will be evaluated in the arithmetic order of 1885their suffixes:: 1886 1887 expr1, expr2, expr3, expr4 1888 (expr1, expr2, expr3, expr4) 1889 {expr1: expr2, expr3: expr4} 1890 expr1 + expr2 * (expr3 - expr4) 1891 expr1(expr2, expr3, *expr4, **expr5) 1892 expr3, expr4 = expr1, expr2 1893 1894 1895.. _operator-summary: 1896 1897Operator precedence 1898=================== 1899 1900.. index:: 1901 pair: operator; precedence 1902 1903The following table summarizes the operator precedence in Python, from highest 1904precedence (most binding) to lowest precedence (least binding). Operators in 1905the same box have the same precedence. Unless the syntax is explicitly given, 1906operators are binary. Operators in the same box group left to right (except for 1907exponentiation and conditional expressions, which group from right to left). 1908 1909Note that comparisons, membership tests, and identity tests, all have the same 1910precedence and have a left-to-right chaining feature as described in the 1911:ref:`comparisons` section. 1912 1913 1914+-----------------------------------------------+-------------------------------------+ 1915| Operator | Description | 1916+===============================================+=====================================+ 1917| ``(expressions...)``, | Binding or parenthesized | 1918| | expression, | 1919| ``[expressions...]``, | list display, | 1920| ``{key: value...}``, | dictionary display, | 1921| ``{expressions...}`` | set display | 1922+-----------------------------------------------+-------------------------------------+ 1923| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | 1924| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | 1925+-----------------------------------------------+-------------------------------------+ 1926| :keyword:`await x <await>` | Await expression | 1927+-----------------------------------------------+-------------------------------------+ 1928| ``**`` | Exponentiation [#]_ | 1929+-----------------------------------------------+-------------------------------------+ 1930| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | 1931+-----------------------------------------------+-------------------------------------+ 1932| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | 1933| | multiplication, division, floor | 1934| | division, remainder [#]_ | 1935+-----------------------------------------------+-------------------------------------+ 1936| ``+``, ``-`` | Addition and subtraction | 1937+-----------------------------------------------+-------------------------------------+ 1938| ``<<``, ``>>`` | Shifts | 1939+-----------------------------------------------+-------------------------------------+ 1940| ``&`` | Bitwise AND | 1941+-----------------------------------------------+-------------------------------------+ 1942| ``^`` | Bitwise XOR | 1943+-----------------------------------------------+-------------------------------------+ 1944| ``|`` | Bitwise OR | 1945+-----------------------------------------------+-------------------------------------+ 1946| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | 1947| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | 1948| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | 1949+-----------------------------------------------+-------------------------------------+ 1950| :keyword:`not x <not>` | Boolean NOT | 1951+-----------------------------------------------+-------------------------------------+ 1952| :keyword:`and` | Boolean AND | 1953+-----------------------------------------------+-------------------------------------+ 1954| :keyword:`or` | Boolean OR | 1955+-----------------------------------------------+-------------------------------------+ 1956| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression | 1957+-----------------------------------------------+-------------------------------------+ 1958| :keyword:`lambda` | Lambda expression | 1959+-----------------------------------------------+-------------------------------------+ 1960| ``:=`` | Assignment expression | 1961+-----------------------------------------------+-------------------------------------+ 1962 1963 1964.. rubric:: Footnotes 1965 1966.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be 1967 true numerically due to roundoff. For example, and assuming a platform on which 1968 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % 1969 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + 1970 1e100``, which is numerically exactly equal to ``1e100``. The function 1971 :func:`math.fmod` returns a result whose sign matches the sign of the 1972 first argument instead, and so returns ``-1e-100`` in this case. Which approach 1973 is more appropriate depends on the application. 1974 1975.. [#] If x is very close to an exact integer multiple of y, it's possible for 1976 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such 1977 cases, Python returns the latter result, in order to preserve that 1978 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. 1979 1980.. [#] The Unicode standard distinguishes between :dfn:`code points` 1981 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). 1982 While most abstract characters in Unicode are only represented using one 1983 code point, there is a number of abstract characters that can in addition be 1984 represented using a sequence of more than one code point. For example, the 1985 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented 1986 as a single :dfn:`precomposed character` at code position U+00C7, or as a 1987 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL 1988 LETTER C), followed by a :dfn:`combining character` at code position U+0327 1989 (COMBINING CEDILLA). 1990 1991 The comparison operators on strings compare at the level of Unicode code 1992 points. This may be counter-intuitive to humans. For example, 1993 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings 1994 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". 1995 1996 To compare strings at the level of abstract characters (that is, in a way 1997 intuitive to humans), use :func:`unicodedata.normalize`. 1998 1999.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of 2000 descriptors, you may notice seemingly unusual behaviour in certain uses of 2001 the :keyword:`is` operator, like those involving comparisons between instance 2002 methods, or constants. Check their documentation for more info. 2003 2004.. [#] The power operator ``**`` binds less tightly than an arithmetic or 2005 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. 2006 2007.. [#] The ``%`` operator is also used for string formatting; the same 2008 precedence applies. 2009