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