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