17db96d56Sopenharmony_ci 27db96d56Sopenharmony_ci.. _expressions: 37db96d56Sopenharmony_ci 47db96d56Sopenharmony_ci*********** 57db96d56Sopenharmony_ciExpressions 67db96d56Sopenharmony_ci*********** 77db96d56Sopenharmony_ci 87db96d56Sopenharmony_ci.. index:: expression, BNF 97db96d56Sopenharmony_ci 107db96d56Sopenharmony_ciThis chapter explains the meaning of the elements of expressions in Python. 117db96d56Sopenharmony_ci 127db96d56Sopenharmony_ci**Syntax Notes:** In this and the following chapters, extended BNF notation will 137db96d56Sopenharmony_cibe used to describe syntax, not lexical analysis. When (one alternative of) a 147db96d56Sopenharmony_cisyntax rule has the form 157db96d56Sopenharmony_ci 167db96d56Sopenharmony_ci.. productionlist:: python-grammar 177db96d56Sopenharmony_ci name: `othername` 187db96d56Sopenharmony_ci 197db96d56Sopenharmony_ciand no semantics are given, the semantics of this form of ``name`` are the same 207db96d56Sopenharmony_cias for ``othername``. 217db96d56Sopenharmony_ci 227db96d56Sopenharmony_ci 237db96d56Sopenharmony_ci.. _conversions: 247db96d56Sopenharmony_ci 257db96d56Sopenharmony_ciArithmetic conversions 267db96d56Sopenharmony_ci====================== 277db96d56Sopenharmony_ci 287db96d56Sopenharmony_ci.. index:: pair: arithmetic; conversion 297db96d56Sopenharmony_ci 307db96d56Sopenharmony_ciWhen a description of an arithmetic operator below uses the phrase "the numeric 317db96d56Sopenharmony_ciarguments are converted to a common type", this means that the operator 327db96d56Sopenharmony_ciimplementation for built-in types works as follows: 337db96d56Sopenharmony_ci 347db96d56Sopenharmony_ci* If either argument is a complex number, the other is converted to complex; 357db96d56Sopenharmony_ci 367db96d56Sopenharmony_ci* otherwise, if either argument is a floating point number, the other is 377db96d56Sopenharmony_ci converted to floating point; 387db96d56Sopenharmony_ci 397db96d56Sopenharmony_ci* otherwise, both must be integers and no conversion is necessary. 407db96d56Sopenharmony_ci 417db96d56Sopenharmony_ciSome additional rules apply for certain operators (e.g., a string as a left 427db96d56Sopenharmony_ciargument to the '%' operator). Extensions must define their own conversion 437db96d56Sopenharmony_cibehavior. 447db96d56Sopenharmony_ci 457db96d56Sopenharmony_ci 467db96d56Sopenharmony_ci.. _atoms: 477db96d56Sopenharmony_ci 487db96d56Sopenharmony_ciAtoms 497db96d56Sopenharmony_ci===== 507db96d56Sopenharmony_ci 517db96d56Sopenharmony_ci.. index:: atom 527db96d56Sopenharmony_ci 537db96d56Sopenharmony_ciAtoms are the most basic elements of expressions. The simplest atoms are 547db96d56Sopenharmony_ciidentifiers or literals. Forms enclosed in parentheses, brackets or braces are 557db96d56Sopenharmony_cialso categorized syntactically as atoms. The syntax for atoms is: 567db96d56Sopenharmony_ci 577db96d56Sopenharmony_ci.. productionlist:: python-grammar 587db96d56Sopenharmony_ci atom: `identifier` | `literal` | `enclosure` 597db96d56Sopenharmony_ci enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display` 607db96d56Sopenharmony_ci : | `generator_expression` | `yield_atom` 617db96d56Sopenharmony_ci 627db96d56Sopenharmony_ci 637db96d56Sopenharmony_ci.. _atom-identifiers: 647db96d56Sopenharmony_ci 657db96d56Sopenharmony_ciIdentifiers (Names) 667db96d56Sopenharmony_ci------------------- 677db96d56Sopenharmony_ci 687db96d56Sopenharmony_ci.. index:: name, identifier 697db96d56Sopenharmony_ci 707db96d56Sopenharmony_ciAn identifier occurring as an atom is a name. See section :ref:`identifiers` 717db96d56Sopenharmony_cifor lexical definition and section :ref:`naming` for documentation of naming and 727db96d56Sopenharmony_cibinding. 737db96d56Sopenharmony_ci 747db96d56Sopenharmony_ci.. index:: pair: exception; NameError 757db96d56Sopenharmony_ci 767db96d56Sopenharmony_ciWhen the name is bound to an object, evaluation of the atom yields that object. 777db96d56Sopenharmony_ciWhen a name is not bound, an attempt to evaluate it raises a :exc:`NameError` 787db96d56Sopenharmony_ciexception. 797db96d56Sopenharmony_ci 807db96d56Sopenharmony_ci.. _private-name-mangling: 817db96d56Sopenharmony_ci 827db96d56Sopenharmony_ci.. index:: 837db96d56Sopenharmony_ci pair: name; mangling 847db96d56Sopenharmony_ci pair: private; names 857db96d56Sopenharmony_ci 867db96d56Sopenharmony_ci**Private name mangling:** When an identifier that textually occurs in a class 877db96d56Sopenharmony_cidefinition begins with two or more underscore characters and does not end in two 887db96d56Sopenharmony_cior more underscores, it is considered a :dfn:`private name` of that class. 897db96d56Sopenharmony_ciPrivate names are transformed to a longer form before code is generated for 907db96d56Sopenharmony_cithem. The transformation inserts the class name, with leading underscores 917db96d56Sopenharmony_ciremoved and a single underscore inserted, in front of the name. For example, 927db96d56Sopenharmony_cithe identifier ``__spam`` occurring in a class named ``Ham`` will be transformed 937db96d56Sopenharmony_cito ``_Ham__spam``. This transformation is independent of the syntactical 947db96d56Sopenharmony_cicontext in which the identifier is used. If the transformed name is extremely 957db96d56Sopenharmony_cilong (longer than 255 characters), implementation defined truncation may happen. 967db96d56Sopenharmony_ciIf the class name consists only of underscores, no transformation is done. 977db96d56Sopenharmony_ci 987db96d56Sopenharmony_ci 997db96d56Sopenharmony_ci.. _atom-literals: 1007db96d56Sopenharmony_ci 1017db96d56Sopenharmony_ciLiterals 1027db96d56Sopenharmony_ci-------- 1037db96d56Sopenharmony_ci 1047db96d56Sopenharmony_ci.. index:: single: literal 1057db96d56Sopenharmony_ci 1067db96d56Sopenharmony_ciPython supports string and bytes literals and various numeric literals: 1077db96d56Sopenharmony_ci 1087db96d56Sopenharmony_ci.. productionlist:: python-grammar 1097db96d56Sopenharmony_ci literal: `stringliteral` | `bytesliteral` 1107db96d56Sopenharmony_ci : | `integer` | `floatnumber` | `imagnumber` 1117db96d56Sopenharmony_ci 1127db96d56Sopenharmony_ciEvaluation of a literal yields an object of the given type (string, bytes, 1137db96d56Sopenharmony_ciinteger, floating point number, complex number) with the given value. The value 1147db96d56Sopenharmony_cimay be approximated in the case of floating point and imaginary (complex) 1157db96d56Sopenharmony_ciliterals. See section :ref:`literals` for details. 1167db96d56Sopenharmony_ci 1177db96d56Sopenharmony_ci.. index:: 1187db96d56Sopenharmony_ci triple: immutable; data; type 1197db96d56Sopenharmony_ci pair: immutable; object 1207db96d56Sopenharmony_ci 1217db96d56Sopenharmony_ciAll literals correspond to immutable data types, and hence the object's identity 1227db96d56Sopenharmony_ciis less important than its value. Multiple evaluations of literals with the 1237db96d56Sopenharmony_cisame value (either the same occurrence in the program text or a different 1247db96d56Sopenharmony_cioccurrence) may obtain the same object or a different object with the same 1257db96d56Sopenharmony_civalue. 1267db96d56Sopenharmony_ci 1277db96d56Sopenharmony_ci 1287db96d56Sopenharmony_ci.. _parenthesized: 1297db96d56Sopenharmony_ci 1307db96d56Sopenharmony_ciParenthesized forms 1317db96d56Sopenharmony_ci------------------- 1327db96d56Sopenharmony_ci 1337db96d56Sopenharmony_ci.. index:: 1347db96d56Sopenharmony_ci single: parenthesized form 1357db96d56Sopenharmony_ci single: () (parentheses); tuple display 1367db96d56Sopenharmony_ci 1377db96d56Sopenharmony_ciA parenthesized form is an optional expression list enclosed in parentheses: 1387db96d56Sopenharmony_ci 1397db96d56Sopenharmony_ci.. productionlist:: python-grammar 1407db96d56Sopenharmony_ci parenth_form: "(" [`starred_expression`] ")" 1417db96d56Sopenharmony_ci 1427db96d56Sopenharmony_ciA parenthesized expression list yields whatever that expression list yields: if 1437db96d56Sopenharmony_cithe list contains at least one comma, it yields a tuple; otherwise, it yields 1447db96d56Sopenharmony_cithe single expression that makes up the expression list. 1457db96d56Sopenharmony_ci 1467db96d56Sopenharmony_ci.. index:: pair: empty; tuple 1477db96d56Sopenharmony_ci 1487db96d56Sopenharmony_ciAn empty pair of parentheses yields an empty tuple object. Since tuples are 1497db96d56Sopenharmony_ciimmutable, the same rules as for literals apply (i.e., two occurrences of the empty 1507db96d56Sopenharmony_cituple may or may not yield the same object). 1517db96d56Sopenharmony_ci 1527db96d56Sopenharmony_ci.. index:: 1537db96d56Sopenharmony_ci single: comma 1547db96d56Sopenharmony_ci single: , (comma) 1557db96d56Sopenharmony_ci 1567db96d56Sopenharmony_ciNote that tuples are not formed by the parentheses, but rather by use of the 1577db96d56Sopenharmony_cicomma. The exception is the empty tuple, for which parentheses *are* 1587db96d56Sopenharmony_cirequired --- allowing unparenthesized "nothing" in expressions would cause 1597db96d56Sopenharmony_ciambiguities and allow common typos to pass uncaught. 1607db96d56Sopenharmony_ci 1617db96d56Sopenharmony_ci 1627db96d56Sopenharmony_ci.. _comprehensions: 1637db96d56Sopenharmony_ci 1647db96d56Sopenharmony_ciDisplays for lists, sets and dictionaries 1657db96d56Sopenharmony_ci----------------------------------------- 1667db96d56Sopenharmony_ci 1677db96d56Sopenharmony_ci.. index:: single: comprehensions 1687db96d56Sopenharmony_ci 1697db96d56Sopenharmony_ciFor constructing a list, a set or a dictionary Python provides special syntax 1707db96d56Sopenharmony_cicalled "displays", each of them in two flavors: 1717db96d56Sopenharmony_ci 1727db96d56Sopenharmony_ci* either the container contents are listed explicitly, or 1737db96d56Sopenharmony_ci 1747db96d56Sopenharmony_ci* they are computed via a set of looping and filtering instructions, called a 1757db96d56Sopenharmony_ci :dfn:`comprehension`. 1767db96d56Sopenharmony_ci 1777db96d56Sopenharmony_ci.. index:: 1787db96d56Sopenharmony_ci single: for; in comprehensions 1797db96d56Sopenharmony_ci single: if; in comprehensions 1807db96d56Sopenharmony_ci single: async for; in comprehensions 1817db96d56Sopenharmony_ci 1827db96d56Sopenharmony_ciCommon syntax elements for comprehensions are: 1837db96d56Sopenharmony_ci 1847db96d56Sopenharmony_ci.. productionlist:: python-grammar 1857db96d56Sopenharmony_ci comprehension: `assignment_expression` `comp_for` 1867db96d56Sopenharmony_ci comp_for: ["async"] "for" `target_list` "in" `or_test` [`comp_iter`] 1877db96d56Sopenharmony_ci comp_iter: `comp_for` | `comp_if` 1887db96d56Sopenharmony_ci comp_if: "if" `or_test` [`comp_iter`] 1897db96d56Sopenharmony_ci 1907db96d56Sopenharmony_ciThe comprehension consists of a single expression followed by at least one 1917db96d56Sopenharmony_ci:keyword:`!for` clause and zero or more :keyword:`!for` or :keyword:`!if` clauses. 1927db96d56Sopenharmony_ciIn this case, the elements of the new container are those that would be produced 1937db96d56Sopenharmony_ciby considering each of the :keyword:`!for` or :keyword:`!if` clauses a block, 1947db96d56Sopenharmony_cinesting from left to right, and evaluating the expression to produce an element 1957db96d56Sopenharmony_cieach time the innermost block is reached. 1967db96d56Sopenharmony_ci 1977db96d56Sopenharmony_ciHowever, aside from the iterable expression in the leftmost :keyword:`!for` clause, 1987db96d56Sopenharmony_cithe comprehension is executed in a separate implicitly nested scope. This ensures 1997db96d56Sopenharmony_cithat names assigned to in the target list don't "leak" into the enclosing scope. 2007db96d56Sopenharmony_ci 2017db96d56Sopenharmony_ciThe iterable expression in the leftmost :keyword:`!for` clause is evaluated 2027db96d56Sopenharmony_cidirectly in the enclosing scope and then passed as an argument to the implicitly 2037db96d56Sopenharmony_cinested scope. Subsequent :keyword:`!for` clauses and any filter condition in the 2047db96d56Sopenharmony_cileftmost :keyword:`!for` clause cannot be evaluated in the enclosing scope as 2057db96d56Sopenharmony_cithey may depend on the values obtained from the leftmost iterable. For example: 2067db96d56Sopenharmony_ci``[x*y for x in range(10) for y in range(x, x+10)]``. 2077db96d56Sopenharmony_ci 2087db96d56Sopenharmony_ciTo ensure the comprehension always results in a container of the appropriate 2097db96d56Sopenharmony_citype, ``yield`` and ``yield from`` expressions are prohibited in the implicitly 2107db96d56Sopenharmony_cinested scope. 2117db96d56Sopenharmony_ci 2127db96d56Sopenharmony_ci.. index:: 2137db96d56Sopenharmony_ci single: await; in comprehensions 2147db96d56Sopenharmony_ci 2157db96d56Sopenharmony_ciSince Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for` 2167db96d56Sopenharmony_ciclause may be used to iterate over a :term:`asynchronous iterator`. 2177db96d56Sopenharmony_ciA comprehension in an :keyword:`!async def` function may consist of either a 2187db96d56Sopenharmony_ci:keyword:`!for` or :keyword:`!async for` clause following the leading 2197db96d56Sopenharmony_ciexpression, may contain additional :keyword:`!for` or :keyword:`!async for` 2207db96d56Sopenharmony_ciclauses, and may also use :keyword:`await` expressions. 2217db96d56Sopenharmony_ciIf a comprehension contains either :keyword:`!async for` clauses or 2227db96d56Sopenharmony_ci:keyword:`!await` expressions or other asynchronous comprehensions it is called 2237db96d56Sopenharmony_cian :dfn:`asynchronous comprehension`. An asynchronous comprehension may 2247db96d56Sopenharmony_cisuspend the execution of the coroutine function in which it appears. 2257db96d56Sopenharmony_ciSee also :pep:`530`. 2267db96d56Sopenharmony_ci 2277db96d56Sopenharmony_ci.. versionadded:: 3.6 2287db96d56Sopenharmony_ci Asynchronous comprehensions were introduced. 2297db96d56Sopenharmony_ci 2307db96d56Sopenharmony_ci.. versionchanged:: 3.8 2317db96d56Sopenharmony_ci ``yield`` and ``yield from`` prohibited in the implicitly nested scope. 2327db96d56Sopenharmony_ci 2337db96d56Sopenharmony_ci.. versionchanged:: 3.11 2347db96d56Sopenharmony_ci Asynchronous comprehensions are now allowed inside comprehensions in 2357db96d56Sopenharmony_ci asynchronous functions. Outer comprehensions implicitly become 2367db96d56Sopenharmony_ci asynchronous. 2377db96d56Sopenharmony_ci 2387db96d56Sopenharmony_ci 2397db96d56Sopenharmony_ci.. _lists: 2407db96d56Sopenharmony_ci 2417db96d56Sopenharmony_ciList displays 2427db96d56Sopenharmony_ci------------- 2437db96d56Sopenharmony_ci 2447db96d56Sopenharmony_ci.. index:: 2457db96d56Sopenharmony_ci pair: list; display 2467db96d56Sopenharmony_ci pair: list; comprehensions 2477db96d56Sopenharmony_ci pair: empty; list 2487db96d56Sopenharmony_ci pair: object; list 2497db96d56Sopenharmony_ci single: [] (square brackets); list expression 2507db96d56Sopenharmony_ci single: , (comma); expression list 2517db96d56Sopenharmony_ci 2527db96d56Sopenharmony_ciA list display is a possibly empty series of expressions enclosed in square 2537db96d56Sopenharmony_cibrackets: 2547db96d56Sopenharmony_ci 2557db96d56Sopenharmony_ci.. productionlist:: python-grammar 2567db96d56Sopenharmony_ci list_display: "[" [`starred_list` | `comprehension`] "]" 2577db96d56Sopenharmony_ci 2587db96d56Sopenharmony_ciA list display yields a new list object, the contents being specified by either 2597db96d56Sopenharmony_cia list of expressions or a comprehension. When a comma-separated list of 2607db96d56Sopenharmony_ciexpressions is supplied, its elements are evaluated from left to right and 2617db96d56Sopenharmony_ciplaced into the list object in that order. When a comprehension is supplied, 2627db96d56Sopenharmony_cithe list is constructed from the elements resulting from the comprehension. 2637db96d56Sopenharmony_ci 2647db96d56Sopenharmony_ci 2657db96d56Sopenharmony_ci.. _set: 2667db96d56Sopenharmony_ci 2677db96d56Sopenharmony_ciSet displays 2687db96d56Sopenharmony_ci------------ 2697db96d56Sopenharmony_ci 2707db96d56Sopenharmony_ci.. index:: 2717db96d56Sopenharmony_ci pair: set; display 2727db96d56Sopenharmony_ci pair: set; comprehensions 2737db96d56Sopenharmony_ci pair: object; set 2747db96d56Sopenharmony_ci single: {} (curly brackets); set expression 2757db96d56Sopenharmony_ci single: , (comma); expression list 2767db96d56Sopenharmony_ci 2777db96d56Sopenharmony_ciA set display is denoted by curly braces and distinguishable from dictionary 2787db96d56Sopenharmony_cidisplays by the lack of colons separating keys and values: 2797db96d56Sopenharmony_ci 2807db96d56Sopenharmony_ci.. productionlist:: python-grammar 2817db96d56Sopenharmony_ci set_display: "{" (`starred_list` | `comprehension`) "}" 2827db96d56Sopenharmony_ci 2837db96d56Sopenharmony_ciA set display yields a new mutable set object, the contents being specified by 2847db96d56Sopenharmony_cieither a sequence of expressions or a comprehension. When a comma-separated 2857db96d56Sopenharmony_cilist of expressions is supplied, its elements are evaluated from left to right 2867db96d56Sopenharmony_ciand added to the set object. When a comprehension is supplied, the set is 2877db96d56Sopenharmony_ciconstructed from the elements resulting from the comprehension. 2887db96d56Sopenharmony_ci 2897db96d56Sopenharmony_ciAn empty set cannot be constructed with ``{}``; this literal constructs an empty 2907db96d56Sopenharmony_cidictionary. 2917db96d56Sopenharmony_ci 2927db96d56Sopenharmony_ci 2937db96d56Sopenharmony_ci.. _dict: 2947db96d56Sopenharmony_ci 2957db96d56Sopenharmony_ciDictionary displays 2967db96d56Sopenharmony_ci------------------- 2977db96d56Sopenharmony_ci 2987db96d56Sopenharmony_ci.. index:: 2997db96d56Sopenharmony_ci pair: dictionary; display 3007db96d56Sopenharmony_ci pair: dictionary; comprehensions 3017db96d56Sopenharmony_ci key, datum, key/datum pair 3027db96d56Sopenharmony_ci pair: object; dictionary 3037db96d56Sopenharmony_ci single: {} (curly brackets); dictionary expression 3047db96d56Sopenharmony_ci single: : (colon); in dictionary expressions 3057db96d56Sopenharmony_ci single: , (comma); in dictionary displays 3067db96d56Sopenharmony_ci 3077db96d56Sopenharmony_ciA dictionary display is a possibly empty series of key/datum pairs enclosed in 3087db96d56Sopenharmony_cicurly braces: 3097db96d56Sopenharmony_ci 3107db96d56Sopenharmony_ci.. productionlist:: python-grammar 3117db96d56Sopenharmony_ci dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}" 3127db96d56Sopenharmony_ci key_datum_list: `key_datum` ("," `key_datum`)* [","] 3137db96d56Sopenharmony_ci key_datum: `expression` ":" `expression` | "**" `or_expr` 3147db96d56Sopenharmony_ci dict_comprehension: `expression` ":" `expression` `comp_for` 3157db96d56Sopenharmony_ci 3167db96d56Sopenharmony_ciA dictionary display yields a new dictionary object. 3177db96d56Sopenharmony_ci 3187db96d56Sopenharmony_ciIf a comma-separated sequence of key/datum pairs is given, they are evaluated 3197db96d56Sopenharmony_cifrom left to right to define the entries of the dictionary: each key object is 3207db96d56Sopenharmony_ciused as a key into the dictionary to store the corresponding datum. This means 3217db96d56Sopenharmony_cithat you can specify the same key multiple times in the key/datum list, and the 3227db96d56Sopenharmony_cifinal dictionary's value for that key will be the last one given. 3237db96d56Sopenharmony_ci 3247db96d56Sopenharmony_ci.. index:: 3257db96d56Sopenharmony_ci unpacking; dictionary 3267db96d56Sopenharmony_ci single: **; in dictionary displays 3277db96d56Sopenharmony_ci 3287db96d56Sopenharmony_ciA double asterisk ``**`` denotes :dfn:`dictionary unpacking`. 3297db96d56Sopenharmony_ciIts operand must be a :term:`mapping`. Each mapping item is added 3307db96d56Sopenharmony_cito the new dictionary. Later values replace values already set by 3317db96d56Sopenharmony_ciearlier key/datum pairs and earlier dictionary unpackings. 3327db96d56Sopenharmony_ci 3337db96d56Sopenharmony_ci.. versionadded:: 3.5 3347db96d56Sopenharmony_ci Unpacking into dictionary displays, originally proposed by :pep:`448`. 3357db96d56Sopenharmony_ci 3367db96d56Sopenharmony_ciA dict comprehension, in contrast to list and set comprehensions, needs two 3377db96d56Sopenharmony_ciexpressions separated with a colon followed by the usual "for" and "if" clauses. 3387db96d56Sopenharmony_ciWhen the comprehension is run, the resulting key and value elements are inserted 3397db96d56Sopenharmony_ciin the new dictionary in the order they are produced. 3407db96d56Sopenharmony_ci 3417db96d56Sopenharmony_ci.. index:: pair: immutable; object 3427db96d56Sopenharmony_ci hashable 3437db96d56Sopenharmony_ci 3447db96d56Sopenharmony_ciRestrictions on the types of the key values are listed earlier in section 3457db96d56Sopenharmony_ci:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes 3467db96d56Sopenharmony_ciall mutable objects.) Clashes between duplicate keys are not detected; the last 3477db96d56Sopenharmony_cidatum (textually rightmost in the display) stored for a given key value 3487db96d56Sopenharmony_ciprevails. 3497db96d56Sopenharmony_ci 3507db96d56Sopenharmony_ci.. versionchanged:: 3.8 3517db96d56Sopenharmony_ci Prior to Python 3.8, in dict comprehensions, the evaluation order of key 3527db96d56Sopenharmony_ci and value was not well-defined. In CPython, the value was evaluated before 3537db96d56Sopenharmony_ci the key. Starting with 3.8, the key is evaluated before the value, as 3547db96d56Sopenharmony_ci proposed by :pep:`572`. 3557db96d56Sopenharmony_ci 3567db96d56Sopenharmony_ci 3577db96d56Sopenharmony_ci.. _genexpr: 3587db96d56Sopenharmony_ci 3597db96d56Sopenharmony_ciGenerator expressions 3607db96d56Sopenharmony_ci--------------------- 3617db96d56Sopenharmony_ci 3627db96d56Sopenharmony_ci.. index:: 3637db96d56Sopenharmony_ci pair: generator; expression 3647db96d56Sopenharmony_ci pair: object; generator 3657db96d56Sopenharmony_ci single: () (parentheses); generator expression 3667db96d56Sopenharmony_ci 3677db96d56Sopenharmony_ciA generator expression is a compact generator notation in parentheses: 3687db96d56Sopenharmony_ci 3697db96d56Sopenharmony_ci.. productionlist:: python-grammar 3707db96d56Sopenharmony_ci generator_expression: "(" `expression` `comp_for` ")" 3717db96d56Sopenharmony_ci 3727db96d56Sopenharmony_ciA generator expression yields a new generator object. Its syntax is the same as 3737db96d56Sopenharmony_cifor comprehensions, except that it is enclosed in parentheses instead of 3747db96d56Sopenharmony_cibrackets or curly braces. 3757db96d56Sopenharmony_ci 3767db96d56Sopenharmony_ciVariables used in the generator expression are evaluated lazily when the 3777db96d56Sopenharmony_ci:meth:`~generator.__next__` method is called for the generator object (in the same 3787db96d56Sopenharmony_cifashion as normal generators). However, the iterable expression in the 3797db96d56Sopenharmony_cileftmost :keyword:`!for` clause is immediately evaluated, so that an error 3807db96d56Sopenharmony_ciproduced by it will be emitted at the point where the generator expression 3817db96d56Sopenharmony_ciis defined, rather than at the point where the first value is retrieved. 3827db96d56Sopenharmony_ciSubsequent :keyword:`!for` clauses and any filter condition in the leftmost 3837db96d56Sopenharmony_ci:keyword:`!for` clause cannot be evaluated in the enclosing scope as they may 3847db96d56Sopenharmony_cidepend on the values obtained from the leftmost iterable. For example: 3857db96d56Sopenharmony_ci``(x*y for x in range(10) for y in range(x, x+10))``. 3867db96d56Sopenharmony_ci 3877db96d56Sopenharmony_ciThe parentheses can be omitted on calls with only one argument. See section 3887db96d56Sopenharmony_ci:ref:`calls` for details. 3897db96d56Sopenharmony_ci 3907db96d56Sopenharmony_ciTo avoid interfering with the expected operation of the generator expression 3917db96d56Sopenharmony_ciitself, ``yield`` and ``yield from`` expressions are prohibited in the 3927db96d56Sopenharmony_ciimplicitly defined generator. 3937db96d56Sopenharmony_ci 3947db96d56Sopenharmony_ciIf a generator expression contains either :keyword:`!async for` 3957db96d56Sopenharmony_ciclauses or :keyword:`await` expressions it is called an 3967db96d56Sopenharmony_ci:dfn:`asynchronous generator expression`. An asynchronous generator 3977db96d56Sopenharmony_ciexpression returns a new asynchronous generator object, 3987db96d56Sopenharmony_ciwhich is an asynchronous iterator (see :ref:`async-iterators`). 3997db96d56Sopenharmony_ci 4007db96d56Sopenharmony_ci.. versionadded:: 3.6 4017db96d56Sopenharmony_ci Asynchronous generator expressions were introduced. 4027db96d56Sopenharmony_ci 4037db96d56Sopenharmony_ci.. versionchanged:: 3.7 4047db96d56Sopenharmony_ci Prior to Python 3.7, asynchronous generator expressions could 4057db96d56Sopenharmony_ci only appear in :keyword:`async def` coroutines. Starting 4067db96d56Sopenharmony_ci with 3.7, any function can use asynchronous generator expressions. 4077db96d56Sopenharmony_ci 4087db96d56Sopenharmony_ci.. versionchanged:: 3.8 4097db96d56Sopenharmony_ci ``yield`` and ``yield from`` prohibited in the implicitly nested scope. 4107db96d56Sopenharmony_ci 4117db96d56Sopenharmony_ci 4127db96d56Sopenharmony_ci.. _yieldexpr: 4137db96d56Sopenharmony_ci 4147db96d56Sopenharmony_ciYield expressions 4157db96d56Sopenharmony_ci----------------- 4167db96d56Sopenharmony_ci 4177db96d56Sopenharmony_ci.. index:: 4187db96d56Sopenharmony_ci pair: keyword; yield 4197db96d56Sopenharmony_ci pair: keyword; from 4207db96d56Sopenharmony_ci pair: yield; expression 4217db96d56Sopenharmony_ci pair: generator; function 4227db96d56Sopenharmony_ci 4237db96d56Sopenharmony_ci.. productionlist:: python-grammar 4247db96d56Sopenharmony_ci yield_atom: "(" `yield_expression` ")" 4257db96d56Sopenharmony_ci yield_expression: "yield" [`expression_list` | "from" `expression`] 4267db96d56Sopenharmony_ci 4277db96d56Sopenharmony_ciThe yield expression is used when defining a :term:`generator` function 4287db96d56Sopenharmony_cior an :term:`asynchronous generator` function and 4297db96d56Sopenharmony_cithus can only be used in the body of a function definition. Using a yield 4307db96d56Sopenharmony_ciexpression in a function's body causes that function to be a generator function, 4317db96d56Sopenharmony_ciand using it in an :keyword:`async def` function's body causes that 4327db96d56Sopenharmony_cicoroutine function to be an asynchronous generator function. For example:: 4337db96d56Sopenharmony_ci 4347db96d56Sopenharmony_ci def gen(): # defines a generator function 4357db96d56Sopenharmony_ci yield 123 4367db96d56Sopenharmony_ci 4377db96d56Sopenharmony_ci async def agen(): # defines an asynchronous generator function 4387db96d56Sopenharmony_ci yield 123 4397db96d56Sopenharmony_ci 4407db96d56Sopenharmony_ciDue to their side effects on the containing scope, ``yield`` expressions 4417db96d56Sopenharmony_ciare not permitted as part of the implicitly defined scopes used to 4427db96d56Sopenharmony_ciimplement comprehensions and generator expressions. 4437db96d56Sopenharmony_ci 4447db96d56Sopenharmony_ci.. versionchanged:: 3.8 4457db96d56Sopenharmony_ci Yield expressions prohibited in the implicitly nested scopes used to 4467db96d56Sopenharmony_ci implement comprehensions and generator expressions. 4477db96d56Sopenharmony_ci 4487db96d56Sopenharmony_ciGenerator functions are described below, while asynchronous generator 4497db96d56Sopenharmony_cifunctions are described separately in section 4507db96d56Sopenharmony_ci:ref:`asynchronous-generator-functions`. 4517db96d56Sopenharmony_ci 4527db96d56Sopenharmony_ciWhen a generator function is called, it returns an iterator known as a 4537db96d56Sopenharmony_cigenerator. That generator then controls the execution of the generator 4547db96d56Sopenharmony_cifunction. The execution starts when one of the generator's methods is called. 4557db96d56Sopenharmony_ciAt that time, the execution proceeds to the first yield expression, where it is 4567db96d56Sopenharmony_cisuspended again, returning the value of :token:`~python-grammar:expression_list` 4577db96d56Sopenharmony_cito the generator's caller, 4587db96d56Sopenharmony_cior ``None`` if :token:`~python-grammar:expression_list` is omitted. 4597db96d56Sopenharmony_ciBy suspended, we mean that all local state is 4607db96d56Sopenharmony_ciretained, including the current bindings of local variables, the instruction 4617db96d56Sopenharmony_cipointer, the internal evaluation stack, and the state of any exception handling. 4627db96d56Sopenharmony_ciWhen the execution is resumed by calling one of the generator's methods, the 4637db96d56Sopenharmony_cifunction can proceed exactly as if the yield expression were just another 4647db96d56Sopenharmony_ciexternal call. The value of the yield expression after resuming depends on the 4657db96d56Sopenharmony_cimethod which resumed the execution. If :meth:`~generator.__next__` is used 4667db96d56Sopenharmony_ci(typically via either a :keyword:`for` or the :func:`next` builtin) then the 4677db96d56Sopenharmony_ciresult is :const:`None`. Otherwise, if :meth:`~generator.send` is used, then 4687db96d56Sopenharmony_cithe result will be the value passed in to that method. 4697db96d56Sopenharmony_ci 4707db96d56Sopenharmony_ci.. index:: single: coroutine 4717db96d56Sopenharmony_ci 4727db96d56Sopenharmony_ciAll of this makes generator functions quite similar to coroutines; they yield 4737db96d56Sopenharmony_cimultiple times, they have more than one entry point and their execution can be 4747db96d56Sopenharmony_cisuspended. The only difference is that a generator function cannot control 4757db96d56Sopenharmony_ciwhere the execution should continue after it yields; the control is always 4767db96d56Sopenharmony_citransferred to the generator's caller. 4777db96d56Sopenharmony_ci 4787db96d56Sopenharmony_ciYield expressions are allowed anywhere in a :keyword:`try` construct. If the 4797db96d56Sopenharmony_cigenerator is not resumed before it is 4807db96d56Sopenharmony_cifinalized (by reaching a zero reference count or by being garbage collected), 4817db96d56Sopenharmony_cithe generator-iterator's :meth:`~generator.close` method will be called, 4827db96d56Sopenharmony_ciallowing any pending :keyword:`finally` clauses to execute. 4837db96d56Sopenharmony_ci 4847db96d56Sopenharmony_ci.. index:: 4857db96d56Sopenharmony_ci single: from; yield from expression 4867db96d56Sopenharmony_ci 4877db96d56Sopenharmony_ciWhen ``yield from <expr>`` is used, the supplied expression must be an 4887db96d56Sopenharmony_ciiterable. The values produced by iterating that iterable are passed directly 4897db96d56Sopenharmony_cito the caller of the current generator's methods. Any values passed in with 4907db96d56Sopenharmony_ci:meth:`~generator.send` and any exceptions passed in with 4917db96d56Sopenharmony_ci:meth:`~generator.throw` are passed to the underlying iterator if it has the 4927db96d56Sopenharmony_ciappropriate methods. If this is not the case, then :meth:`~generator.send` 4937db96d56Sopenharmony_ciwill raise :exc:`AttributeError` or :exc:`TypeError`, while 4947db96d56Sopenharmony_ci:meth:`~generator.throw` will just raise the passed in exception immediately. 4957db96d56Sopenharmony_ci 4967db96d56Sopenharmony_ciWhen the underlying iterator is complete, the :attr:`~StopIteration.value` 4977db96d56Sopenharmony_ciattribute of the raised :exc:`StopIteration` instance becomes the value of 4987db96d56Sopenharmony_cithe yield expression. It can be either set explicitly when raising 4997db96d56Sopenharmony_ci:exc:`StopIteration`, or automatically when the subiterator is a generator 5007db96d56Sopenharmony_ci(by returning a value from the subgenerator). 5017db96d56Sopenharmony_ci 5027db96d56Sopenharmony_ci .. versionchanged:: 3.3 5037db96d56Sopenharmony_ci Added ``yield from <expr>`` to delegate control flow to a subiterator. 5047db96d56Sopenharmony_ci 5057db96d56Sopenharmony_ciThe parentheses may be omitted when the yield expression is the sole expression 5067db96d56Sopenharmony_cion the right hand side of an assignment statement. 5077db96d56Sopenharmony_ci 5087db96d56Sopenharmony_ci.. seealso:: 5097db96d56Sopenharmony_ci 5107db96d56Sopenharmony_ci :pep:`255` - Simple Generators 5117db96d56Sopenharmony_ci The proposal for adding generators and the :keyword:`yield` statement to Python. 5127db96d56Sopenharmony_ci 5137db96d56Sopenharmony_ci :pep:`342` - Coroutines via Enhanced Generators 5147db96d56Sopenharmony_ci The proposal to enhance the API and syntax of generators, making them 5157db96d56Sopenharmony_ci usable as simple coroutines. 5167db96d56Sopenharmony_ci 5177db96d56Sopenharmony_ci :pep:`380` - Syntax for Delegating to a Subgenerator 5187db96d56Sopenharmony_ci The proposal to introduce the :token:`~python-grammar:yield_from` syntax, 5197db96d56Sopenharmony_ci making delegation to subgenerators easy. 5207db96d56Sopenharmony_ci 5217db96d56Sopenharmony_ci :pep:`525` - Asynchronous Generators 5227db96d56Sopenharmony_ci The proposal that expanded on :pep:`492` by adding generator capabilities to 5237db96d56Sopenharmony_ci coroutine functions. 5247db96d56Sopenharmony_ci 5257db96d56Sopenharmony_ci.. index:: pair: object; generator 5267db96d56Sopenharmony_ci.. _generator-methods: 5277db96d56Sopenharmony_ci 5287db96d56Sopenharmony_ciGenerator-iterator methods 5297db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^ 5307db96d56Sopenharmony_ci 5317db96d56Sopenharmony_ciThis subsection describes the methods of a generator iterator. They can 5327db96d56Sopenharmony_cibe used to control the execution of a generator function. 5337db96d56Sopenharmony_ci 5347db96d56Sopenharmony_ciNote that calling any of the generator methods below when the generator 5357db96d56Sopenharmony_ciis already executing raises a :exc:`ValueError` exception. 5367db96d56Sopenharmony_ci 5377db96d56Sopenharmony_ci.. index:: pair: exception; StopIteration 5387db96d56Sopenharmony_ci 5397db96d56Sopenharmony_ci 5407db96d56Sopenharmony_ci.. method:: generator.__next__() 5417db96d56Sopenharmony_ci 5427db96d56Sopenharmony_ci Starts the execution of a generator function or resumes it at the last 5437db96d56Sopenharmony_ci executed yield expression. When a generator function is resumed with a 5447db96d56Sopenharmony_ci :meth:`~generator.__next__` method, the current yield expression always 5457db96d56Sopenharmony_ci evaluates to :const:`None`. The execution then continues to the next yield 5467db96d56Sopenharmony_ci expression, where the generator is suspended again, and the value of the 5477db96d56Sopenharmony_ci :token:`~python-grammar:expression_list` is returned to :meth:`__next__`'s 5487db96d56Sopenharmony_ci caller. If the generator exits without yielding another value, a 5497db96d56Sopenharmony_ci :exc:`StopIteration` exception is raised. 5507db96d56Sopenharmony_ci 5517db96d56Sopenharmony_ci This method is normally called implicitly, e.g. by a :keyword:`for` loop, or 5527db96d56Sopenharmony_ci by the built-in :func:`next` function. 5537db96d56Sopenharmony_ci 5547db96d56Sopenharmony_ci 5557db96d56Sopenharmony_ci.. method:: generator.send(value) 5567db96d56Sopenharmony_ci 5577db96d56Sopenharmony_ci Resumes the execution and "sends" a value into the generator function. The 5587db96d56Sopenharmony_ci *value* argument becomes the result of the current yield expression. The 5597db96d56Sopenharmony_ci :meth:`send` method returns the next value yielded by the generator, or 5607db96d56Sopenharmony_ci raises :exc:`StopIteration` if the generator exits without yielding another 5617db96d56Sopenharmony_ci value. When :meth:`send` is called to start the generator, it must be called 5627db96d56Sopenharmony_ci with :const:`None` as the argument, because there is no yield expression that 5637db96d56Sopenharmony_ci could receive the value. 5647db96d56Sopenharmony_ci 5657db96d56Sopenharmony_ci 5667db96d56Sopenharmony_ci.. method:: generator.throw(value) 5677db96d56Sopenharmony_ci generator.throw(type[, value[, traceback]]) 5687db96d56Sopenharmony_ci 5697db96d56Sopenharmony_ci Raises an exception at the point where the generator was paused, 5707db96d56Sopenharmony_ci and returns the next value yielded by the generator function. If the generator 5717db96d56Sopenharmony_ci exits without yielding another value, a :exc:`StopIteration` exception is 5727db96d56Sopenharmony_ci raised. If the generator function does not catch the passed-in exception, or 5737db96d56Sopenharmony_ci raises a different exception, then that exception propagates to the caller. 5747db96d56Sopenharmony_ci 5757db96d56Sopenharmony_ci In typical use, this is called with a single exception instance similar to the 5767db96d56Sopenharmony_ci way the :keyword:`raise` keyword is used. 5777db96d56Sopenharmony_ci 5787db96d56Sopenharmony_ci For backwards compatibility, however, the second signature is 5797db96d56Sopenharmony_ci supported, following a convention from older versions of Python. 5807db96d56Sopenharmony_ci The *type* argument should be an exception class, and *value* 5817db96d56Sopenharmony_ci should be an exception instance. If the *value* is not provided, the 5827db96d56Sopenharmony_ci *type* constructor is called to get an instance. If *traceback* 5837db96d56Sopenharmony_ci is provided, it is set on the exception, otherwise any existing 5847db96d56Sopenharmony_ci :attr:`~BaseException.__traceback__` attribute stored in *value* may 5857db96d56Sopenharmony_ci be cleared. 5867db96d56Sopenharmony_ci 5877db96d56Sopenharmony_ci.. index:: pair: exception; GeneratorExit 5887db96d56Sopenharmony_ci 5897db96d56Sopenharmony_ci 5907db96d56Sopenharmony_ci.. method:: generator.close() 5917db96d56Sopenharmony_ci 5927db96d56Sopenharmony_ci Raises a :exc:`GeneratorExit` at the point where the generator function was 5937db96d56Sopenharmony_ci paused. If the generator function then exits gracefully, is already closed, 5947db96d56Sopenharmony_ci or raises :exc:`GeneratorExit` (by not catching the exception), close 5957db96d56Sopenharmony_ci returns to its caller. If the generator yields a value, a 5967db96d56Sopenharmony_ci :exc:`RuntimeError` is raised. If the generator raises any other exception, 5977db96d56Sopenharmony_ci it is propagated to the caller. :meth:`close` does nothing if the generator 5987db96d56Sopenharmony_ci has already exited due to an exception or normal exit. 5997db96d56Sopenharmony_ci 6007db96d56Sopenharmony_ci.. index:: single: yield; examples 6017db96d56Sopenharmony_ci 6027db96d56Sopenharmony_ciExamples 6037db96d56Sopenharmony_ci^^^^^^^^ 6047db96d56Sopenharmony_ci 6057db96d56Sopenharmony_ciHere is a simple example that demonstrates the behavior of generators and 6067db96d56Sopenharmony_cigenerator functions:: 6077db96d56Sopenharmony_ci 6087db96d56Sopenharmony_ci >>> def echo(value=None): 6097db96d56Sopenharmony_ci ... print("Execution starts when 'next()' is called for the first time.") 6107db96d56Sopenharmony_ci ... try: 6117db96d56Sopenharmony_ci ... while True: 6127db96d56Sopenharmony_ci ... try: 6137db96d56Sopenharmony_ci ... value = (yield value) 6147db96d56Sopenharmony_ci ... except Exception as e: 6157db96d56Sopenharmony_ci ... value = e 6167db96d56Sopenharmony_ci ... finally: 6177db96d56Sopenharmony_ci ... print("Don't forget to clean up when 'close()' is called.") 6187db96d56Sopenharmony_ci ... 6197db96d56Sopenharmony_ci >>> generator = echo(1) 6207db96d56Sopenharmony_ci >>> print(next(generator)) 6217db96d56Sopenharmony_ci Execution starts when 'next()' is called for the first time. 6227db96d56Sopenharmony_ci 1 6237db96d56Sopenharmony_ci >>> print(next(generator)) 6247db96d56Sopenharmony_ci None 6257db96d56Sopenharmony_ci >>> print(generator.send(2)) 6267db96d56Sopenharmony_ci 2 6277db96d56Sopenharmony_ci >>> generator.throw(TypeError, "spam") 6287db96d56Sopenharmony_ci TypeError('spam',) 6297db96d56Sopenharmony_ci >>> generator.close() 6307db96d56Sopenharmony_ci Don't forget to clean up when 'close()' is called. 6317db96d56Sopenharmony_ci 6327db96d56Sopenharmony_ciFor examples using ``yield from``, see :ref:`pep-380` in "What's New in 6337db96d56Sopenharmony_ciPython." 6347db96d56Sopenharmony_ci 6357db96d56Sopenharmony_ci.. _asynchronous-generator-functions: 6367db96d56Sopenharmony_ci 6377db96d56Sopenharmony_ciAsynchronous generator functions 6387db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6397db96d56Sopenharmony_ci 6407db96d56Sopenharmony_ciThe presence of a yield expression in a function or method defined using 6417db96d56Sopenharmony_ci:keyword:`async def` further defines the function as an 6427db96d56Sopenharmony_ci:term:`asynchronous generator` function. 6437db96d56Sopenharmony_ci 6447db96d56Sopenharmony_ciWhen an asynchronous generator function is called, it returns an 6457db96d56Sopenharmony_ciasynchronous iterator known as an asynchronous generator object. 6467db96d56Sopenharmony_ciThat object then controls the execution of the generator function. 6477db96d56Sopenharmony_ciAn asynchronous generator object is typically used in an 6487db96d56Sopenharmony_ci:keyword:`async for` statement in a coroutine function analogously to 6497db96d56Sopenharmony_cihow a generator object would be used in a :keyword:`for` statement. 6507db96d56Sopenharmony_ci 6517db96d56Sopenharmony_ciCalling one of the asynchronous generator's methods returns an :term:`awaitable` 6527db96d56Sopenharmony_ciobject, and the execution starts when this object is awaited on. At that time, 6537db96d56Sopenharmony_cithe execution proceeds to the first yield expression, where it is suspended 6547db96d56Sopenharmony_ciagain, returning the value of :token:`~python-grammar:expression_list` to the 6557db96d56Sopenharmony_ciawaiting coroutine. As with a generator, suspension means that all local state 6567db96d56Sopenharmony_ciis retained, including the current bindings of local variables, the instruction 6577db96d56Sopenharmony_cipointer, the internal evaluation stack, and the state of any exception handling. 6587db96d56Sopenharmony_ciWhen the execution is resumed by awaiting on the next object returned by the 6597db96d56Sopenharmony_ciasynchronous generator's methods, the function can proceed exactly as if the 6607db96d56Sopenharmony_ciyield expression were just another external call. The value of the yield 6617db96d56Sopenharmony_ciexpression after resuming depends on the method which resumed the execution. If 6627db96d56Sopenharmony_ci:meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if 6637db96d56Sopenharmony_ci:meth:`~agen.asend` is used, then the result will be the value passed in to that 6647db96d56Sopenharmony_cimethod. 6657db96d56Sopenharmony_ci 6667db96d56Sopenharmony_ciIf an asynchronous generator happens to exit early by :keyword:`break`, the caller 6677db96d56Sopenharmony_citask being cancelled, or other exceptions, the generator's async cleanup code 6687db96d56Sopenharmony_ciwill run and possibly raise exceptions or access context variables in an 6697db96d56Sopenharmony_ciunexpected context--perhaps after the lifetime of tasks it depends, or 6707db96d56Sopenharmony_ciduring the event loop shutdown when the async-generator garbage collection hook 6717db96d56Sopenharmony_ciis called. 6727db96d56Sopenharmony_ciTo prevent this, the caller must explicitly close the async generator by calling 6737db96d56Sopenharmony_ci:meth:`~agen.aclose` method to finalize the generator and ultimately detach it 6747db96d56Sopenharmony_cifrom the event loop. 6757db96d56Sopenharmony_ci 6767db96d56Sopenharmony_ciIn an asynchronous generator function, yield expressions are allowed anywhere 6777db96d56Sopenharmony_ciin a :keyword:`try` construct. However, if an asynchronous generator is not 6787db96d56Sopenharmony_ciresumed before it is finalized (by reaching a zero reference count or by 6797db96d56Sopenharmony_cibeing garbage collected), then a yield expression within a :keyword:`!try` 6807db96d56Sopenharmony_ciconstruct could result in a failure to execute pending :keyword:`finally` 6817db96d56Sopenharmony_ciclauses. In this case, it is the responsibility of the event loop or 6827db96d56Sopenharmony_cischeduler running the asynchronous generator to call the asynchronous 6837db96d56Sopenharmony_cigenerator-iterator's :meth:`~agen.aclose` method and run the resulting 6847db96d56Sopenharmony_cicoroutine object, thus allowing any pending :keyword:`!finally` clauses 6857db96d56Sopenharmony_cito execute. 6867db96d56Sopenharmony_ci 6877db96d56Sopenharmony_ciTo take care of finalization upon event loop termination, an event loop should 6887db96d56Sopenharmony_cidefine a *finalizer* function which takes an asynchronous generator-iterator and 6897db96d56Sopenharmony_cipresumably calls :meth:`~agen.aclose` and executes the coroutine. 6907db96d56Sopenharmony_ciThis *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. 6917db96d56Sopenharmony_ciWhen first iterated over, an asynchronous generator-iterator will store the 6927db96d56Sopenharmony_ciregistered *finalizer* to be called upon finalization. For a reference example 6937db96d56Sopenharmony_ciof a *finalizer* method see the implementation of 6947db96d56Sopenharmony_ci``asyncio.Loop.shutdown_asyncgens`` in :source:`Lib/asyncio/base_events.py`. 6957db96d56Sopenharmony_ci 6967db96d56Sopenharmony_ciThe expression ``yield from <expr>`` is a syntax error when used in an 6977db96d56Sopenharmony_ciasynchronous generator function. 6987db96d56Sopenharmony_ci 6997db96d56Sopenharmony_ci.. index:: pair: object; asynchronous-generator 7007db96d56Sopenharmony_ci.. _asynchronous-generator-methods: 7017db96d56Sopenharmony_ci 7027db96d56Sopenharmony_ciAsynchronous generator-iterator methods 7037db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 7047db96d56Sopenharmony_ci 7057db96d56Sopenharmony_ciThis subsection describes the methods of an asynchronous generator iterator, 7067db96d56Sopenharmony_ciwhich are used to control the execution of a generator function. 7077db96d56Sopenharmony_ci 7087db96d56Sopenharmony_ci 7097db96d56Sopenharmony_ci.. index:: pair: exception; StopAsyncIteration 7107db96d56Sopenharmony_ci 7117db96d56Sopenharmony_ci.. coroutinemethod:: agen.__anext__() 7127db96d56Sopenharmony_ci 7137db96d56Sopenharmony_ci Returns an awaitable which when run starts to execute the asynchronous 7147db96d56Sopenharmony_ci generator or resumes it at the last executed yield expression. When an 7157db96d56Sopenharmony_ci asynchronous generator function is resumed with an :meth:`~agen.__anext__` 7167db96d56Sopenharmony_ci method, the current yield expression always evaluates to :const:`None` in the 7177db96d56Sopenharmony_ci returned awaitable, which when run will continue to the next yield 7187db96d56Sopenharmony_ci expression. The value of the :token:`~python-grammar:expression_list` of the 7197db96d56Sopenharmony_ci yield expression is the value of the :exc:`StopIteration` exception raised by 7207db96d56Sopenharmony_ci the completing coroutine. If the asynchronous generator exits without 7217db96d56Sopenharmony_ci yielding another value, the awaitable instead raises a 7227db96d56Sopenharmony_ci :exc:`StopAsyncIteration` exception, signalling that the asynchronous 7237db96d56Sopenharmony_ci iteration has completed. 7247db96d56Sopenharmony_ci 7257db96d56Sopenharmony_ci This method is normally called implicitly by a :keyword:`async for` loop. 7267db96d56Sopenharmony_ci 7277db96d56Sopenharmony_ci 7287db96d56Sopenharmony_ci.. coroutinemethod:: agen.asend(value) 7297db96d56Sopenharmony_ci 7307db96d56Sopenharmony_ci Returns an awaitable which when run resumes the execution of the 7317db96d56Sopenharmony_ci asynchronous generator. As with the :meth:`~generator.send()` method for a 7327db96d56Sopenharmony_ci generator, this "sends" a value into the asynchronous generator function, 7337db96d56Sopenharmony_ci and the *value* argument becomes the result of the current yield expression. 7347db96d56Sopenharmony_ci The awaitable returned by the :meth:`asend` method will return the next 7357db96d56Sopenharmony_ci value yielded by the generator as the value of the raised 7367db96d56Sopenharmony_ci :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the 7377db96d56Sopenharmony_ci asynchronous generator exits without yielding another value. When 7387db96d56Sopenharmony_ci :meth:`asend` is called to start the asynchronous 7397db96d56Sopenharmony_ci generator, it must be called with :const:`None` as the argument, 7407db96d56Sopenharmony_ci because there is no yield expression that could receive the value. 7417db96d56Sopenharmony_ci 7427db96d56Sopenharmony_ci 7437db96d56Sopenharmony_ci.. coroutinemethod:: agen.athrow(type[, value[, traceback]]) 7447db96d56Sopenharmony_ci 7457db96d56Sopenharmony_ci Returns an awaitable that raises an exception of type ``type`` at the point 7467db96d56Sopenharmony_ci where the asynchronous generator was paused, and returns the next value 7477db96d56Sopenharmony_ci yielded by the generator function as the value of the raised 7487db96d56Sopenharmony_ci :exc:`StopIteration` exception. If the asynchronous generator exits 7497db96d56Sopenharmony_ci without yielding another value, a :exc:`StopAsyncIteration` exception is 7507db96d56Sopenharmony_ci raised by the awaitable. 7517db96d56Sopenharmony_ci If the generator function does not catch the passed-in exception, or 7527db96d56Sopenharmony_ci raises a different exception, then when the awaitable is run that exception 7537db96d56Sopenharmony_ci propagates to the caller of the awaitable. 7547db96d56Sopenharmony_ci 7557db96d56Sopenharmony_ci.. index:: pair: exception; GeneratorExit 7567db96d56Sopenharmony_ci 7577db96d56Sopenharmony_ci 7587db96d56Sopenharmony_ci.. coroutinemethod:: agen.aclose() 7597db96d56Sopenharmony_ci 7607db96d56Sopenharmony_ci Returns an awaitable that when run will throw a :exc:`GeneratorExit` into 7617db96d56Sopenharmony_ci the asynchronous generator function at the point where it was paused. 7627db96d56Sopenharmony_ci If the asynchronous generator function then exits gracefully, is already 7637db96d56Sopenharmony_ci closed, or raises :exc:`GeneratorExit` (by not catching the exception), 7647db96d56Sopenharmony_ci then the returned awaitable will raise a :exc:`StopIteration` exception. 7657db96d56Sopenharmony_ci Any further awaitables returned by subsequent calls to the asynchronous 7667db96d56Sopenharmony_ci generator will raise a :exc:`StopAsyncIteration` exception. If the 7677db96d56Sopenharmony_ci asynchronous generator yields a value, a :exc:`RuntimeError` is raised 7687db96d56Sopenharmony_ci by the awaitable. If the asynchronous generator raises any other exception, 7697db96d56Sopenharmony_ci it is propagated to the caller of the awaitable. If the asynchronous 7707db96d56Sopenharmony_ci generator has already exited due to an exception or normal exit, then 7717db96d56Sopenharmony_ci further calls to :meth:`aclose` will return an awaitable that does nothing. 7727db96d56Sopenharmony_ci 7737db96d56Sopenharmony_ci.. _primaries: 7747db96d56Sopenharmony_ci 7757db96d56Sopenharmony_ciPrimaries 7767db96d56Sopenharmony_ci========= 7777db96d56Sopenharmony_ci 7787db96d56Sopenharmony_ci.. index:: single: primary 7797db96d56Sopenharmony_ci 7807db96d56Sopenharmony_ciPrimaries represent the most tightly bound operations of the language. Their 7817db96d56Sopenharmony_cisyntax is: 7827db96d56Sopenharmony_ci 7837db96d56Sopenharmony_ci.. productionlist:: python-grammar 7847db96d56Sopenharmony_ci primary: `atom` | `attributeref` | `subscription` | `slicing` | `call` 7857db96d56Sopenharmony_ci 7867db96d56Sopenharmony_ci 7877db96d56Sopenharmony_ci.. _attribute-references: 7887db96d56Sopenharmony_ci 7897db96d56Sopenharmony_ciAttribute references 7907db96d56Sopenharmony_ci-------------------- 7917db96d56Sopenharmony_ci 7927db96d56Sopenharmony_ci.. index:: 7937db96d56Sopenharmony_ci pair: attribute; reference 7947db96d56Sopenharmony_ci single: . (dot); attribute reference 7957db96d56Sopenharmony_ci 7967db96d56Sopenharmony_ciAn attribute reference is a primary followed by a period and a name: 7977db96d56Sopenharmony_ci 7987db96d56Sopenharmony_ci.. productionlist:: python-grammar 7997db96d56Sopenharmony_ci attributeref: `primary` "." `identifier` 8007db96d56Sopenharmony_ci 8017db96d56Sopenharmony_ci.. index:: 8027db96d56Sopenharmony_ci pair: exception; AttributeError 8037db96d56Sopenharmony_ci pair: object; module 8047db96d56Sopenharmony_ci pair: object; list 8057db96d56Sopenharmony_ci 8067db96d56Sopenharmony_ciThe primary must evaluate to an object of a type that supports attribute 8077db96d56Sopenharmony_cireferences, which most objects do. This object is then asked to produce the 8087db96d56Sopenharmony_ciattribute whose name is the identifier. This production can be customized by 8097db96d56Sopenharmony_cioverriding the :meth:`__getattr__` method. If this attribute is not available, 8107db96d56Sopenharmony_cithe exception :exc:`AttributeError` is raised. Otherwise, the type and value of 8117db96d56Sopenharmony_cithe object produced is determined by the object. Multiple evaluations of the 8127db96d56Sopenharmony_cisame attribute reference may yield different objects. 8137db96d56Sopenharmony_ci 8147db96d56Sopenharmony_ci 8157db96d56Sopenharmony_ci.. _subscriptions: 8167db96d56Sopenharmony_ci 8177db96d56Sopenharmony_ciSubscriptions 8187db96d56Sopenharmony_ci------------- 8197db96d56Sopenharmony_ci 8207db96d56Sopenharmony_ci.. index:: 8217db96d56Sopenharmony_ci single: subscription 8227db96d56Sopenharmony_ci single: [] (square brackets); subscription 8237db96d56Sopenharmony_ci 8247db96d56Sopenharmony_ci.. index:: 8257db96d56Sopenharmony_ci pair: object; sequence 8267db96d56Sopenharmony_ci pair: object; mapping 8277db96d56Sopenharmony_ci pair: object; string 8287db96d56Sopenharmony_ci pair: object; tuple 8297db96d56Sopenharmony_ci pair: object; list 8307db96d56Sopenharmony_ci pair: object; dictionary 8317db96d56Sopenharmony_ci pair: sequence; item 8327db96d56Sopenharmony_ci 8337db96d56Sopenharmony_ciThe subscription of an instance of a :ref:`container class <sequence-types>` 8347db96d56Sopenharmony_ciwill generally select an element from the container. The subscription of a 8357db96d56Sopenharmony_ci:term:`generic class <generic type>` will generally return a 8367db96d56Sopenharmony_ci:ref:`GenericAlias <types-genericalias>` object. 8377db96d56Sopenharmony_ci 8387db96d56Sopenharmony_ci.. productionlist:: python-grammar 8397db96d56Sopenharmony_ci subscription: `primary` "[" `expression_list` "]" 8407db96d56Sopenharmony_ci 8417db96d56Sopenharmony_ciWhen an object is subscripted, the interpreter will evaluate the primary and 8427db96d56Sopenharmony_cithe expression list. 8437db96d56Sopenharmony_ci 8447db96d56Sopenharmony_ciThe primary must evaluate to an object that supports subscription. An object 8457db96d56Sopenharmony_cimay support subscription through defining one or both of 8467db96d56Sopenharmony_ci:meth:`~object.__getitem__` and :meth:`~object.__class_getitem__`. When the 8477db96d56Sopenharmony_ciprimary is subscripted, the evaluated result of the expression list will be 8487db96d56Sopenharmony_cipassed to one of these methods. For more details on when ``__class_getitem__`` 8497db96d56Sopenharmony_ciis called instead of ``__getitem__``, see :ref:`classgetitem-versus-getitem`. 8507db96d56Sopenharmony_ci 8517db96d56Sopenharmony_ciIf the expression list contains at least one comma, it will evaluate to a 8527db96d56Sopenharmony_ci:class:`tuple` containing the items of the expression list. Otherwise, the 8537db96d56Sopenharmony_ciexpression list will evaluate to the value of the list's sole member. 8547db96d56Sopenharmony_ci 8557db96d56Sopenharmony_ciFor built-in objects, there are two types of objects that support subscription 8567db96d56Sopenharmony_civia :meth:`~object.__getitem__`: 8577db96d56Sopenharmony_ci 8587db96d56Sopenharmony_ci1. Mappings. If the primary is a :term:`mapping`, the expression list must 8597db96d56Sopenharmony_ci evaluate to an object whose value is one of the keys of the mapping, and the 8607db96d56Sopenharmony_ci subscription selects the value in the mapping that corresponds to that key. 8617db96d56Sopenharmony_ci An example of a builtin mapping class is the :class:`dict` class. 8627db96d56Sopenharmony_ci2. Sequences. If the primary is a :term:`sequence`, the expression list must 8637db96d56Sopenharmony_ci evaluate to an :class:`int` or a :class:`slice` (as discussed in the 8647db96d56Sopenharmony_ci following section). Examples of builtin sequence classes include the 8657db96d56Sopenharmony_ci :class:`str`, :class:`list` and :class:`tuple` classes. 8667db96d56Sopenharmony_ci 8677db96d56Sopenharmony_ciThe formal syntax makes no special provision for negative indices in 8687db96d56Sopenharmony_ci:term:`sequences <sequence>`. However, built-in sequences all provide a :meth:`~object.__getitem__` 8697db96d56Sopenharmony_cimethod that interprets negative indices by adding the length of the sequence 8707db96d56Sopenharmony_cito the index so that, for example, ``x[-1]`` selects the last item of ``x``. The 8717db96d56Sopenharmony_ciresulting value must be a nonnegative integer less than the number of items in 8727db96d56Sopenharmony_cithe sequence, and the subscription selects the item whose index is that value 8737db96d56Sopenharmony_ci(counting from zero). Since the support for negative indices and slicing 8747db96d56Sopenharmony_cioccurs in the object's :meth:`__getitem__` method, subclasses overriding 8757db96d56Sopenharmony_cithis method will need to explicitly add that support. 8767db96d56Sopenharmony_ci 8777db96d56Sopenharmony_ci.. index:: 8787db96d56Sopenharmony_ci single: character 8797db96d56Sopenharmony_ci pair: string; item 8807db96d56Sopenharmony_ci 8817db96d56Sopenharmony_ciA :class:`string <str>` is a special kind of sequence whose items are 8827db96d56Sopenharmony_ci*characters*. A character is not a separate data type but a 8837db96d56Sopenharmony_cistring of exactly one character. 8847db96d56Sopenharmony_ci 8857db96d56Sopenharmony_ci 8867db96d56Sopenharmony_ci.. _slicings: 8877db96d56Sopenharmony_ci 8887db96d56Sopenharmony_ciSlicings 8897db96d56Sopenharmony_ci-------- 8907db96d56Sopenharmony_ci 8917db96d56Sopenharmony_ci.. index:: 8927db96d56Sopenharmony_ci single: slicing 8937db96d56Sopenharmony_ci single: slice 8947db96d56Sopenharmony_ci single: : (colon); slicing 8957db96d56Sopenharmony_ci single: , (comma); slicing 8967db96d56Sopenharmony_ci 8977db96d56Sopenharmony_ci.. index:: 8987db96d56Sopenharmony_ci pair: object; sequence 8997db96d56Sopenharmony_ci pair: object; string 9007db96d56Sopenharmony_ci pair: object; tuple 9017db96d56Sopenharmony_ci pair: object; list 9027db96d56Sopenharmony_ci 9037db96d56Sopenharmony_ciA slicing selects a range of items in a sequence object (e.g., a string, tuple 9047db96d56Sopenharmony_cior list). Slicings may be used as expressions or as targets in assignment or 9057db96d56Sopenharmony_ci:keyword:`del` statements. The syntax for a slicing: 9067db96d56Sopenharmony_ci 9077db96d56Sopenharmony_ci.. productionlist:: python-grammar 9087db96d56Sopenharmony_ci slicing: `primary` "[" `slice_list` "]" 9097db96d56Sopenharmony_ci slice_list: `slice_item` ("," `slice_item`)* [","] 9107db96d56Sopenharmony_ci slice_item: `expression` | `proper_slice` 9117db96d56Sopenharmony_ci proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] 9127db96d56Sopenharmony_ci lower_bound: `expression` 9137db96d56Sopenharmony_ci upper_bound: `expression` 9147db96d56Sopenharmony_ci stride: `expression` 9157db96d56Sopenharmony_ci 9167db96d56Sopenharmony_ciThere is ambiguity in the formal syntax here: anything that looks like an 9177db96d56Sopenharmony_ciexpression list also looks like a slice list, so any subscription can be 9187db96d56Sopenharmony_ciinterpreted as a slicing. Rather than further complicating the syntax, this is 9197db96d56Sopenharmony_cidisambiguated by defining that in this case the interpretation as a subscription 9207db96d56Sopenharmony_citakes priority over the interpretation as a slicing (this is the case if the 9217db96d56Sopenharmony_cislice list contains no proper slice). 9227db96d56Sopenharmony_ci 9237db96d56Sopenharmony_ci.. index:: 9247db96d56Sopenharmony_ci single: start (slice object attribute) 9257db96d56Sopenharmony_ci single: stop (slice object attribute) 9267db96d56Sopenharmony_ci single: step (slice object attribute) 9277db96d56Sopenharmony_ci 9287db96d56Sopenharmony_ciThe semantics for a slicing are as follows. The primary is indexed (using the 9297db96d56Sopenharmony_cisame :meth:`__getitem__` method as 9307db96d56Sopenharmony_cinormal subscription) with a key that is constructed from the slice list, as 9317db96d56Sopenharmony_cifollows. If the slice list contains at least one comma, the key is a tuple 9327db96d56Sopenharmony_cicontaining the conversion of the slice items; otherwise, the conversion of the 9337db96d56Sopenharmony_cilone slice item is the key. The conversion of a slice item that is an 9347db96d56Sopenharmony_ciexpression is that expression. The conversion of a proper slice is a slice 9357db96d56Sopenharmony_ciobject (see section :ref:`types`) whose :attr:`~slice.start`, 9367db96d56Sopenharmony_ci:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the 9377db96d56Sopenharmony_ciexpressions given as lower bound, upper bound and stride, respectively, 9387db96d56Sopenharmony_cisubstituting ``None`` for missing expressions. 9397db96d56Sopenharmony_ci 9407db96d56Sopenharmony_ci 9417db96d56Sopenharmony_ci.. index:: 9427db96d56Sopenharmony_ci pair: object; callable 9437db96d56Sopenharmony_ci single: call 9447db96d56Sopenharmony_ci single: argument; call semantics 9457db96d56Sopenharmony_ci single: () (parentheses); call 9467db96d56Sopenharmony_ci single: , (comma); argument list 9477db96d56Sopenharmony_ci single: = (equals); in function calls 9487db96d56Sopenharmony_ci 9497db96d56Sopenharmony_ci.. _calls: 9507db96d56Sopenharmony_ci 9517db96d56Sopenharmony_ciCalls 9527db96d56Sopenharmony_ci----- 9537db96d56Sopenharmony_ci 9547db96d56Sopenharmony_ciA call calls a callable object (e.g., a :term:`function`) with a possibly empty 9557db96d56Sopenharmony_ciseries of :term:`arguments <argument>`: 9567db96d56Sopenharmony_ci 9577db96d56Sopenharmony_ci.. productionlist:: python-grammar 9587db96d56Sopenharmony_ci call: `primary` "(" [`argument_list` [","] | `comprehension`] ")" 9597db96d56Sopenharmony_ci argument_list: `positional_arguments` ["," `starred_and_keywords`] 9607db96d56Sopenharmony_ci : ["," `keywords_arguments`] 9617db96d56Sopenharmony_ci : | `starred_and_keywords` ["," `keywords_arguments`] 9627db96d56Sopenharmony_ci : | `keywords_arguments` 9637db96d56Sopenharmony_ci positional_arguments: positional_item ("," positional_item)* 9647db96d56Sopenharmony_ci positional_item: `assignment_expression` | "*" `expression` 9657db96d56Sopenharmony_ci starred_and_keywords: ("*" `expression` | `keyword_item`) 9667db96d56Sopenharmony_ci : ("," "*" `expression` | "," `keyword_item`)* 9677db96d56Sopenharmony_ci keywords_arguments: (`keyword_item` | "**" `expression`) 9687db96d56Sopenharmony_ci : ("," `keyword_item` | "," "**" `expression`)* 9697db96d56Sopenharmony_ci keyword_item: `identifier` "=" `expression` 9707db96d56Sopenharmony_ci 9717db96d56Sopenharmony_ciAn optional trailing comma may be present after the positional and keyword arguments 9727db96d56Sopenharmony_cibut does not affect the semantics. 9737db96d56Sopenharmony_ci 9747db96d56Sopenharmony_ci.. index:: 9757db96d56Sopenharmony_ci single: parameter; call semantics 9767db96d56Sopenharmony_ci 9777db96d56Sopenharmony_ciThe primary must evaluate to a callable object (user-defined functions, built-in 9787db96d56Sopenharmony_cifunctions, methods of built-in objects, class objects, methods of class 9797db96d56Sopenharmony_ciinstances, and all objects having a :meth:`__call__` method are callable). All 9807db96d56Sopenharmony_ciargument expressions are evaluated before the call is attempted. Please refer 9817db96d56Sopenharmony_cito section :ref:`function` for the syntax of formal :term:`parameter` lists. 9827db96d56Sopenharmony_ci 9837db96d56Sopenharmony_ci.. XXX update with kwonly args PEP 9847db96d56Sopenharmony_ci 9857db96d56Sopenharmony_ciIf keyword arguments are present, they are first converted to positional 9867db96d56Sopenharmony_ciarguments, as follows. First, a list of unfilled slots is created for the 9877db96d56Sopenharmony_ciformal parameters. If there are N positional arguments, they are placed in the 9887db96d56Sopenharmony_cifirst N slots. Next, for each keyword argument, the identifier is used to 9897db96d56Sopenharmony_cidetermine the corresponding slot (if the identifier is the same as the first 9907db96d56Sopenharmony_ciformal parameter name, the first slot is used, and so on). If the slot is 9917db96d56Sopenharmony_cialready filled, a :exc:`TypeError` exception is raised. Otherwise, the 9927db96d56Sopenharmony_ciargument is placed in the slot, filling it (even if the expression is 9937db96d56Sopenharmony_ci``None``, it fills the slot). When all arguments have been processed, the slots 9947db96d56Sopenharmony_cithat are still unfilled are filled with the corresponding default value from the 9957db96d56Sopenharmony_cifunction definition. (Default values are calculated, once, when the function is 9967db96d56Sopenharmony_cidefined; thus, a mutable object such as a list or dictionary used as default 9977db96d56Sopenharmony_civalue will be shared by all calls that don't specify an argument value for the 9987db96d56Sopenharmony_cicorresponding slot; this should usually be avoided.) If there are any unfilled 9997db96d56Sopenharmony_cislots for which no default value is specified, a :exc:`TypeError` exception is 10007db96d56Sopenharmony_ciraised. Otherwise, the list of filled slots is used as the argument list for 10017db96d56Sopenharmony_cithe call. 10027db96d56Sopenharmony_ci 10037db96d56Sopenharmony_ci.. impl-detail:: 10047db96d56Sopenharmony_ci 10057db96d56Sopenharmony_ci An implementation may provide built-in functions whose positional parameters 10067db96d56Sopenharmony_ci do not have names, even if they are 'named' for the purpose of documentation, 10077db96d56Sopenharmony_ci and which therefore cannot be supplied by keyword. In CPython, this is the 10087db96d56Sopenharmony_ci case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to 10097db96d56Sopenharmony_ci parse their arguments. 10107db96d56Sopenharmony_ci 10117db96d56Sopenharmony_ciIf there are more positional arguments than there are formal parameter slots, a 10127db96d56Sopenharmony_ci:exc:`TypeError` exception is raised, unless a formal parameter using the syntax 10137db96d56Sopenharmony_ci``*identifier`` is present; in this case, that formal parameter receives a tuple 10147db96d56Sopenharmony_cicontaining the excess positional arguments (or an empty tuple if there were no 10157db96d56Sopenharmony_ciexcess positional arguments). 10167db96d56Sopenharmony_ci 10177db96d56Sopenharmony_ciIf any keyword argument does not correspond to a formal parameter name, a 10187db96d56Sopenharmony_ci:exc:`TypeError` exception is raised, unless a formal parameter using the syntax 10197db96d56Sopenharmony_ci``**identifier`` is present; in this case, that formal parameter receives a 10207db96d56Sopenharmony_cidictionary containing the excess keyword arguments (using the keywords as keys 10217db96d56Sopenharmony_ciand the argument values as corresponding values), or a (new) empty dictionary if 10227db96d56Sopenharmony_cithere were no excess keyword arguments. 10237db96d56Sopenharmony_ci 10247db96d56Sopenharmony_ci.. index:: 10257db96d56Sopenharmony_ci single: * (asterisk); in function calls 10267db96d56Sopenharmony_ci single: unpacking; in function calls 10277db96d56Sopenharmony_ci 10287db96d56Sopenharmony_ciIf the syntax ``*expression`` appears in the function call, ``expression`` must 10297db96d56Sopenharmony_cievaluate to an :term:`iterable`. Elements from these iterables are 10307db96d56Sopenharmony_citreated as if they were additional positional arguments. For the call 10317db96d56Sopenharmony_ci``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*, 10327db96d56Sopenharmony_cithis is equivalent to a call with M+4 positional arguments *x1*, *x2*, 10337db96d56Sopenharmony_ci*y1*, ..., *yM*, *x3*, *x4*. 10347db96d56Sopenharmony_ci 10357db96d56Sopenharmony_ciA consequence of this is that although the ``*expression`` syntax may appear 10367db96d56Sopenharmony_ci*after* explicit keyword arguments, it is processed *before* the 10377db96d56Sopenharmony_cikeyword arguments (and any ``**expression`` arguments -- see below). So:: 10387db96d56Sopenharmony_ci 10397db96d56Sopenharmony_ci >>> def f(a, b): 10407db96d56Sopenharmony_ci ... print(a, b) 10417db96d56Sopenharmony_ci ... 10427db96d56Sopenharmony_ci >>> f(b=1, *(2,)) 10437db96d56Sopenharmony_ci 2 1 10447db96d56Sopenharmony_ci >>> f(a=1, *(2,)) 10457db96d56Sopenharmony_ci Traceback (most recent call last): 10467db96d56Sopenharmony_ci File "<stdin>", line 1, in <module> 10477db96d56Sopenharmony_ci TypeError: f() got multiple values for keyword argument 'a' 10487db96d56Sopenharmony_ci >>> f(1, *(2,)) 10497db96d56Sopenharmony_ci 1 2 10507db96d56Sopenharmony_ci 10517db96d56Sopenharmony_ciIt is unusual for both keyword arguments and the ``*expression`` syntax to be 10527db96d56Sopenharmony_ciused in the same call, so in practice this confusion does not often arise. 10537db96d56Sopenharmony_ci 10547db96d56Sopenharmony_ci.. index:: 10557db96d56Sopenharmony_ci single: **; in function calls 10567db96d56Sopenharmony_ci 10577db96d56Sopenharmony_ciIf the syntax ``**expression`` appears in the function call, ``expression`` must 10587db96d56Sopenharmony_cievaluate to a :term:`mapping`, the contents of which are treated as 10597db96d56Sopenharmony_ciadditional keyword arguments. If a parameter matching a key has already been 10607db96d56Sopenharmony_cigiven a value (by an explicit keyword argument, or from another unpacking), 10617db96d56Sopenharmony_cia :exc:`TypeError` exception is raised. 10627db96d56Sopenharmony_ci 10637db96d56Sopenharmony_ciWhen ``**expression`` is used, each key in this mapping must be 10647db96d56Sopenharmony_cia string. 10657db96d56Sopenharmony_ciEach value from the mapping is assigned to the first formal parameter 10667db96d56Sopenharmony_cieligible for keyword assignment whose name is equal to the key. 10677db96d56Sopenharmony_ciA key need not be a Python identifier (e.g. ``"max-temp °F"`` is acceptable, 10687db96d56Sopenharmony_cialthough it will not match any formal parameter that could be declared). 10697db96d56Sopenharmony_ciIf there is no match to a formal parameter 10707db96d56Sopenharmony_cithe key-value pair is collected by the ``**`` parameter, if there is one, 10717db96d56Sopenharmony_cior if there is not, a :exc:`TypeError` exception is raised. 10727db96d56Sopenharmony_ci 10737db96d56Sopenharmony_ciFormal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be 10747db96d56Sopenharmony_ciused as positional argument slots or as keyword argument names. 10757db96d56Sopenharmony_ci 10767db96d56Sopenharmony_ci.. versionchanged:: 3.5 10777db96d56Sopenharmony_ci Function calls accept any number of ``*`` and ``**`` unpackings, 10787db96d56Sopenharmony_ci positional arguments may follow iterable unpackings (``*``), 10797db96d56Sopenharmony_ci and keyword arguments may follow dictionary unpackings (``**``). 10807db96d56Sopenharmony_ci Originally proposed by :pep:`448`. 10817db96d56Sopenharmony_ci 10827db96d56Sopenharmony_ciA call always returns some value, possibly ``None``, unless it raises an 10837db96d56Sopenharmony_ciexception. How this value is computed depends on the type of the callable 10847db96d56Sopenharmony_ciobject. 10857db96d56Sopenharmony_ci 10867db96d56Sopenharmony_ciIf it is--- 10877db96d56Sopenharmony_ci 10887db96d56Sopenharmony_cia user-defined function: 10897db96d56Sopenharmony_ci .. index:: 10907db96d56Sopenharmony_ci pair: function; call 10917db96d56Sopenharmony_ci triple: user-defined; function; call 10927db96d56Sopenharmony_ci pair: object; user-defined function 10937db96d56Sopenharmony_ci pair: object; function 10947db96d56Sopenharmony_ci 10957db96d56Sopenharmony_ci The code block for the function is executed, passing it the argument list. The 10967db96d56Sopenharmony_ci first thing the code block will do is bind the formal parameters to the 10977db96d56Sopenharmony_ci arguments; this is described in section :ref:`function`. When the code block 10987db96d56Sopenharmony_ci executes a :keyword:`return` statement, this specifies the return value of the 10997db96d56Sopenharmony_ci function call. 11007db96d56Sopenharmony_ci 11017db96d56Sopenharmony_cia built-in function or method: 11027db96d56Sopenharmony_ci .. index:: 11037db96d56Sopenharmony_ci pair: function; call 11047db96d56Sopenharmony_ci pair: built-in function; call 11057db96d56Sopenharmony_ci pair: method; call 11067db96d56Sopenharmony_ci pair: built-in method; call 11077db96d56Sopenharmony_ci pair: object; built-in method 11087db96d56Sopenharmony_ci pair: object; built-in function 11097db96d56Sopenharmony_ci pair: object; method 11107db96d56Sopenharmony_ci pair: object; function 11117db96d56Sopenharmony_ci 11127db96d56Sopenharmony_ci The result is up to the interpreter; see :ref:`built-in-funcs` for the 11137db96d56Sopenharmony_ci descriptions of built-in functions and methods. 11147db96d56Sopenharmony_ci 11157db96d56Sopenharmony_cia class object: 11167db96d56Sopenharmony_ci .. index:: 11177db96d56Sopenharmony_ci pair: object; class 11187db96d56Sopenharmony_ci pair: class object; call 11197db96d56Sopenharmony_ci 11207db96d56Sopenharmony_ci A new instance of that class is returned. 11217db96d56Sopenharmony_ci 11227db96d56Sopenharmony_cia class instance method: 11237db96d56Sopenharmony_ci .. index:: 11247db96d56Sopenharmony_ci pair: object; class instance 11257db96d56Sopenharmony_ci pair: object; instance 11267db96d56Sopenharmony_ci pair: class instance; call 11277db96d56Sopenharmony_ci 11287db96d56Sopenharmony_ci The corresponding user-defined function is called, with an argument list that is 11297db96d56Sopenharmony_ci one longer than the argument list of the call: the instance becomes the first 11307db96d56Sopenharmony_ci argument. 11317db96d56Sopenharmony_ci 11327db96d56Sopenharmony_cia class instance: 11337db96d56Sopenharmony_ci .. index:: 11347db96d56Sopenharmony_ci pair: instance; call 11357db96d56Sopenharmony_ci single: __call__() (object method) 11367db96d56Sopenharmony_ci 11377db96d56Sopenharmony_ci The class must define a :meth:`__call__` method; the effect is then the same as 11387db96d56Sopenharmony_ci if that method was called. 11397db96d56Sopenharmony_ci 11407db96d56Sopenharmony_ci 11417db96d56Sopenharmony_ci.. index:: pair: keyword; await 11427db96d56Sopenharmony_ci.. _await: 11437db96d56Sopenharmony_ci 11447db96d56Sopenharmony_ciAwait expression 11457db96d56Sopenharmony_ci================ 11467db96d56Sopenharmony_ci 11477db96d56Sopenharmony_ciSuspend the execution of :term:`coroutine` on an :term:`awaitable` object. 11487db96d56Sopenharmony_ciCan only be used inside a :term:`coroutine function`. 11497db96d56Sopenharmony_ci 11507db96d56Sopenharmony_ci.. productionlist:: python-grammar 11517db96d56Sopenharmony_ci await_expr: "await" `primary` 11527db96d56Sopenharmony_ci 11537db96d56Sopenharmony_ci.. versionadded:: 3.5 11547db96d56Sopenharmony_ci 11557db96d56Sopenharmony_ci 11567db96d56Sopenharmony_ci.. _power: 11577db96d56Sopenharmony_ci 11587db96d56Sopenharmony_ciThe power operator 11597db96d56Sopenharmony_ci================== 11607db96d56Sopenharmony_ci 11617db96d56Sopenharmony_ci.. index:: 11627db96d56Sopenharmony_ci pair: power; operation 11637db96d56Sopenharmony_ci pair: operator; ** 11647db96d56Sopenharmony_ci 11657db96d56Sopenharmony_ciThe power operator binds more tightly than unary operators on its left; it binds 11667db96d56Sopenharmony_ciless tightly than unary operators on its right. The syntax is: 11677db96d56Sopenharmony_ci 11687db96d56Sopenharmony_ci.. productionlist:: python-grammar 11697db96d56Sopenharmony_ci power: (`await_expr` | `primary`) ["**" `u_expr`] 11707db96d56Sopenharmony_ci 11717db96d56Sopenharmony_ciThus, in an unparenthesized sequence of power and unary operators, the operators 11727db96d56Sopenharmony_ciare evaluated from right to left (this does not constrain the evaluation order 11737db96d56Sopenharmony_cifor the operands): ``-1**2`` results in ``-1``. 11747db96d56Sopenharmony_ci 11757db96d56Sopenharmony_ciThe power operator has the same semantics as the built-in :func:`pow` function, 11767db96d56Sopenharmony_ciwhen called with two arguments: it yields its left argument raised to the power 11777db96d56Sopenharmony_ciof its right argument. The numeric arguments are first converted to a common 11787db96d56Sopenharmony_citype, and the result is of that type. 11797db96d56Sopenharmony_ci 11807db96d56Sopenharmony_ciFor int operands, the result has the same type as the operands unless the second 11817db96d56Sopenharmony_ciargument is negative; in that case, all arguments are converted to float and a 11827db96d56Sopenharmony_cifloat result is delivered. For example, ``10**2`` returns ``100``, but 11837db96d56Sopenharmony_ci``10**-2`` returns ``0.01``. 11847db96d56Sopenharmony_ci 11857db96d56Sopenharmony_ciRaising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. 11867db96d56Sopenharmony_ciRaising a negative number to a fractional power results in a :class:`complex` 11877db96d56Sopenharmony_cinumber. (In earlier versions it raised a :exc:`ValueError`.) 11887db96d56Sopenharmony_ci 11897db96d56Sopenharmony_ciThis operation can be customized using the special :meth:`__pow__` method. 11907db96d56Sopenharmony_ci 11917db96d56Sopenharmony_ci.. _unary: 11927db96d56Sopenharmony_ci 11937db96d56Sopenharmony_ciUnary arithmetic and bitwise operations 11947db96d56Sopenharmony_ci======================================= 11957db96d56Sopenharmony_ci 11967db96d56Sopenharmony_ci.. index:: 11977db96d56Sopenharmony_ci triple: unary; arithmetic; operation 11987db96d56Sopenharmony_ci triple: unary; bitwise; operation 11997db96d56Sopenharmony_ci 12007db96d56Sopenharmony_ciAll unary arithmetic and bitwise operations have the same priority: 12017db96d56Sopenharmony_ci 12027db96d56Sopenharmony_ci.. productionlist:: python-grammar 12037db96d56Sopenharmony_ci u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr` 12047db96d56Sopenharmony_ci 12057db96d56Sopenharmony_ci.. index:: 12067db96d56Sopenharmony_ci single: negation 12077db96d56Sopenharmony_ci single: minus 12087db96d56Sopenharmony_ci single: operator; - (minus) 12097db96d56Sopenharmony_ci single: - (minus); unary operator 12107db96d56Sopenharmony_ci 12117db96d56Sopenharmony_ciThe unary ``-`` (minus) operator yields the negation of its numeric argument; the 12127db96d56Sopenharmony_cioperation can be overridden with the :meth:`__neg__` special method. 12137db96d56Sopenharmony_ci 12147db96d56Sopenharmony_ci.. index:: 12157db96d56Sopenharmony_ci single: plus 12167db96d56Sopenharmony_ci single: operator; + (plus) 12177db96d56Sopenharmony_ci single: + (plus); unary operator 12187db96d56Sopenharmony_ci 12197db96d56Sopenharmony_ciThe unary ``+`` (plus) operator yields its numeric argument unchanged; the 12207db96d56Sopenharmony_cioperation can be overridden with the :meth:`__pos__` special method. 12217db96d56Sopenharmony_ci 12227db96d56Sopenharmony_ci.. index:: 12237db96d56Sopenharmony_ci single: inversion 12247db96d56Sopenharmony_ci pair: operator; ~ (tilde) 12257db96d56Sopenharmony_ci 12267db96d56Sopenharmony_ciThe unary ``~`` (invert) operator yields the bitwise inversion of its integer 12277db96d56Sopenharmony_ciargument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only 12287db96d56Sopenharmony_ciapplies to integral numbers or to custom objects that override the 12297db96d56Sopenharmony_ci:meth:`__invert__` special method. 12307db96d56Sopenharmony_ci 12317db96d56Sopenharmony_ci 12327db96d56Sopenharmony_ci 12337db96d56Sopenharmony_ci.. index:: pair: exception; TypeError 12347db96d56Sopenharmony_ci 12357db96d56Sopenharmony_ciIn all three cases, if the argument does not have the proper type, a 12367db96d56Sopenharmony_ci:exc:`TypeError` exception is raised. 12377db96d56Sopenharmony_ci 12387db96d56Sopenharmony_ci 12397db96d56Sopenharmony_ci.. _binary: 12407db96d56Sopenharmony_ci 12417db96d56Sopenharmony_ciBinary arithmetic operations 12427db96d56Sopenharmony_ci============================ 12437db96d56Sopenharmony_ci 12447db96d56Sopenharmony_ci.. index:: triple: binary; arithmetic; operation 12457db96d56Sopenharmony_ci 12467db96d56Sopenharmony_ciThe binary arithmetic operations have the conventional priority levels. Note 12477db96d56Sopenharmony_cithat some of these operations also apply to certain non-numeric types. Apart 12487db96d56Sopenharmony_cifrom the power operator, there are only two levels, one for multiplicative 12497db96d56Sopenharmony_cioperators and one for additive operators: 12507db96d56Sopenharmony_ci 12517db96d56Sopenharmony_ci.. productionlist:: python-grammar 12527db96d56Sopenharmony_ci m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "@" `m_expr` | 12537db96d56Sopenharmony_ci : `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr` | 12547db96d56Sopenharmony_ci : `m_expr` "%" `u_expr` 12557db96d56Sopenharmony_ci a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr` 12567db96d56Sopenharmony_ci 12577db96d56Sopenharmony_ci.. index:: 12587db96d56Sopenharmony_ci single: multiplication 12597db96d56Sopenharmony_ci pair: operator; * (asterisk) 12607db96d56Sopenharmony_ci 12617db96d56Sopenharmony_ciThe ``*`` (multiplication) operator yields the product of its arguments. The 12627db96d56Sopenharmony_ciarguments must either both be numbers, or one argument must be an integer and 12637db96d56Sopenharmony_cithe other must be a sequence. In the former case, the numbers are converted to a 12647db96d56Sopenharmony_cicommon type and then multiplied together. In the latter case, sequence 12657db96d56Sopenharmony_cirepetition is performed; a negative repetition factor yields an empty sequence. 12667db96d56Sopenharmony_ci 12677db96d56Sopenharmony_ciThis operation can be customized using the special :meth:`__mul__` and 12687db96d56Sopenharmony_ci:meth:`__rmul__` methods. 12697db96d56Sopenharmony_ci 12707db96d56Sopenharmony_ci.. index:: 12717db96d56Sopenharmony_ci single: matrix multiplication 12727db96d56Sopenharmony_ci pair: operator; @ (at) 12737db96d56Sopenharmony_ci 12747db96d56Sopenharmony_ciThe ``@`` (at) operator is intended to be used for matrix multiplication. No 12757db96d56Sopenharmony_cibuiltin Python types implement this operator. 12767db96d56Sopenharmony_ci 12777db96d56Sopenharmony_ci.. versionadded:: 3.5 12787db96d56Sopenharmony_ci 12797db96d56Sopenharmony_ci.. index:: 12807db96d56Sopenharmony_ci pair: exception; ZeroDivisionError 12817db96d56Sopenharmony_ci single: division 12827db96d56Sopenharmony_ci pair: operator; / (slash) 12837db96d56Sopenharmony_ci pair: operator; // 12847db96d56Sopenharmony_ci 12857db96d56Sopenharmony_ciThe ``/`` (division) and ``//`` (floor division) operators yield the quotient of 12867db96d56Sopenharmony_citheir arguments. The numeric arguments are first converted to a common type. 12877db96d56Sopenharmony_ciDivision of integers yields a float, while floor division of integers results in an 12887db96d56Sopenharmony_ciinteger; the result is that of mathematical division with the 'floor' function 12897db96d56Sopenharmony_ciapplied to the result. Division by zero raises the :exc:`ZeroDivisionError` 12907db96d56Sopenharmony_ciexception. 12917db96d56Sopenharmony_ci 12927db96d56Sopenharmony_ciThis operation can be customized using the special :meth:`__truediv__` and 12937db96d56Sopenharmony_ci:meth:`__floordiv__` methods. 12947db96d56Sopenharmony_ci 12957db96d56Sopenharmony_ci.. index:: 12967db96d56Sopenharmony_ci single: modulo 12977db96d56Sopenharmony_ci pair: operator; % (percent) 12987db96d56Sopenharmony_ci 12997db96d56Sopenharmony_ciThe ``%`` (modulo) operator yields the remainder from the division of the first 13007db96d56Sopenharmony_ciargument by the second. The numeric arguments are first converted to a common 13017db96d56Sopenharmony_citype. A zero right argument raises the :exc:`ZeroDivisionError` exception. The 13027db96d56Sopenharmony_ciarguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34`` 13037db96d56Sopenharmony_ci(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a 13047db96d56Sopenharmony_ciresult with the same sign as its second operand (or zero); the absolute value of 13057db96d56Sopenharmony_cithe result is strictly smaller than the absolute value of the second operand 13067db96d56Sopenharmony_ci[#]_. 13077db96d56Sopenharmony_ci 13087db96d56Sopenharmony_ciThe floor division and modulo operators are connected by the following 13097db96d56Sopenharmony_ciidentity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also 13107db96d56Sopenharmony_ciconnected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, 13117db96d56Sopenharmony_cix%y)``. [#]_. 13127db96d56Sopenharmony_ci 13137db96d56Sopenharmony_ciIn addition to performing the modulo operation on numbers, the ``%`` operator is 13147db96d56Sopenharmony_cialso overloaded by string objects to perform old-style string formatting (also 13157db96d56Sopenharmony_ciknown as interpolation). The syntax for string formatting is described in the 13167db96d56Sopenharmony_ciPython Library Reference, section :ref:`old-string-formatting`. 13177db96d56Sopenharmony_ci 13187db96d56Sopenharmony_ciThe *modulo* operation can be customized using the special :meth:`__mod__` method. 13197db96d56Sopenharmony_ci 13207db96d56Sopenharmony_ciThe floor division operator, the modulo operator, and the :func:`divmod` 13217db96d56Sopenharmony_cifunction are not defined for complex numbers. Instead, convert to a floating 13227db96d56Sopenharmony_cipoint number using the :func:`abs` function if appropriate. 13237db96d56Sopenharmony_ci 13247db96d56Sopenharmony_ci.. index:: 13257db96d56Sopenharmony_ci single: addition 13267db96d56Sopenharmony_ci single: operator; + (plus) 13277db96d56Sopenharmony_ci single: + (plus); binary operator 13287db96d56Sopenharmony_ci 13297db96d56Sopenharmony_ciThe ``+`` (addition) operator yields the sum of its arguments. The arguments 13307db96d56Sopenharmony_cimust either both be numbers or both be sequences of the same type. In the 13317db96d56Sopenharmony_ciformer case, the numbers are converted to a common type and then added together. 13327db96d56Sopenharmony_ciIn the latter case, the sequences are concatenated. 13337db96d56Sopenharmony_ci 13347db96d56Sopenharmony_ciThis operation can be customized using the special :meth:`__add__` and 13357db96d56Sopenharmony_ci:meth:`__radd__` methods. 13367db96d56Sopenharmony_ci 13377db96d56Sopenharmony_ci.. index:: 13387db96d56Sopenharmony_ci single: subtraction 13397db96d56Sopenharmony_ci single: operator; - (minus) 13407db96d56Sopenharmony_ci single: - (minus); binary operator 13417db96d56Sopenharmony_ci 13427db96d56Sopenharmony_ciThe ``-`` (subtraction) operator yields the difference of its arguments. The 13437db96d56Sopenharmony_cinumeric arguments are first converted to a common type. 13447db96d56Sopenharmony_ci 13457db96d56Sopenharmony_ciThis operation can be customized using the special :meth:`__sub__` method. 13467db96d56Sopenharmony_ci 13477db96d56Sopenharmony_ci 13487db96d56Sopenharmony_ci.. _shifting: 13497db96d56Sopenharmony_ci 13507db96d56Sopenharmony_ciShifting operations 13517db96d56Sopenharmony_ci=================== 13527db96d56Sopenharmony_ci 13537db96d56Sopenharmony_ci.. index:: 13547db96d56Sopenharmony_ci pair: shifting; operation 13557db96d56Sopenharmony_ci pair: operator; << 13567db96d56Sopenharmony_ci pair: operator; >> 13577db96d56Sopenharmony_ci 13587db96d56Sopenharmony_ciThe shifting operations have lower priority than the arithmetic operations: 13597db96d56Sopenharmony_ci 13607db96d56Sopenharmony_ci.. productionlist:: python-grammar 13617db96d56Sopenharmony_ci shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr` 13627db96d56Sopenharmony_ci 13637db96d56Sopenharmony_ciThese operators accept integers as arguments. They shift the first argument to 13647db96d56Sopenharmony_cithe left or right by the number of bits given by the second argument. 13657db96d56Sopenharmony_ci 13667db96d56Sopenharmony_ciThis operation can be customized using the special :meth:`__lshift__` and 13677db96d56Sopenharmony_ci:meth:`__rshift__` methods. 13687db96d56Sopenharmony_ci 13697db96d56Sopenharmony_ci.. index:: pair: exception; ValueError 13707db96d56Sopenharmony_ci 13717db96d56Sopenharmony_ciA right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left 13727db96d56Sopenharmony_cishift by *n* bits is defined as multiplication with ``pow(2,n)``. 13737db96d56Sopenharmony_ci 13747db96d56Sopenharmony_ci 13757db96d56Sopenharmony_ci.. _bitwise: 13767db96d56Sopenharmony_ci 13777db96d56Sopenharmony_ciBinary bitwise operations 13787db96d56Sopenharmony_ci========================= 13797db96d56Sopenharmony_ci 13807db96d56Sopenharmony_ci.. index:: triple: binary; bitwise; operation 13817db96d56Sopenharmony_ci 13827db96d56Sopenharmony_ciEach of the three bitwise operations has a different priority level: 13837db96d56Sopenharmony_ci 13847db96d56Sopenharmony_ci.. productionlist:: python-grammar 13857db96d56Sopenharmony_ci and_expr: `shift_expr` | `and_expr` "&" `shift_expr` 13867db96d56Sopenharmony_ci xor_expr: `and_expr` | `xor_expr` "^" `and_expr` 13877db96d56Sopenharmony_ci or_expr: `xor_expr` | `or_expr` "|" `xor_expr` 13887db96d56Sopenharmony_ci 13897db96d56Sopenharmony_ci.. index:: 13907db96d56Sopenharmony_ci pair: bitwise; and 13917db96d56Sopenharmony_ci pair: operator; & (ampersand) 13927db96d56Sopenharmony_ci 13937db96d56Sopenharmony_ciThe ``&`` operator yields the bitwise AND of its arguments, which must be 13947db96d56Sopenharmony_ciintegers or one of them must be a custom object overriding :meth:`__and__` or 13957db96d56Sopenharmony_ci:meth:`__rand__` special methods. 13967db96d56Sopenharmony_ci 13977db96d56Sopenharmony_ci.. index:: 13987db96d56Sopenharmony_ci pair: bitwise; xor 13997db96d56Sopenharmony_ci pair: exclusive; or 14007db96d56Sopenharmony_ci pair: operator; ^ (caret) 14017db96d56Sopenharmony_ci 14027db96d56Sopenharmony_ciThe ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which 14037db96d56Sopenharmony_cimust be integers or one of them must be a custom object overriding :meth:`__xor__` or 14047db96d56Sopenharmony_ci:meth:`__rxor__` special methods. 14057db96d56Sopenharmony_ci 14067db96d56Sopenharmony_ci.. index:: 14077db96d56Sopenharmony_ci pair: bitwise; or 14087db96d56Sopenharmony_ci pair: inclusive; or 14097db96d56Sopenharmony_ci pair: operator; | (vertical bar) 14107db96d56Sopenharmony_ci 14117db96d56Sopenharmony_ciThe ``|`` operator yields the bitwise (inclusive) OR of its arguments, which 14127db96d56Sopenharmony_cimust be integers or one of them must be a custom object overriding :meth:`__or__` or 14137db96d56Sopenharmony_ci:meth:`__ror__` special methods. 14147db96d56Sopenharmony_ci 14157db96d56Sopenharmony_ci 14167db96d56Sopenharmony_ci.. _comparisons: 14177db96d56Sopenharmony_ci 14187db96d56Sopenharmony_ciComparisons 14197db96d56Sopenharmony_ci=========== 14207db96d56Sopenharmony_ci 14217db96d56Sopenharmony_ci.. index:: 14227db96d56Sopenharmony_ci single: comparison 14237db96d56Sopenharmony_ci pair: C; language 14247db96d56Sopenharmony_ci pair: operator; < (less) 14257db96d56Sopenharmony_ci pair: operator; > (greater) 14267db96d56Sopenharmony_ci pair: operator; <= 14277db96d56Sopenharmony_ci pair: operator; >= 14287db96d56Sopenharmony_ci pair: operator; == 14297db96d56Sopenharmony_ci pair: operator; != 14307db96d56Sopenharmony_ci 14317db96d56Sopenharmony_ciUnlike C, all comparison operations in Python have the same priority, which is 14327db96d56Sopenharmony_cilower than that of any arithmetic, shifting or bitwise operation. Also unlike 14337db96d56Sopenharmony_ciC, expressions like ``a < b < c`` have the interpretation that is conventional 14347db96d56Sopenharmony_ciin mathematics: 14357db96d56Sopenharmony_ci 14367db96d56Sopenharmony_ci.. productionlist:: python-grammar 14377db96d56Sopenharmony_ci comparison: `or_expr` (`comp_operator` `or_expr`)* 14387db96d56Sopenharmony_ci comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!=" 14397db96d56Sopenharmony_ci : | "is" ["not"] | ["not"] "in" 14407db96d56Sopenharmony_ci 14417db96d56Sopenharmony_ciComparisons yield boolean values: ``True`` or ``False``. Custom 14427db96d56Sopenharmony_ci:dfn:`rich comparison methods` may return non-boolean values. In this case 14437db96d56Sopenharmony_ciPython will call :func:`bool` on such value in boolean contexts. 14447db96d56Sopenharmony_ci 14457db96d56Sopenharmony_ci.. index:: pair: chaining; comparisons 14467db96d56Sopenharmony_ci 14477db96d56Sopenharmony_ciComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to 14487db96d56Sopenharmony_ci``x < y and y <= z``, except that ``y`` is evaluated only once (but in both 14497db96d56Sopenharmony_cicases ``z`` is not evaluated at all when ``x < y`` is found to be false). 14507db96d56Sopenharmony_ci 14517db96d56Sopenharmony_ciFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., 14527db96d56Sopenharmony_ci*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent 14537db96d56Sopenharmony_cito ``a op1 b and b op2 c and ... y opN z``, except that each expression is 14547db96d56Sopenharmony_cievaluated at most once. 14557db96d56Sopenharmony_ci 14567db96d56Sopenharmony_ciNote that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and 14577db96d56Sopenharmony_ci*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not 14587db96d56Sopenharmony_cipretty). 14597db96d56Sopenharmony_ci 14607db96d56Sopenharmony_ci.. _expressions-value-comparisons: 14617db96d56Sopenharmony_ci 14627db96d56Sopenharmony_ciValue comparisons 14637db96d56Sopenharmony_ci----------------- 14647db96d56Sopenharmony_ci 14657db96d56Sopenharmony_ciThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the 14667db96d56Sopenharmony_civalues of two objects. The objects do not need to have the same type. 14677db96d56Sopenharmony_ci 14687db96d56Sopenharmony_ciChapter :ref:`objects` states that objects have a value (in addition to type 14697db96d56Sopenharmony_ciand identity). The value of an object is a rather abstract notion in Python: 14707db96d56Sopenharmony_ciFor example, there is no canonical access method for an object's value. Also, 14717db96d56Sopenharmony_cithere is no requirement that the value of an object should be constructed in a 14727db96d56Sopenharmony_ciparticular way, e.g. comprised of all its data attributes. Comparison operators 14737db96d56Sopenharmony_ciimplement a particular notion of what the value of an object is. One can think 14747db96d56Sopenharmony_ciof them as defining the value of an object indirectly, by means of their 14757db96d56Sopenharmony_cicomparison implementation. 14767db96d56Sopenharmony_ci 14777db96d56Sopenharmony_ciBecause all types are (direct or indirect) subtypes of :class:`object`, they 14787db96d56Sopenharmony_ciinherit the default comparison behavior from :class:`object`. Types can 14797db96d56Sopenharmony_cicustomize their comparison behavior by implementing 14807db96d56Sopenharmony_ci:dfn:`rich comparison methods` like :meth:`__lt__`, described in 14817db96d56Sopenharmony_ci:ref:`customization`. 14827db96d56Sopenharmony_ci 14837db96d56Sopenharmony_ciThe default behavior for equality comparison (``==`` and ``!=``) is based on 14847db96d56Sopenharmony_cithe identity of the objects. Hence, equality comparison of instances with the 14857db96d56Sopenharmony_cisame identity results in equality, and equality comparison of instances with 14867db96d56Sopenharmony_cidifferent identities results in inequality. A motivation for this default 14877db96d56Sopenharmony_cibehavior is the desire that all objects should be reflexive (i.e. ``x is y`` 14887db96d56Sopenharmony_ciimplies ``x == y``). 14897db96d56Sopenharmony_ci 14907db96d56Sopenharmony_ciA default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; 14917db96d56Sopenharmony_cian attempt raises :exc:`TypeError`. A motivation for this default behavior is 14927db96d56Sopenharmony_cithe lack of a similar invariant as for equality. 14937db96d56Sopenharmony_ci 14947db96d56Sopenharmony_ciThe behavior of the default equality comparison, that instances with different 14957db96d56Sopenharmony_ciidentities are always unequal, may be in contrast to what types will need that 14967db96d56Sopenharmony_cihave a sensible definition of object value and value-based equality. Such 14977db96d56Sopenharmony_citypes will need to customize their comparison behavior, and in fact, a number 14987db96d56Sopenharmony_ciof built-in types have done that. 14997db96d56Sopenharmony_ci 15007db96d56Sopenharmony_ciThe following list describes the comparison behavior of the most important 15017db96d56Sopenharmony_cibuilt-in types. 15027db96d56Sopenharmony_ci 15037db96d56Sopenharmony_ci* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard 15047db96d56Sopenharmony_ci library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be 15057db96d56Sopenharmony_ci compared within and across their types, with the restriction that complex 15067db96d56Sopenharmony_ci numbers do not support order comparison. Within the limits of the types 15077db96d56Sopenharmony_ci involved, they compare mathematically (algorithmically) correct without loss 15087db96d56Sopenharmony_ci of precision. 15097db96d56Sopenharmony_ci 15107db96d56Sopenharmony_ci The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are 15117db96d56Sopenharmony_ci special. Any ordered comparison of a number to a not-a-number value is false. 15127db96d56Sopenharmony_ci A counter-intuitive implication is that not-a-number values are not equal to 15137db96d56Sopenharmony_ci themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and 15147db96d56Sopenharmony_ci ``x == x`` are all false, while ``x != x`` is true. This behavior is 15157db96d56Sopenharmony_ci compliant with IEEE 754. 15167db96d56Sopenharmony_ci 15177db96d56Sopenharmony_ci* ``None`` and ``NotImplemented`` are singletons. :PEP:`8` advises that 15187db96d56Sopenharmony_ci comparisons for singletons should always be done with ``is`` or ``is not``, 15197db96d56Sopenharmony_ci never the equality operators. 15207db96d56Sopenharmony_ci 15217db96d56Sopenharmony_ci* Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be 15227db96d56Sopenharmony_ci compared within and across their types. They compare lexicographically using 15237db96d56Sopenharmony_ci the numeric values of their elements. 15247db96d56Sopenharmony_ci 15257db96d56Sopenharmony_ci* Strings (instances of :class:`str`) compare lexicographically using the 15267db96d56Sopenharmony_ci numerical Unicode code points (the result of the built-in function 15277db96d56Sopenharmony_ci :func:`ord`) of their characters. [#]_ 15287db96d56Sopenharmony_ci 15297db96d56Sopenharmony_ci Strings and binary sequences cannot be directly compared. 15307db96d56Sopenharmony_ci 15317db96d56Sopenharmony_ci* Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can 15327db96d56Sopenharmony_ci be compared only within each of their types, with the restriction that ranges 15337db96d56Sopenharmony_ci do not support order comparison. Equality comparison across these types 15347db96d56Sopenharmony_ci results in inequality, and ordering comparison across these types raises 15357db96d56Sopenharmony_ci :exc:`TypeError`. 15367db96d56Sopenharmony_ci 15377db96d56Sopenharmony_ci Sequences compare lexicographically using comparison of corresponding 15387db96d56Sopenharmony_ci elements. The built-in containers typically assume identical objects are 15397db96d56Sopenharmony_ci equal to themselves. That lets them bypass equality tests for identical 15407db96d56Sopenharmony_ci objects to improve performance and to maintain their internal invariants. 15417db96d56Sopenharmony_ci 15427db96d56Sopenharmony_ci Lexicographical comparison between built-in collections works as follows: 15437db96d56Sopenharmony_ci 15447db96d56Sopenharmony_ci - For two collections to compare equal, they must be of the same type, have 15457db96d56Sopenharmony_ci the same length, and each pair of corresponding elements must compare 15467db96d56Sopenharmony_ci equal (for example, ``[1,2] == (1,2)`` is false because the type is not the 15477db96d56Sopenharmony_ci same). 15487db96d56Sopenharmony_ci 15497db96d56Sopenharmony_ci - Collections that support order comparison are ordered the same as their 15507db96d56Sopenharmony_ci first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same 15517db96d56Sopenharmony_ci value as ``x <= y``). If a corresponding element does not exist, the 15527db96d56Sopenharmony_ci shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is 15537db96d56Sopenharmony_ci true). 15547db96d56Sopenharmony_ci 15557db96d56Sopenharmony_ci* Mappings (instances of :class:`dict`) compare equal if and only if they have 15567db96d56Sopenharmony_ci equal ``(key, value)`` pairs. Equality comparison of the keys and values 15577db96d56Sopenharmony_ci enforces reflexivity. 15587db96d56Sopenharmony_ci 15597db96d56Sopenharmony_ci Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`. 15607db96d56Sopenharmony_ci 15617db96d56Sopenharmony_ci* Sets (instances of :class:`set` or :class:`frozenset`) can be compared within 15627db96d56Sopenharmony_ci and across their types. 15637db96d56Sopenharmony_ci 15647db96d56Sopenharmony_ci They define order 15657db96d56Sopenharmony_ci comparison operators to mean subset and superset tests. Those relations do 15667db96d56Sopenharmony_ci not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` 15677db96d56Sopenharmony_ci are not equal, nor subsets of one another, nor supersets of one 15687db96d56Sopenharmony_ci another). Accordingly, sets are not appropriate arguments for functions 15697db96d56Sopenharmony_ci which depend on total ordering (for example, :func:`min`, :func:`max`, and 15707db96d56Sopenharmony_ci :func:`sorted` produce undefined results given a list of sets as inputs). 15717db96d56Sopenharmony_ci 15727db96d56Sopenharmony_ci Comparison of sets enforces reflexivity of its elements. 15737db96d56Sopenharmony_ci 15747db96d56Sopenharmony_ci* Most other built-in types have no comparison methods implemented, so they 15757db96d56Sopenharmony_ci inherit the default comparison behavior. 15767db96d56Sopenharmony_ci 15777db96d56Sopenharmony_ciUser-defined classes that customize their comparison behavior should follow 15787db96d56Sopenharmony_cisome consistency rules, if possible: 15797db96d56Sopenharmony_ci 15807db96d56Sopenharmony_ci* Equality comparison should be reflexive. 15817db96d56Sopenharmony_ci In other words, identical objects should compare equal: 15827db96d56Sopenharmony_ci 15837db96d56Sopenharmony_ci ``x is y`` implies ``x == y`` 15847db96d56Sopenharmony_ci 15857db96d56Sopenharmony_ci* Comparison should be symmetric. 15867db96d56Sopenharmony_ci In other words, the following expressions should have the same result: 15877db96d56Sopenharmony_ci 15887db96d56Sopenharmony_ci ``x == y`` and ``y == x`` 15897db96d56Sopenharmony_ci 15907db96d56Sopenharmony_ci ``x != y`` and ``y != x`` 15917db96d56Sopenharmony_ci 15927db96d56Sopenharmony_ci ``x < y`` and ``y > x`` 15937db96d56Sopenharmony_ci 15947db96d56Sopenharmony_ci ``x <= y`` and ``y >= x`` 15957db96d56Sopenharmony_ci 15967db96d56Sopenharmony_ci* Comparison should be transitive. 15977db96d56Sopenharmony_ci The following (non-exhaustive) examples illustrate that: 15987db96d56Sopenharmony_ci 15997db96d56Sopenharmony_ci ``x > y and y > z`` implies ``x > z`` 16007db96d56Sopenharmony_ci 16017db96d56Sopenharmony_ci ``x < y and y <= z`` implies ``x < z`` 16027db96d56Sopenharmony_ci 16037db96d56Sopenharmony_ci* Inverse comparison should result in the boolean negation. 16047db96d56Sopenharmony_ci In other words, the following expressions should have the same result: 16057db96d56Sopenharmony_ci 16067db96d56Sopenharmony_ci ``x == y`` and ``not x != y`` 16077db96d56Sopenharmony_ci 16087db96d56Sopenharmony_ci ``x < y`` and ``not x >= y`` (for total ordering) 16097db96d56Sopenharmony_ci 16107db96d56Sopenharmony_ci ``x > y`` and ``not x <= y`` (for total ordering) 16117db96d56Sopenharmony_ci 16127db96d56Sopenharmony_ci The last two expressions apply to totally ordered collections (e.g. to 16137db96d56Sopenharmony_ci sequences, but not to sets or mappings). See also the 16147db96d56Sopenharmony_ci :func:`~functools.total_ordering` decorator. 16157db96d56Sopenharmony_ci 16167db96d56Sopenharmony_ci* The :func:`hash` result should be consistent with equality. 16177db96d56Sopenharmony_ci Objects that are equal should either have the same hash value, 16187db96d56Sopenharmony_ci or be marked as unhashable. 16197db96d56Sopenharmony_ci 16207db96d56Sopenharmony_ciPython does not enforce these consistency rules. In fact, the not-a-number 16217db96d56Sopenharmony_civalues are an example for not following these rules. 16227db96d56Sopenharmony_ci 16237db96d56Sopenharmony_ci 16247db96d56Sopenharmony_ci.. _in: 16257db96d56Sopenharmony_ci.. _not in: 16267db96d56Sopenharmony_ci.. _membership-test-details: 16277db96d56Sopenharmony_ci 16287db96d56Sopenharmony_ciMembership test operations 16297db96d56Sopenharmony_ci-------------------------- 16307db96d56Sopenharmony_ci 16317db96d56Sopenharmony_ciThe operators :keyword:`in` and :keyword:`not in` test for membership. ``x in 16327db96d56Sopenharmony_cis`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. 16337db96d56Sopenharmony_ci``x not in s`` returns the negation of ``x in s``. All built-in sequences and 16347db96d56Sopenharmony_ciset types support this as well as dictionary, for which :keyword:`!in` tests 16357db96d56Sopenharmony_ciwhether the dictionary has a given key. For container types such as list, tuple, 16367db96d56Sopenharmony_ciset, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent 16377db96d56Sopenharmony_cito ``any(x is e or x == e for e in y)``. 16387db96d56Sopenharmony_ci 16397db96d56Sopenharmony_ciFor the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a 16407db96d56Sopenharmony_cisubstring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are 16417db96d56Sopenharmony_cialways considered to be a substring of any other string, so ``"" in "abc"`` will 16427db96d56Sopenharmony_cireturn ``True``. 16437db96d56Sopenharmony_ci 16447db96d56Sopenharmony_ciFor user-defined classes which define the :meth:`__contains__` method, ``x in 16457db96d56Sopenharmony_ciy`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and 16467db96d56Sopenharmony_ci``False`` otherwise. 16477db96d56Sopenharmony_ci 16487db96d56Sopenharmony_ciFor user-defined classes which do not define :meth:`__contains__` but do define 16497db96d56Sopenharmony_ci:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the 16507db96d56Sopenharmony_ciexpression ``x is z or x == z`` is true, is produced while iterating over ``y``. 16517db96d56Sopenharmony_ciIf an exception is raised during the iteration, it is as if :keyword:`in` raised 16527db96d56Sopenharmony_cithat exception. 16537db96d56Sopenharmony_ci 16547db96d56Sopenharmony_ciLastly, the old-style iteration protocol is tried: if a class defines 16557db96d56Sopenharmony_ci:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative 16567db96d56Sopenharmony_ciinteger index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index 16577db96d56Sopenharmony_ciraises the :exc:`IndexError` exception. (If any other exception is raised, it is as 16587db96d56Sopenharmony_ciif :keyword:`in` raised that exception). 16597db96d56Sopenharmony_ci 16607db96d56Sopenharmony_ci.. index:: 16617db96d56Sopenharmony_ci pair: operator; in 16627db96d56Sopenharmony_ci pair: operator; not in 16637db96d56Sopenharmony_ci pair: membership; test 16647db96d56Sopenharmony_ci pair: object; sequence 16657db96d56Sopenharmony_ci 16667db96d56Sopenharmony_ciThe operator :keyword:`not in` is defined to have the inverse truth value of 16677db96d56Sopenharmony_ci:keyword:`in`. 16687db96d56Sopenharmony_ci 16697db96d56Sopenharmony_ci.. index:: 16707db96d56Sopenharmony_ci pair: operator; is 16717db96d56Sopenharmony_ci pair: operator; is not 16727db96d56Sopenharmony_ci pair: identity; test 16737db96d56Sopenharmony_ci 16747db96d56Sopenharmony_ci 16757db96d56Sopenharmony_ci.. _is: 16767db96d56Sopenharmony_ci.. _is not: 16777db96d56Sopenharmony_ci 16787db96d56Sopenharmony_ciIdentity comparisons 16797db96d56Sopenharmony_ci-------------------- 16807db96d56Sopenharmony_ci 16817db96d56Sopenharmony_ciThe operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x 16827db96d56Sopenharmony_ciis y`` is true if and only if *x* and *y* are the same object. An Object's identity 16837db96d56Sopenharmony_ciis determined using the :meth:`id` function. ``x is not y`` yields the inverse 16847db96d56Sopenharmony_citruth value. [#]_ 16857db96d56Sopenharmony_ci 16867db96d56Sopenharmony_ci 16877db96d56Sopenharmony_ci.. _booleans: 16887db96d56Sopenharmony_ci.. _and: 16897db96d56Sopenharmony_ci.. _or: 16907db96d56Sopenharmony_ci.. _not: 16917db96d56Sopenharmony_ci 16927db96d56Sopenharmony_ciBoolean operations 16937db96d56Sopenharmony_ci================== 16947db96d56Sopenharmony_ci 16957db96d56Sopenharmony_ci.. index:: 16967db96d56Sopenharmony_ci pair: Conditional; expression 16977db96d56Sopenharmony_ci pair: Boolean; operation 16987db96d56Sopenharmony_ci 16997db96d56Sopenharmony_ci.. productionlist:: python-grammar 17007db96d56Sopenharmony_ci or_test: `and_test` | `or_test` "or" `and_test` 17017db96d56Sopenharmony_ci and_test: `not_test` | `and_test` "and" `not_test` 17027db96d56Sopenharmony_ci not_test: `comparison` | "not" `not_test` 17037db96d56Sopenharmony_ci 17047db96d56Sopenharmony_ciIn the context of Boolean operations, and also when expressions are used by 17057db96d56Sopenharmony_cicontrol flow statements, the following values are interpreted as false: 17067db96d56Sopenharmony_ci``False``, ``None``, numeric zero of all types, and empty strings and containers 17077db96d56Sopenharmony_ci(including strings, tuples, lists, dictionaries, sets and frozensets). All 17087db96d56Sopenharmony_ciother values are interpreted as true. User-defined objects can customize their 17097db96d56Sopenharmony_citruth value by providing a :meth:`__bool__` method. 17107db96d56Sopenharmony_ci 17117db96d56Sopenharmony_ci.. index:: pair: operator; not 17127db96d56Sopenharmony_ci 17137db96d56Sopenharmony_ciThe operator :keyword:`not` yields ``True`` if its argument is false, ``False`` 17147db96d56Sopenharmony_ciotherwise. 17157db96d56Sopenharmony_ci 17167db96d56Sopenharmony_ci.. index:: pair: operator; and 17177db96d56Sopenharmony_ci 17187db96d56Sopenharmony_ciThe expression ``x and y`` first evaluates *x*; if *x* is false, its value is 17197db96d56Sopenharmony_cireturned; otherwise, *y* is evaluated and the resulting value is returned. 17207db96d56Sopenharmony_ci 17217db96d56Sopenharmony_ci.. index:: pair: operator; or 17227db96d56Sopenharmony_ci 17237db96d56Sopenharmony_ciThe expression ``x or y`` first evaluates *x*; if *x* is true, its value is 17247db96d56Sopenharmony_cireturned; otherwise, *y* is evaluated and the resulting value is returned. 17257db96d56Sopenharmony_ci 17267db96d56Sopenharmony_ciNote that neither :keyword:`and` nor :keyword:`or` restrict the value and type 17277db96d56Sopenharmony_cithey return to ``False`` and ``True``, but rather return the last evaluated 17287db96d56Sopenharmony_ciargument. This is sometimes useful, e.g., if ``s`` is a string that should be 17297db96d56Sopenharmony_cireplaced by a default value if it is empty, the expression ``s or 'foo'`` yields 17307db96d56Sopenharmony_cithe desired value. Because :keyword:`not` has to create a new value, it 17317db96d56Sopenharmony_cireturns a boolean value regardless of the type of its argument 17327db96d56Sopenharmony_ci(for example, ``not 'foo'`` produces ``False`` rather than ``''``.) 17337db96d56Sopenharmony_ci 17347db96d56Sopenharmony_ci 17357db96d56Sopenharmony_ci.. index:: 17367db96d56Sopenharmony_ci single: := (colon equals) 17377db96d56Sopenharmony_ci single: assignment expression 17387db96d56Sopenharmony_ci single: walrus operator 17397db96d56Sopenharmony_ci single: named expression 17407db96d56Sopenharmony_ci 17417db96d56Sopenharmony_ciAssignment expressions 17427db96d56Sopenharmony_ci====================== 17437db96d56Sopenharmony_ci 17447db96d56Sopenharmony_ci.. productionlist:: python-grammar 17457db96d56Sopenharmony_ci assignment_expression: [`identifier` ":="] `expression` 17467db96d56Sopenharmony_ci 17477db96d56Sopenharmony_ciAn assignment expression (sometimes also called a "named expression" or 17487db96d56Sopenharmony_ci"walrus") assigns an :token:`~python-grammar:expression` to an 17497db96d56Sopenharmony_ci:token:`~python-grammar:identifier`, while also returning the value of the 17507db96d56Sopenharmony_ci:token:`~python-grammar:expression`. 17517db96d56Sopenharmony_ci 17527db96d56Sopenharmony_ciOne common use case is when handling matched regular expressions: 17537db96d56Sopenharmony_ci 17547db96d56Sopenharmony_ci.. code-block:: python 17557db96d56Sopenharmony_ci 17567db96d56Sopenharmony_ci if matching := pattern.search(data): 17577db96d56Sopenharmony_ci do_something(matching) 17587db96d56Sopenharmony_ci 17597db96d56Sopenharmony_ciOr, when processing a file stream in chunks: 17607db96d56Sopenharmony_ci 17617db96d56Sopenharmony_ci.. code-block:: python 17627db96d56Sopenharmony_ci 17637db96d56Sopenharmony_ci while chunk := file.read(9000): 17647db96d56Sopenharmony_ci process(chunk) 17657db96d56Sopenharmony_ci 17667db96d56Sopenharmony_ciAssignment expressions must be surrounded by parentheses when used 17677db96d56Sopenharmony_cias sub-expressions in slicing, conditional, lambda, 17687db96d56Sopenharmony_cikeyword-argument, and comprehension-if expressions 17697db96d56Sopenharmony_ciand in ``assert`` and ``with`` statements. 17707db96d56Sopenharmony_ciIn all other places where they can be used, parentheses are not required, 17717db96d56Sopenharmony_ciincluding in ``if`` and ``while`` statements. 17727db96d56Sopenharmony_ci 17737db96d56Sopenharmony_ci.. versionadded:: 3.8 17747db96d56Sopenharmony_ci See :pep:`572` for more details about assignment expressions. 17757db96d56Sopenharmony_ci 17767db96d56Sopenharmony_ci 17777db96d56Sopenharmony_ci.. _if_expr: 17787db96d56Sopenharmony_ci 17797db96d56Sopenharmony_ciConditional expressions 17807db96d56Sopenharmony_ci======================= 17817db96d56Sopenharmony_ci 17827db96d56Sopenharmony_ci.. index:: 17837db96d56Sopenharmony_ci pair: conditional; expression 17847db96d56Sopenharmony_ci pair: ternary; operator 17857db96d56Sopenharmony_ci single: if; conditional expression 17867db96d56Sopenharmony_ci single: else; conditional expression 17877db96d56Sopenharmony_ci 17887db96d56Sopenharmony_ci.. productionlist:: python-grammar 17897db96d56Sopenharmony_ci conditional_expression: `or_test` ["if" `or_test` "else" `expression`] 17907db96d56Sopenharmony_ci expression: `conditional_expression` | `lambda_expr` 17917db96d56Sopenharmony_ci 17927db96d56Sopenharmony_ciConditional expressions (sometimes called a "ternary operator") have the lowest 17937db96d56Sopenharmony_cipriority of all Python operations. 17947db96d56Sopenharmony_ci 17957db96d56Sopenharmony_ciThe expression ``x if C else y`` first evaluates the condition, *C* rather than *x*. 17967db96d56Sopenharmony_ciIf *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is 17977db96d56Sopenharmony_cievaluated and its value is returned. 17987db96d56Sopenharmony_ci 17997db96d56Sopenharmony_ciSee :pep:`308` for more details about conditional expressions. 18007db96d56Sopenharmony_ci 18017db96d56Sopenharmony_ci 18027db96d56Sopenharmony_ci.. _lambdas: 18037db96d56Sopenharmony_ci.. _lambda: 18047db96d56Sopenharmony_ci 18057db96d56Sopenharmony_ciLambdas 18067db96d56Sopenharmony_ci======= 18077db96d56Sopenharmony_ci 18087db96d56Sopenharmony_ci.. index:: 18097db96d56Sopenharmony_ci pair: lambda; expression 18107db96d56Sopenharmony_ci pair: lambda; form 18117db96d56Sopenharmony_ci pair: anonymous; function 18127db96d56Sopenharmony_ci single: : (colon); lambda expression 18137db96d56Sopenharmony_ci 18147db96d56Sopenharmony_ci.. productionlist:: python-grammar 18157db96d56Sopenharmony_ci lambda_expr: "lambda" [`parameter_list`] ":" `expression` 18167db96d56Sopenharmony_ci 18177db96d56Sopenharmony_ciLambda expressions (sometimes called lambda forms) are used to create anonymous 18187db96d56Sopenharmony_cifunctions. The expression ``lambda parameters: expression`` yields a function 18197db96d56Sopenharmony_ciobject. The unnamed object behaves like a function object defined with: 18207db96d56Sopenharmony_ci 18217db96d56Sopenharmony_ci.. code-block:: none 18227db96d56Sopenharmony_ci 18237db96d56Sopenharmony_ci def <lambda>(parameters): 18247db96d56Sopenharmony_ci return expression 18257db96d56Sopenharmony_ci 18267db96d56Sopenharmony_ciSee section :ref:`function` for the syntax of parameter lists. Note that 18277db96d56Sopenharmony_cifunctions created with lambda expressions cannot contain statements or 18287db96d56Sopenharmony_ciannotations. 18297db96d56Sopenharmony_ci 18307db96d56Sopenharmony_ci 18317db96d56Sopenharmony_ci.. _exprlists: 18327db96d56Sopenharmony_ci 18337db96d56Sopenharmony_ciExpression lists 18347db96d56Sopenharmony_ci================ 18357db96d56Sopenharmony_ci 18367db96d56Sopenharmony_ci.. index:: 18377db96d56Sopenharmony_ci pair: expression; list 18387db96d56Sopenharmony_ci single: , (comma); expression list 18397db96d56Sopenharmony_ci 18407db96d56Sopenharmony_ci.. productionlist:: python-grammar 18417db96d56Sopenharmony_ci expression_list: `expression` ("," `expression`)* [","] 18427db96d56Sopenharmony_ci starred_list: `starred_item` ("," `starred_item`)* [","] 18437db96d56Sopenharmony_ci starred_expression: `expression` | (`starred_item` ",")* [`starred_item`] 18447db96d56Sopenharmony_ci starred_item: `assignment_expression` | "*" `or_expr` 18457db96d56Sopenharmony_ci 18467db96d56Sopenharmony_ci.. index:: pair: object; tuple 18477db96d56Sopenharmony_ci 18487db96d56Sopenharmony_ciExcept when part of a list or set display, an expression list 18497db96d56Sopenharmony_cicontaining at least one comma yields a tuple. The length of 18507db96d56Sopenharmony_cithe tuple is the number of expressions in the list. The expressions are 18517db96d56Sopenharmony_cievaluated from left to right. 18527db96d56Sopenharmony_ci 18537db96d56Sopenharmony_ci.. index:: 18547db96d56Sopenharmony_ci pair: iterable; unpacking 18557db96d56Sopenharmony_ci single: * (asterisk); in expression lists 18567db96d56Sopenharmony_ci 18577db96d56Sopenharmony_ciAn asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be 18587db96d56Sopenharmony_cian :term:`iterable`. The iterable is expanded into a sequence of items, 18597db96d56Sopenharmony_ciwhich are included in the new tuple, list, or set, at the site of 18607db96d56Sopenharmony_cithe unpacking. 18617db96d56Sopenharmony_ci 18627db96d56Sopenharmony_ci.. versionadded:: 3.5 18637db96d56Sopenharmony_ci Iterable unpacking in expression lists, originally proposed by :pep:`448`. 18647db96d56Sopenharmony_ci 18657db96d56Sopenharmony_ci.. index:: pair: trailing; comma 18667db96d56Sopenharmony_ci 18677db96d56Sopenharmony_ciThe trailing comma is required only to create a single tuple (a.k.a. a 18687db96d56Sopenharmony_ci*singleton*); it is optional in all other cases. A single expression without a 18697db96d56Sopenharmony_citrailing comma doesn't create a tuple, but rather yields the value of that 18707db96d56Sopenharmony_ciexpression. (To create an empty tuple, use an empty pair of parentheses: 18717db96d56Sopenharmony_ci``()``.) 18727db96d56Sopenharmony_ci 18737db96d56Sopenharmony_ci 18747db96d56Sopenharmony_ci.. _evalorder: 18757db96d56Sopenharmony_ci 18767db96d56Sopenharmony_ciEvaluation order 18777db96d56Sopenharmony_ci================ 18787db96d56Sopenharmony_ci 18797db96d56Sopenharmony_ci.. index:: pair: evaluation; order 18807db96d56Sopenharmony_ci 18817db96d56Sopenharmony_ciPython evaluates expressions from left to right. Notice that while evaluating 18827db96d56Sopenharmony_cian assignment, the right-hand side is evaluated before the left-hand side. 18837db96d56Sopenharmony_ci 18847db96d56Sopenharmony_ciIn the following lines, expressions will be evaluated in the arithmetic order of 18857db96d56Sopenharmony_citheir suffixes:: 18867db96d56Sopenharmony_ci 18877db96d56Sopenharmony_ci expr1, expr2, expr3, expr4 18887db96d56Sopenharmony_ci (expr1, expr2, expr3, expr4) 18897db96d56Sopenharmony_ci {expr1: expr2, expr3: expr4} 18907db96d56Sopenharmony_ci expr1 + expr2 * (expr3 - expr4) 18917db96d56Sopenharmony_ci expr1(expr2, expr3, *expr4, **expr5) 18927db96d56Sopenharmony_ci expr3, expr4 = expr1, expr2 18937db96d56Sopenharmony_ci 18947db96d56Sopenharmony_ci 18957db96d56Sopenharmony_ci.. _operator-summary: 18967db96d56Sopenharmony_ci 18977db96d56Sopenharmony_ciOperator precedence 18987db96d56Sopenharmony_ci=================== 18997db96d56Sopenharmony_ci 19007db96d56Sopenharmony_ci.. index:: 19017db96d56Sopenharmony_ci pair: operator; precedence 19027db96d56Sopenharmony_ci 19037db96d56Sopenharmony_ciThe following table summarizes the operator precedence in Python, from highest 19047db96d56Sopenharmony_ciprecedence (most binding) to lowest precedence (least binding). Operators in 19057db96d56Sopenharmony_cithe same box have the same precedence. Unless the syntax is explicitly given, 19067db96d56Sopenharmony_cioperators are binary. Operators in the same box group left to right (except for 19077db96d56Sopenharmony_ciexponentiation and conditional expressions, which group from right to left). 19087db96d56Sopenharmony_ci 19097db96d56Sopenharmony_ciNote that comparisons, membership tests, and identity tests, all have the same 19107db96d56Sopenharmony_ciprecedence and have a left-to-right chaining feature as described in the 19117db96d56Sopenharmony_ci:ref:`comparisons` section. 19127db96d56Sopenharmony_ci 19137db96d56Sopenharmony_ci 19147db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19157db96d56Sopenharmony_ci| Operator | Description | 19167db96d56Sopenharmony_ci+===============================================+=====================================+ 19177db96d56Sopenharmony_ci| ``(expressions...)``, | Binding or parenthesized | 19187db96d56Sopenharmony_ci| | expression, | 19197db96d56Sopenharmony_ci| ``[expressions...]``, | list display, | 19207db96d56Sopenharmony_ci| ``{key: value...}``, | dictionary display, | 19217db96d56Sopenharmony_ci| ``{expressions...}`` | set display | 19227db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19237db96d56Sopenharmony_ci| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | 19247db96d56Sopenharmony_ci| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | 19257db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19267db96d56Sopenharmony_ci| :keyword:`await x <await>` | Await expression | 19277db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19287db96d56Sopenharmony_ci| ``**`` | Exponentiation [#]_ | 19297db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19307db96d56Sopenharmony_ci| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | 19317db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19327db96d56Sopenharmony_ci| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | 19337db96d56Sopenharmony_ci| | multiplication, division, floor | 19347db96d56Sopenharmony_ci| | division, remainder [#]_ | 19357db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19367db96d56Sopenharmony_ci| ``+``, ``-`` | Addition and subtraction | 19377db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19387db96d56Sopenharmony_ci| ``<<``, ``>>`` | Shifts | 19397db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19407db96d56Sopenharmony_ci| ``&`` | Bitwise AND | 19417db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19427db96d56Sopenharmony_ci| ``^`` | Bitwise XOR | 19437db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19447db96d56Sopenharmony_ci| ``|`` | Bitwise OR | 19457db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19467db96d56Sopenharmony_ci| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | 19477db96d56Sopenharmony_ci| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | 19487db96d56Sopenharmony_ci| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | 19497db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19507db96d56Sopenharmony_ci| :keyword:`not x <not>` | Boolean NOT | 19517db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19527db96d56Sopenharmony_ci| :keyword:`and` | Boolean AND | 19537db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19547db96d56Sopenharmony_ci| :keyword:`or` | Boolean OR | 19557db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19567db96d56Sopenharmony_ci| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression | 19577db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19587db96d56Sopenharmony_ci| :keyword:`lambda` | Lambda expression | 19597db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19607db96d56Sopenharmony_ci| ``:=`` | Assignment expression | 19617db96d56Sopenharmony_ci+-----------------------------------------------+-------------------------------------+ 19627db96d56Sopenharmony_ci 19637db96d56Sopenharmony_ci 19647db96d56Sopenharmony_ci.. rubric:: Footnotes 19657db96d56Sopenharmony_ci 19667db96d56Sopenharmony_ci.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be 19677db96d56Sopenharmony_ci true numerically due to roundoff. For example, and assuming a platform on which 19687db96d56Sopenharmony_ci a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % 19697db96d56Sopenharmony_ci 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + 19707db96d56Sopenharmony_ci 1e100``, which is numerically exactly equal to ``1e100``. The function 19717db96d56Sopenharmony_ci :func:`math.fmod` returns a result whose sign matches the sign of the 19727db96d56Sopenharmony_ci first argument instead, and so returns ``-1e-100`` in this case. Which approach 19737db96d56Sopenharmony_ci is more appropriate depends on the application. 19747db96d56Sopenharmony_ci 19757db96d56Sopenharmony_ci.. [#] If x is very close to an exact integer multiple of y, it's possible for 19767db96d56Sopenharmony_ci ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such 19777db96d56Sopenharmony_ci cases, Python returns the latter result, in order to preserve that 19787db96d56Sopenharmony_ci ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. 19797db96d56Sopenharmony_ci 19807db96d56Sopenharmony_ci.. [#] The Unicode standard distinguishes between :dfn:`code points` 19817db96d56Sopenharmony_ci (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). 19827db96d56Sopenharmony_ci While most abstract characters in Unicode are only represented using one 19837db96d56Sopenharmony_ci code point, there is a number of abstract characters that can in addition be 19847db96d56Sopenharmony_ci represented using a sequence of more than one code point. For example, the 19857db96d56Sopenharmony_ci abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented 19867db96d56Sopenharmony_ci as a single :dfn:`precomposed character` at code position U+00C7, or as a 19877db96d56Sopenharmony_ci sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL 19887db96d56Sopenharmony_ci LETTER C), followed by a :dfn:`combining character` at code position U+0327 19897db96d56Sopenharmony_ci (COMBINING CEDILLA). 19907db96d56Sopenharmony_ci 19917db96d56Sopenharmony_ci The comparison operators on strings compare at the level of Unicode code 19927db96d56Sopenharmony_ci points. This may be counter-intuitive to humans. For example, 19937db96d56Sopenharmony_ci ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings 19947db96d56Sopenharmony_ci represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". 19957db96d56Sopenharmony_ci 19967db96d56Sopenharmony_ci To compare strings at the level of abstract characters (that is, in a way 19977db96d56Sopenharmony_ci intuitive to humans), use :func:`unicodedata.normalize`. 19987db96d56Sopenharmony_ci 19997db96d56Sopenharmony_ci.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of 20007db96d56Sopenharmony_ci descriptors, you may notice seemingly unusual behaviour in certain uses of 20017db96d56Sopenharmony_ci the :keyword:`is` operator, like those involving comparisons between instance 20027db96d56Sopenharmony_ci methods, or constants. Check their documentation for more info. 20037db96d56Sopenharmony_ci 20047db96d56Sopenharmony_ci.. [#] The power operator ``**`` binds less tightly than an arithmetic or 20057db96d56Sopenharmony_ci bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. 20067db96d56Sopenharmony_ci 20077db96d56Sopenharmony_ci.. [#] The ``%`` operator is also used for string formatting; the same 20087db96d56Sopenharmony_ci precedence applies. 2009