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 813Subscription of a sequence (string, tuple or list) or mapping (dictionary) 814object usually selects an item from the collection: 815 816.. productionlist:: python-grammar 817 subscription: `primary` "[" `expression_list` "]" 818 819The primary must evaluate to an object that supports subscription (lists or 820dictionaries for example). User-defined objects can support subscription by 821defining a :meth:`__getitem__` method. 822 823For built-in objects, there are two types of objects that support subscription: 824 825If the primary is a mapping, the expression list must evaluate to an object 826whose value is one of the keys of the mapping, and the subscription selects the 827value in the mapping that corresponds to that key. (The expression list is a 828tuple except if it has exactly one item.) 829 830If the primary is a sequence, the expression list must evaluate to an integer 831or a slice (as discussed in the following section). 832 833The formal syntax makes no special provision for negative indices in 834sequences; however, built-in sequences all provide a :meth:`__getitem__` 835method that interprets negative indices by adding the length of the sequence 836to the index (so that ``x[-1]`` selects the last item of ``x``). The 837resulting value must be a nonnegative integer less than the number of items in 838the sequence, and the subscription selects the item whose index is that value 839(counting from zero). Since the support for negative indices and slicing 840occurs in the object's :meth:`__getitem__` method, subclasses overriding 841this method will need to explicitly add that support. 842 843.. index:: 844 single: character 845 pair: string; item 846 847A string's items are characters. A character is not a separate data type but a 848string of exactly one character. 849 850Subscription of certain :term:`classes <class>` or :term:`types <type>` 851creates a :ref:`generic alias <types-genericalias>`. 852In this case, user-defined classes can support subscription by providing a 853:meth:`__class_getitem__` classmethod. 854 855 856.. _slicings: 857 858Slicings 859-------- 860 861.. index:: 862 single: slicing 863 single: slice 864 single: : (colon); slicing 865 single: , (comma); slicing 866 867.. index:: 868 object: sequence 869 object: string 870 object: tuple 871 object: list 872 873A slicing selects a range of items in a sequence object (e.g., a string, tuple 874or list). Slicings may be used as expressions or as targets in assignment or 875:keyword:`del` statements. The syntax for a slicing: 876 877.. productionlist:: python-grammar 878 slicing: `primary` "[" `slice_list` "]" 879 slice_list: `slice_item` ("," `slice_item`)* [","] 880 slice_item: `expression` | `proper_slice` 881 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] 882 lower_bound: `expression` 883 upper_bound: `expression` 884 stride: `expression` 885 886There is ambiguity in the formal syntax here: anything that looks like an 887expression list also looks like a slice list, so any subscription can be 888interpreted as a slicing. Rather than further complicating the syntax, this is 889disambiguated by defining that in this case the interpretation as a subscription 890takes priority over the interpretation as a slicing (this is the case if the 891slice list contains no proper slice). 892 893.. index:: 894 single: start (slice object attribute) 895 single: stop (slice object attribute) 896 single: step (slice object attribute) 897 898The semantics for a slicing are as follows. The primary is indexed (using the 899same :meth:`__getitem__` method as 900normal subscription) with a key that is constructed from the slice list, as 901follows. If the slice list contains at least one comma, the key is a tuple 902containing the conversion of the slice items; otherwise, the conversion of the 903lone slice item is the key. The conversion of a slice item that is an 904expression is that expression. The conversion of a proper slice is a slice 905object (see section :ref:`types`) whose :attr:`~slice.start`, 906:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the 907expressions given as lower bound, upper bound and stride, respectively, 908substituting ``None`` for missing expressions. 909 910 911.. index:: 912 object: callable 913 single: call 914 single: argument; call semantics 915 single: () (parentheses); call 916 single: , (comma); argument list 917 single: = (equals); in function calls 918 919.. _calls: 920 921Calls 922----- 923 924A call calls a callable object (e.g., a :term:`function`) with a possibly empty 925series of :term:`arguments <argument>`: 926 927.. productionlist:: python-grammar 928 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")" 929 argument_list: `positional_arguments` ["," `starred_and_keywords`] 930 : ["," `keywords_arguments`] 931 : | `starred_and_keywords` ["," `keywords_arguments`] 932 : | `keywords_arguments` 933 positional_arguments: positional_item ("," positional_item)* 934 positional_item: `assignment_expression` | "*" `expression` 935 starred_and_keywords: ("*" `expression` | `keyword_item`) 936 : ("," "*" `expression` | "," `keyword_item`)* 937 keywords_arguments: (`keyword_item` | "**" `expression`) 938 : ("," `keyword_item` | "," "**" `expression`)* 939 keyword_item: `identifier` "=" `expression` 940 941An optional trailing comma may be present after the positional and keyword arguments 942but does not affect the semantics. 943 944.. index:: 945 single: parameter; call semantics 946 947The primary must evaluate to a callable object (user-defined functions, built-in 948functions, methods of built-in objects, class objects, methods of class 949instances, and all objects having a :meth:`__call__` method are callable). All 950argument expressions are evaluated before the call is attempted. Please refer 951to section :ref:`function` for the syntax of formal :term:`parameter` lists. 952 953.. XXX update with kwonly args PEP 954 955If keyword arguments are present, they are first converted to positional 956arguments, as follows. First, a list of unfilled slots is created for the 957formal parameters. If there are N positional arguments, they are placed in the 958first N slots. Next, for each keyword argument, the identifier is used to 959determine the corresponding slot (if the identifier is the same as the first 960formal parameter name, the first slot is used, and so on). If the slot is 961already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of 962the argument is placed in the slot, filling it (even if the expression is 963``None``, it fills the slot). When all arguments have been processed, the slots 964that are still unfilled are filled with the corresponding default value from the 965function definition. (Default values are calculated, once, when the function is 966defined; thus, a mutable object such as a list or dictionary used as default 967value will be shared by all calls that don't specify an argument value for the 968corresponding slot; this should usually be avoided.) If there are any unfilled 969slots for which no default value is specified, a :exc:`TypeError` exception is 970raised. Otherwise, the list of filled slots is used as the argument list for 971the call. 972 973.. impl-detail:: 974 975 An implementation may provide built-in functions whose positional parameters 976 do not have names, even if they are 'named' for the purpose of documentation, 977 and which therefore cannot be supplied by keyword. In CPython, this is the 978 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to 979 parse their arguments. 980 981If there are more positional arguments than there are formal parameter slots, a 982:exc:`TypeError` exception is raised, unless a formal parameter using the syntax 983``*identifier`` is present; in this case, that formal parameter receives a tuple 984containing the excess positional arguments (or an empty tuple if there were no 985excess positional arguments). 986 987If any keyword argument does not correspond to a formal parameter name, a 988:exc:`TypeError` exception is raised, unless a formal parameter using the syntax 989``**identifier`` is present; in this case, that formal parameter receives a 990dictionary containing the excess keyword arguments (using the keywords as keys 991and the argument values as corresponding values), or a (new) empty dictionary if 992there were no excess keyword arguments. 993 994.. index:: 995 single: * (asterisk); in function calls 996 single: unpacking; in function calls 997 998If the syntax ``*expression`` appears in the function call, ``expression`` must 999evaluate to an :term:`iterable`. Elements from these iterables are 1000treated as if they were additional positional arguments. For the call 1001``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*, 1002this is equivalent to a call with M+4 positional arguments *x1*, *x2*, 1003*y1*, ..., *yM*, *x3*, *x4*. 1004 1005A consequence of this is that although the ``*expression`` syntax may appear 1006*after* explicit keyword arguments, it is processed *before* the 1007keyword arguments (and any ``**expression`` arguments -- see below). So:: 1008 1009 >>> def f(a, b): 1010 ... print(a, b) 1011 ... 1012 >>> f(b=1, *(2,)) 1013 2 1 1014 >>> f(a=1, *(2,)) 1015 Traceback (most recent call last): 1016 File "<stdin>", line 1, in <module> 1017 TypeError: f() got multiple values for keyword argument 'a' 1018 >>> f(1, *(2,)) 1019 1 2 1020 1021It is unusual for both keyword arguments and the ``*expression`` syntax to be 1022used in the same call, so in practice this confusion does not arise. 1023 1024.. index:: 1025 single: **; in function calls 1026 1027If the syntax ``**expression`` appears in the function call, ``expression`` must 1028evaluate to a :term:`mapping`, the contents of which are treated as 1029additional keyword arguments. If a keyword is already present 1030(as an explicit keyword argument, or from another unpacking), 1031a :exc:`TypeError` exception is raised. 1032 1033Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be 1034used as positional argument slots or as keyword argument names. 1035 1036.. versionchanged:: 3.5 1037 Function calls accept any number of ``*`` and ``**`` unpackings, 1038 positional arguments may follow iterable unpackings (``*``), 1039 and keyword arguments may follow dictionary unpackings (``**``). 1040 Originally proposed by :pep:`448`. 1041 1042A call always returns some value, possibly ``None``, unless it raises an 1043exception. How this value is computed depends on the type of the callable 1044object. 1045 1046If it is--- 1047 1048a user-defined function: 1049 .. index:: 1050 pair: function; call 1051 triple: user-defined; function; call 1052 object: user-defined function 1053 object: function 1054 1055 The code block for the function is executed, passing it the argument list. The 1056 first thing the code block will do is bind the formal parameters to the 1057 arguments; this is described in section :ref:`function`. When the code block 1058 executes a :keyword:`return` statement, this specifies the return value of the 1059 function call. 1060 1061a built-in function or method: 1062 .. index:: 1063 pair: function; call 1064 pair: built-in function; call 1065 pair: method; call 1066 pair: built-in method; call 1067 object: built-in method 1068 object: built-in function 1069 object: method 1070 object: function 1071 1072 The result is up to the interpreter; see :ref:`built-in-funcs` for the 1073 descriptions of built-in functions and methods. 1074 1075a class object: 1076 .. index:: 1077 object: class 1078 pair: class object; call 1079 1080 A new instance of that class is returned. 1081 1082a class instance method: 1083 .. index:: 1084 object: class instance 1085 object: instance 1086 pair: class instance; call 1087 1088 The corresponding user-defined function is called, with an argument list that is 1089 one longer than the argument list of the call: the instance becomes the first 1090 argument. 1091 1092a class instance: 1093 .. index:: 1094 pair: instance; call 1095 single: __call__() (object method) 1096 1097 The class must define a :meth:`__call__` method; the effect is then the same as 1098 if that method was called. 1099 1100 1101.. index:: keyword: await 1102.. _await: 1103 1104Await expression 1105================ 1106 1107Suspend the execution of :term:`coroutine` on an :term:`awaitable` object. 1108Can only be used inside a :term:`coroutine function`. 1109 1110.. productionlist:: python-grammar 1111 await_expr: "await" `primary` 1112 1113.. versionadded:: 3.5 1114 1115 1116.. _power: 1117 1118The power operator 1119================== 1120 1121.. index:: 1122 pair: power; operation 1123 operator: ** 1124 1125The power operator binds more tightly than unary operators on its left; it binds 1126less tightly than unary operators on its right. The syntax is: 1127 1128.. productionlist:: python-grammar 1129 power: (`await_expr` | `primary`) ["**" `u_expr`] 1130 1131Thus, in an unparenthesized sequence of power and unary operators, the operators 1132are evaluated from right to left (this does not constrain the evaluation order 1133for the operands): ``-1**2`` results in ``-1``. 1134 1135The power operator has the same semantics as the built-in :func:`pow` function, 1136when called with two arguments: it yields its left argument raised to the power 1137of its right argument. The numeric arguments are first converted to a common 1138type, and the result is of that type. 1139 1140For int operands, the result has the same type as the operands unless the second 1141argument is negative; in that case, all arguments are converted to float and a 1142float result is delivered. For example, ``10**2`` returns ``100``, but 1143``10**-2`` returns ``0.01``. 1144 1145Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. 1146Raising a negative number to a fractional power results in a :class:`complex` 1147number. (In earlier versions it raised a :exc:`ValueError`.) 1148 1149This operation can be customized using the special :meth:`__pow__` method. 1150 1151.. _unary: 1152 1153Unary arithmetic and bitwise operations 1154======================================= 1155 1156.. index:: 1157 triple: unary; arithmetic; operation 1158 triple: unary; bitwise; operation 1159 1160All unary arithmetic and bitwise operations have the same priority: 1161 1162.. productionlist:: python-grammar 1163 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` 1164 1165.. index:: 1166 single: negation 1167 single: minus 1168 single: operator; - (minus) 1169 single: - (minus); unary operator 1170 1171The unary ``-`` (minus) operator yields the negation of its numeric argument; the 1172operation can be overridden with the :meth:`__neg__` special method. 1173 1174.. index:: 1175 single: plus 1176 single: operator; + (plus) 1177 single: + (plus); unary operator 1178 1179The unary ``+`` (plus) operator yields its numeric argument unchanged; the 1180operation can be overridden with the :meth:`__pos__` special method. 1181 1182.. index:: 1183 single: inversion 1184 operator: ~ (tilde) 1185 1186The unary ``~`` (invert) operator yields the bitwise inversion of its integer 1187argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only 1188applies to integral numbers or to custom objects that override the 1189:meth:`__invert__` special method. 1190 1191 1192 1193.. index:: exception: TypeError 1194 1195In all three cases, if the argument does not have the proper type, a 1196:exc:`TypeError` exception is raised. 1197 1198 1199.. _binary: 1200 1201Binary arithmetic operations 1202============================ 1203 1204.. index:: triple: binary; arithmetic; operation 1205 1206The binary arithmetic operations have the conventional priority levels. Note 1207that some of these operations also apply to certain non-numeric types. Apart 1208from the power operator, there are only two levels, one for multiplicative 1209operators and one for additive operators: 1210 1211.. productionlist:: python-grammar 1212 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` | 1213 : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` | 1214 : `m_expr` "%" `u_expr` 1215 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr` 1216 1217.. index:: 1218 single: multiplication 1219 operator: * (asterisk) 1220 1221The ``*`` (multiplication) operator yields the product of its arguments. The 1222arguments must either both be numbers, or one argument must be an integer and 1223the other must be a sequence. In the former case, the numbers are converted to a 1224common type and then multiplied together. In the latter case, sequence 1225repetition is performed; a negative repetition factor yields an empty sequence. 1226 1227This operation can be customized using the special :meth:`__mul__` and 1228:meth:`__rmul__` methods. 1229 1230.. index:: 1231 single: matrix multiplication 1232 operator: @ (at) 1233 1234The ``@`` (at) operator is intended to be used for matrix multiplication. No 1235builtin Python types implement this operator. 1236 1237.. versionadded:: 3.5 1238 1239.. index:: 1240 exception: ZeroDivisionError 1241 single: division 1242 operator: / (slash) 1243 operator: // 1244 1245The ``/`` (division) and ``//`` (floor division) operators yield the quotient of 1246their arguments. The numeric arguments are first converted to a common type. 1247Division of integers yields a float, while floor division of integers results in an 1248integer; the result is that of mathematical division with the 'floor' function 1249applied to the result. Division by zero raises the :exc:`ZeroDivisionError` 1250exception. 1251 1252This operation can be customized using the special :meth:`__truediv__` and 1253:meth:`__floordiv__` methods. 1254 1255.. index:: 1256 single: modulo 1257 operator: % (percent) 1258 1259The ``%`` (modulo) operator yields the remainder from the division of the first 1260argument by the second. The numeric arguments are first converted to a common 1261type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The 1262arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34`` 1263(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a 1264result with the same sign as its second operand (or zero); the absolute value of 1265the result is strictly smaller than the absolute value of the second operand 1266[#]_. 1267 1268The floor division and modulo operators are connected by the following 1269identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also 1270connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, 1271x%y)``. [#]_. 1272 1273In addition to performing the modulo operation on numbers, the ``%`` operator is 1274also overloaded by string objects to perform old-style string formatting (also 1275known as interpolation). The syntax for string formatting is described in the 1276Python Library Reference, section :ref:`old-string-formatting`. 1277 1278The *modulo* operation can be customized using the special :meth:`__mod__` method. 1279 1280The floor division operator, the modulo operator, and the :func:`divmod` 1281function are not defined for complex numbers. Instead, convert to a floating 1282point number using the :func:`abs` function if appropriate. 1283 1284.. index:: 1285 single: addition 1286 single: operator; + (plus) 1287 single: + (plus); binary operator 1288 1289The ``+`` (addition) operator yields the sum of its arguments. The arguments 1290must either both be numbers or both be sequences of the same type. In the 1291former case, the numbers are converted to a common type and then added together. 1292In the latter case, the sequences are concatenated. 1293 1294This operation can be customized using the special :meth:`__add__` and 1295:meth:`__radd__` methods. 1296 1297.. index:: 1298 single: subtraction 1299 single: operator; - (minus) 1300 single: - (minus); binary operator 1301 1302The ``-`` (subtraction) operator yields the difference of its arguments. The 1303numeric arguments are first converted to a common type. 1304 1305This operation can be customized using the special :meth:`__sub__` method. 1306 1307 1308.. _shifting: 1309 1310Shifting operations 1311=================== 1312 1313.. index:: 1314 pair: shifting; operation 1315 operator: << 1316 operator: >> 1317 1318The shifting operations have lower priority than the arithmetic operations: 1319 1320.. productionlist:: python-grammar 1321 shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr` 1322 1323These operators accept integers as arguments. They shift the first argument to 1324the left or right by the number of bits given by the second argument. 1325 1326This operation can be customized using the special :meth:`__lshift__` and 1327:meth:`__rshift__` methods. 1328 1329.. index:: exception: ValueError 1330 1331A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left 1332shift by *n* bits is defined as multiplication with ``pow(2,n)``. 1333 1334 1335.. _bitwise: 1336 1337Binary bitwise operations 1338========================= 1339 1340.. index:: triple: binary; bitwise; operation 1341 1342Each of the three bitwise operations has a different priority level: 1343 1344.. productionlist:: python-grammar 1345 and_expr: `shift_expr` | `and_expr` "&" `shift_expr` 1346 xor_expr: `and_expr` | `xor_expr` "^" `and_expr` 1347 or_expr: `xor_expr` | `or_expr` "|" `xor_expr` 1348 1349.. index:: 1350 pair: bitwise; and 1351 operator: & (ampersand) 1352 1353The ``&`` operator yields the bitwise AND of its arguments, which must be 1354integers or one of them must be a custom object overriding :meth:`__and__` or 1355:meth:`__rand__` special methods. 1356 1357.. index:: 1358 pair: bitwise; xor 1359 pair: exclusive; or 1360 operator: ^ (caret) 1361 1362The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which 1363must be integers or one of them must be a custom object overriding :meth:`__xor__` or 1364:meth:`__rxor__` special methods. 1365 1366.. index:: 1367 pair: bitwise; or 1368 pair: inclusive; or 1369 operator: | (vertical bar) 1370 1371The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which 1372must be integers or one of them must be a custom object overriding :meth:`__or__` or 1373:meth:`__ror__` special methods. 1374 1375 1376.. _comparisons: 1377 1378Comparisons 1379=========== 1380 1381.. index:: 1382 single: comparison 1383 pair: C; language 1384 operator: < (less) 1385 operator: > (greater) 1386 operator: <= 1387 operator: >= 1388 operator: == 1389 operator: != 1390 1391Unlike C, all comparison operations in Python have the same priority, which is 1392lower than that of any arithmetic, shifting or bitwise operation. Also unlike 1393C, expressions like ``a < b < c`` have the interpretation that is conventional 1394in mathematics: 1395 1396.. productionlist:: python-grammar 1397 comparison: `or_expr` (`comp_operator` `or_expr`)* 1398 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!=" 1399 : | "is" ["not"] | ["not"] "in" 1400 1401Comparisons yield boolean values: ``True`` or ``False``. Custom 1402:dfn:`rich comparison methods` may return non-boolean values. In this case 1403Python will call :func:`bool` on such value in boolean contexts. 1404 1405.. index:: pair: chaining; comparisons 1406 1407Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to 1408``x < y and y <= z``, except that ``y`` is evaluated only once (but in both 1409cases ``z`` is not evaluated at all when ``x < y`` is found to be false). 1410 1411Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., 1412*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent 1413to ``a op1 b and b op2 c and ... y opN z``, except that each expression is 1414evaluated at most once. 1415 1416Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and 1417*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not 1418pretty). 1419 1420Value comparisons 1421----------------- 1422 1423The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the 1424values of two objects. The objects do not need to have the same type. 1425 1426Chapter :ref:`objects` states that objects have a value (in addition to type 1427and identity). The value of an object is a rather abstract notion in Python: 1428For example, there is no canonical access method for an object's value. Also, 1429there is no requirement that the value of an object should be constructed in a 1430particular way, e.g. comprised of all its data attributes. Comparison operators 1431implement a particular notion of what the value of an object is. One can think 1432of them as defining the value of an object indirectly, by means of their 1433comparison implementation. 1434 1435Because all types are (direct or indirect) subtypes of :class:`object`, they 1436inherit the default comparison behavior from :class:`object`. Types can 1437customize their comparison behavior by implementing 1438:dfn:`rich comparison methods` like :meth:`__lt__`, described in 1439:ref:`customization`. 1440 1441The default behavior for equality comparison (``==`` and ``!=``) is based on 1442the identity of the objects. Hence, equality comparison of instances with the 1443same identity results in equality, and equality comparison of instances with 1444different identities results in inequality. A motivation for this default 1445behavior is the desire that all objects should be reflexive (i.e. ``x is y`` 1446implies ``x == y``). 1447 1448A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; 1449an attempt raises :exc:`TypeError`. A motivation for this default behavior is 1450the lack of a similar invariant as for equality. 1451 1452The behavior of the default equality comparison, that instances with different 1453identities are always unequal, may be in contrast to what types will need that 1454have a sensible definition of object value and value-based equality. Such 1455types will need to customize their comparison behavior, and in fact, a number 1456of built-in types have done that. 1457 1458The following list describes the comparison behavior of the most important 1459built-in types. 1460 1461* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard 1462 library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be 1463 compared within and across their types, with the restriction that complex 1464 numbers do not support order comparison. Within the limits of the types 1465 involved, they compare mathematically (algorithmically) correct without loss 1466 of precision. 1467 1468 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are 1469 special. Any ordered comparison of a number to a not-a-number value is false. 1470 A counter-intuitive implication is that not-a-number values are not equal to 1471 themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and 1472 ``x == x`` are all false, while ``x != x`` is true. This behavior is 1473 compliant with IEEE 754. 1474 1475* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that 1476 comparisons for singletons should always be done with ``is`` or ``is not``, 1477 never the equality operators. 1478 1479* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be 1480 compared within and across their types. They compare lexicographically using 1481 the numeric values of their elements. 1482 1483* Strings (instances of :class:`str`) compare lexicographically using the 1484 numerical Unicode code points (the result of the built-in function 1485 :func:`ord`) of their characters. [#]_ 1486 1487 Strings and binary sequences cannot be directly compared. 1488 1489* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can 1490 be compared only within each of their types, with the restriction that ranges 1491 do not support order comparison. Equality comparison across these types 1492 results in inequality, and ordering comparison across these types raises 1493 :exc:`TypeError`. 1494 1495 Sequences compare lexicographically using comparison of corresponding 1496 elements. The built-in containers typically assume identical objects are 1497 equal to themselves. That lets them bypass equality tests for identical 1498 objects to improve performance and to maintain their internal invariants. 1499 1500 Lexicographical comparison between built-in collections works as follows: 1501 1502 - For two collections to compare equal, they must be of the same type, have 1503 the same length, and each pair of corresponding elements must compare 1504 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the 1505 same). 1506 1507 - Collections that support order comparison are ordered the same as their 1508 first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same 1509 value as ``x <= y``). If a corresponding element does not exist, the 1510 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is 1511 true). 1512 1513* Mappings (instances of :class:`dict`) compare equal if and only if they have 1514 equal `(key, value)` pairs. Equality comparison of the keys and values 1515 enforces reflexivity. 1516 1517 Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`. 1518 1519* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within 1520 and across their types. 1521 1522 They define order 1523 comparison operators to mean subset and superset tests. Those relations do 1524 not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` 1525 are not equal, nor subsets of one another, nor supersets of one 1526 another). Accordingly, sets are not appropriate arguments for functions 1527 which depend on total ordering (for example, :func:`min`, :func:`max`, and 1528 :func:`sorted` produce undefined results given a list of sets as inputs). 1529 1530 Comparison of sets enforces reflexivity of its elements. 1531 1532* Most other built-in types have no comparison methods implemented, so they 1533 inherit the default comparison behavior. 1534 1535User-defined classes that customize their comparison behavior should follow 1536some consistency rules, if possible: 1537 1538* Equality comparison should be reflexive. 1539 In other words, identical objects should compare equal: 1540 1541 ``x is y`` implies ``x == y`` 1542 1543* Comparison should be symmetric. 1544 In other words, the following expressions should have the same result: 1545 1546 ``x == y`` and ``y == x`` 1547 1548 ``x != y`` and ``y != x`` 1549 1550 ``x < y`` and ``y > x`` 1551 1552 ``x <= y`` and ``y >= x`` 1553 1554* Comparison should be transitive. 1555 The following (non-exhaustive) examples illustrate that: 1556 1557 ``x > y and y > z`` implies ``x > z`` 1558 1559 ``x < y and y <= z`` implies ``x < z`` 1560 1561* Inverse comparison should result in the boolean negation. 1562 In other words, the following expressions should have the same result: 1563 1564 ``x == y`` and ``not x != y`` 1565 1566 ``x < y`` and ``not x >= y`` (for total ordering) 1567 1568 ``x > y`` and ``not x <= y`` (for total ordering) 1569 1570 The last two expressions apply to totally ordered collections (e.g. to 1571 sequences, but not to sets or mappings). See also the 1572 :func:`~functools.total_ordering` decorator. 1573 1574* The :func:`hash` result should be consistent with equality. 1575 Objects that are equal should either have the same hash value, 1576 or be marked as unhashable. 1577 1578Python does not enforce these consistency rules. In fact, the not-a-number 1579values are an example for not following these rules. 1580 1581 1582.. _in: 1583.. _not in: 1584.. _membership-test-details: 1585 1586Membership test operations 1587-------------------------- 1588 1589The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in 1590s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. 1591``x not in s`` returns the negation of ``x in s``. All built-in sequences and 1592set types support this as well as dictionary, for which :keyword:`!in` tests 1593whether the dictionary has a given key. For container types such as list, tuple, 1594set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent 1595to ``any(x is e or x == e for e in y)``. 1596 1597For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a 1598substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are 1599always considered to be a substring of any other string, so ``"" in "abc"`` will 1600return ``True``. 1601 1602For user-defined classes which define the :meth:`__contains__` method, ``x in 1603y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and 1604``False`` otherwise. 1605 1606For user-defined classes which do not define :meth:`__contains__` but do define 1607:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the 1608expression ``x is z or x == z`` is true, is produced while iterating over ``y``. 1609If an exception is raised during the iteration, it is as if :keyword:`in` raised 1610that exception. 1611 1612Lastly, the old-style iteration protocol is tried: if a class defines 1613:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative 1614integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index 1615raises the :exc:`IndexError` exception. (If any other exception is raised, it is as 1616if :keyword:`in` raised that exception). 1617 1618.. index:: 1619 operator: in 1620 operator: not in 1621 pair: membership; test 1622 object: sequence 1623 1624The operator :keyword:`not in` is defined to have the inverse truth value of 1625:keyword:`in`. 1626 1627.. index:: 1628 operator: is 1629 operator: is not 1630 pair: identity; test 1631 1632 1633.. _is: 1634.. _is not: 1635 1636Identity comparisons 1637-------------------- 1638 1639The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x 1640is y`` is true if and only if *x* and *y* are the same object. An Object's identity 1641is determined using the :meth:`id` function. ``x is not y`` yields the inverse 1642truth value. [#]_ 1643 1644 1645.. _booleans: 1646.. _and: 1647.. _or: 1648.. _not: 1649 1650Boolean operations 1651================== 1652 1653.. index:: 1654 pair: Conditional; expression 1655 pair: Boolean; operation 1656 1657.. productionlist:: python-grammar 1658 or_test: `and_test` | `or_test` "or" `and_test` 1659 and_test: `not_test` | `and_test` "and" `not_test` 1660 not_test: `comparison` | "not" `not_test` 1661 1662In the context of Boolean operations, and also when expressions are used by 1663control flow statements, the following values are interpreted as false: 1664``False``, ``None``, numeric zero of all types, and empty strings and containers 1665(including strings, tuples, lists, dictionaries, sets and frozensets). All 1666other values are interpreted as true. User-defined objects can customize their 1667truth value by providing a :meth:`__bool__` method. 1668 1669.. index:: operator: not 1670 1671The operator :keyword:`not` yields ``True`` if its argument is false, ``False`` 1672otherwise. 1673 1674.. index:: operator: and 1675 1676The expression ``x and y`` first evaluates *x*; if *x* is false, its value is 1677returned; otherwise, *y* is evaluated and the resulting value is returned. 1678 1679.. index:: operator: or 1680 1681The expression ``x or y`` first evaluates *x*; if *x* is true, its value is 1682returned; otherwise, *y* is evaluated and the resulting value is returned. 1683 1684Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type 1685they return to ``False`` and ``True``, but rather return the last evaluated 1686argument. This is sometimes useful, e.g., if ``s`` is a string that should be 1687replaced by a default value if it is empty, the expression ``s or 'foo'`` yields 1688the desired value. Because :keyword:`not` has to create a new value, it 1689returns a boolean value regardless of the type of its argument 1690(for example, ``not 'foo'`` produces ``False`` rather than ``''``.) 1691 1692 1693Assignment expressions 1694====================== 1695 1696.. productionlist:: python-grammar 1697 assignment_expression: [`identifier` ":="] `expression` 1698 1699An assignment expression (sometimes also called a "named expression" or 1700"walrus") assigns an :token:`~python-grammar:expression` to an 1701:token:`~python-grammar:identifier`, while also returning the value of the 1702:token:`~python-grammar:expression`. 1703 1704One common use case is when handling matched regular expressions: 1705 1706.. code-block:: python 1707 1708 if matching := pattern.search(data): 1709 do_something(matching) 1710 1711Or, when processing a file stream in chunks: 1712 1713.. code-block:: python 1714 1715 while chunk := file.read(9000): 1716 process(chunk) 1717 1718.. versionadded:: 3.8 1719 See :pep:`572` for more details about assignment expressions. 1720 1721 1722.. _if_expr: 1723 1724Conditional expressions 1725======================= 1726 1727.. index:: 1728 pair: conditional; expression 1729 pair: ternary; operator 1730 single: if; conditional expression 1731 single: else; conditional expression 1732 1733.. productionlist:: python-grammar 1734 conditional_expression: `or_test` ["if" `or_test` "else" `expression`] 1735 expression: `conditional_expression` | `lambda_expr` 1736 1737Conditional expressions (sometimes called a "ternary operator") have the lowest 1738priority of all Python operations. 1739 1740The expression ``x if C else y`` first evaluates the condition, *C* rather than *x*. 1741If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is 1742evaluated and its value is returned. 1743 1744See :pep:`308` for more details about conditional expressions. 1745 1746 1747.. _lambdas: 1748.. _lambda: 1749 1750Lambdas 1751======= 1752 1753.. index:: 1754 pair: lambda; expression 1755 pair: lambda; form 1756 pair: anonymous; function 1757 single: : (colon); lambda expression 1758 1759.. productionlist:: python-grammar 1760 lambda_expr: "lambda" [`parameter_list`] ":" `expression` 1761 1762Lambda expressions (sometimes called lambda forms) are used to create anonymous 1763functions. The expression ``lambda parameters: expression`` yields a function 1764object. The unnamed object behaves like a function object defined with: 1765 1766.. code-block:: none 1767 1768 def <lambda>(parameters): 1769 return expression 1770 1771See section :ref:`function` for the syntax of parameter lists. Note that 1772functions created with lambda expressions cannot contain statements or 1773annotations. 1774 1775 1776.. _exprlists: 1777 1778Expression lists 1779================ 1780 1781.. index:: 1782 pair: expression; list 1783 single: , (comma); expression list 1784 1785.. productionlist:: python-grammar 1786 expression_list: `expression` ("," `expression`)* [","] 1787 starred_list: `starred_item` ("," `starred_item`)* [","] 1788 starred_expression: `expression` | (`starred_item` ",")* [`starred_item`] 1789 starred_item: `assignment_expression` | "*" `or_expr` 1790 1791.. index:: object: tuple 1792 1793Except when part of a list or set display, an expression list 1794containing at least one comma yields a tuple. The length of 1795the tuple is the number of expressions in the list. The expressions are 1796evaluated from left to right. 1797 1798.. index:: 1799 pair: iterable; unpacking 1800 single: * (asterisk); in expression lists 1801 1802An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be 1803an :term:`iterable`. The iterable is expanded into a sequence of items, 1804which are included in the new tuple, list, or set, at the site of 1805the unpacking. 1806 1807.. versionadded:: 3.5 1808 Iterable unpacking in expression lists, originally proposed by :pep:`448`. 1809 1810.. index:: pair: trailing; comma 1811 1812The trailing comma is required only to create a single tuple (a.k.a. a 1813*singleton*); it is optional in all other cases. A single expression without a 1814trailing comma doesn't create a tuple, but rather yields the value of that 1815expression. (To create an empty tuple, use an empty pair of parentheses: 1816``()``.) 1817 1818 1819.. _evalorder: 1820 1821Evaluation order 1822================ 1823 1824.. index:: pair: evaluation; order 1825 1826Python evaluates expressions from left to right. Notice that while evaluating 1827an assignment, the right-hand side is evaluated before the left-hand side. 1828 1829In the following lines, expressions will be evaluated in the arithmetic order of 1830their suffixes:: 1831 1832 expr1, expr2, expr3, expr4 1833 (expr1, expr2, expr3, expr4) 1834 {expr1: expr2, expr3: expr4} 1835 expr1 + expr2 * (expr3 - expr4) 1836 expr1(expr2, expr3, *expr4, **expr5) 1837 expr3, expr4 = expr1, expr2 1838 1839 1840.. _operator-summary: 1841 1842Operator precedence 1843=================== 1844 1845.. index:: 1846 pair: operator; precedence 1847 1848The following table summarizes the operator precedence in Python, from highest 1849precedence (most binding) to lowest precedence (least binding). Operators in 1850the same box have the same precedence. Unless the syntax is explicitly given, 1851operators are binary. Operators in the same box group left to right (except for 1852exponentiation, which groups from right to left). 1853 1854Note that comparisons, membership tests, and identity tests, all have the same 1855precedence and have a left-to-right chaining feature as described in the 1856:ref:`comparisons` section. 1857 1858 1859+-----------------------------------------------+-------------------------------------+ 1860| Operator | Description | 1861+===============================================+=====================================+ 1862| ``(expressions...)``, | Binding or parenthesized | 1863| | expression, | 1864| ``[expressions...]``, | list display, | 1865| ``{key: value...}``, | dictionary display, | 1866| ``{expressions...}`` | set display | 1867+-----------------------------------------------+-------------------------------------+ 1868| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | 1869| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | 1870+-----------------------------------------------+-------------------------------------+ 1871| :keyword:`await` ``x`` | Await expression | 1872+-----------------------------------------------+-------------------------------------+ 1873| ``**`` | Exponentiation [#]_ | 1874+-----------------------------------------------+-------------------------------------+ 1875| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | 1876+-----------------------------------------------+-------------------------------------+ 1877| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | 1878| | multiplication, division, floor | 1879| | division, remainder [#]_ | 1880+-----------------------------------------------+-------------------------------------+ 1881| ``+``, ``-`` | Addition and subtraction | 1882+-----------------------------------------------+-------------------------------------+ 1883| ``<<``, ``>>`` | Shifts | 1884+-----------------------------------------------+-------------------------------------+ 1885| ``&`` | Bitwise AND | 1886+-----------------------------------------------+-------------------------------------+ 1887| ``^`` | Bitwise XOR | 1888+-----------------------------------------------+-------------------------------------+ 1889| ``|`` | Bitwise OR | 1890+-----------------------------------------------+-------------------------------------+ 1891| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | 1892| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | 1893| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | 1894+-----------------------------------------------+-------------------------------------+ 1895| :keyword:`not` ``x`` | Boolean NOT | 1896+-----------------------------------------------+-------------------------------------+ 1897| :keyword:`and` | Boolean AND | 1898+-----------------------------------------------+-------------------------------------+ 1899| :keyword:`or` | Boolean OR | 1900+-----------------------------------------------+-------------------------------------+ 1901| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression | 1902+-----------------------------------------------+-------------------------------------+ 1903| :keyword:`lambda` | Lambda expression | 1904+-----------------------------------------------+-------------------------------------+ 1905| ``:=`` | Assignment expression | 1906+-----------------------------------------------+-------------------------------------+ 1907 1908 1909.. rubric:: Footnotes 1910 1911.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be 1912 true numerically due to roundoff. For example, and assuming a platform on which 1913 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % 1914 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + 1915 1e100``, which is numerically exactly equal to ``1e100``. The function 1916 :func:`math.fmod` returns a result whose sign matches the sign of the 1917 first argument instead, and so returns ``-1e-100`` in this case. Which approach 1918 is more appropriate depends on the application. 1919 1920.. [#] If x is very close to an exact integer multiple of y, it's possible for 1921 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such 1922 cases, Python returns the latter result, in order to preserve that 1923 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. 1924 1925.. [#] The Unicode standard distinguishes between :dfn:`code points` 1926 (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). 1927 While most abstract characters in Unicode are only represented using one 1928 code point, there is a number of abstract characters that can in addition be 1929 represented using a sequence of more than one code point. For example, the 1930 abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented 1931 as a single :dfn:`precomposed character` at code position U+00C7, or as a 1932 sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL 1933 LETTER C), followed by a :dfn:`combining character` at code position U+0327 1934 (COMBINING CEDILLA). 1935 1936 The comparison operators on strings compare at the level of Unicode code 1937 points. This may be counter-intuitive to humans. For example, 1938 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings 1939 represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". 1940 1941 To compare strings at the level of abstract characters (that is, in a way 1942 intuitive to humans), use :func:`unicodedata.normalize`. 1943 1944.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of 1945 descriptors, you may notice seemingly unusual behaviour in certain uses of 1946 the :keyword:`is` operator, like those involving comparisons between instance 1947 methods, or constants. Check their documentation for more info. 1948 1949.. [#] The power operator ``**`` binds less tightly than an arithmetic or 1950 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. 1951 1952.. [#] The ``%`` operator is also used for string formatting; the same 1953 precedence applies. 1954