• Home
  • Raw
  • Download

Lines Matching +full:is +full:- +full:generator +full:- +full:function

16 .. productionlist:: python-grammar
32 implementation for built-in types works as follows:
34 * If either argument is a complex number, the other is converted to complex;
36 * otherwise, if either argument is a floating point number, the other is
39 * otherwise, both must be integers and no conversion is necessary.
55 also categorized syntactically as atoms. The syntax for atoms is:
57 .. productionlist:: python-grammar
63 .. _atom-identifiers:
66 -------------------
70 An identifier occurring as an atom is a name. See section :ref:`identifiers`
76 When the name is bound to an object, evaluation of the atom yields that object.
77 When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
80 .. _private-name-mangling:
88 or more underscores, it is considered a :dfn:`private name` of that class.
89 Private names are transformed to a longer form before code is generated for
93 to ``_Ham__spam``. This transformation is independent of the syntactical
94 context in which the identifier is used. If the transformed name is extremely
96 If the class name consists only of underscores, no transformation is done.
99 .. _atom-literals:
102 --------
108 .. productionlist:: python-grammar
122 is less important than its value. Multiple evaluations of literals with the
131 -------------------
137 A parenthesized form is an optional expression list enclosed in parentheses:
139 .. productionlist:: python-grammar
157 comma. The exception is the empty tuple, for which parentheses *are*
158 required --- allowing unparenthesized "nothing" in expressions would cause
165 -----------------------------------------
184 .. productionlist:: python-grammar
195 each time the innermost block is reached.
198 the comprehension is executed in a separate implicitly nested scope. This ensures
201 The iterable expression in the leftmost :keyword:`!for` clause is evaluated
215 Since Python 3.6, in an :keyword:`async def` function, an :keyword:`!async for`
217 A comprehension in an :keyword:`!async def` function may consist of either a
222 :keyword:`!await` expressions or other asynchronous comprehensions it is called
224 suspend the execution of the coroutine function in which it appears.
242 -------------
252 A list display is a possibly empty series of expressions enclosed in square
255 .. productionlist:: python-grammar
259 a list of expressions or a comprehension. When a comma-separated list of
260 expressions is supplied, its elements are evaluated from left to right and
261 placed into the list object in that order. When a comprehension is supplied,
262 the list is constructed from the elements resulting from the comprehension.
268 ------------
277 A set display is denoted by curly braces and distinguishable from dictionary
280 .. productionlist:: python-grammar
284 either a sequence of expressions or a comprehension. When a comma-separated
285 list of expressions is supplied, its elements are evaluated from left to right
286 and added to the set object. When a comprehension is supplied, the set is
296 -------------------
307 A dictionary display is a possibly empty series of key/datum pairs enclosed in
310 .. productionlist:: python-grammar
318 If a comma-separated sequence of key/datum pairs is given, they are evaluated
319 from left to right to define the entries of the dictionary: each key object is
329 Its operand must be a :term:`mapping`. Each mapping item is added
338 When the comprehension is run, the resulting key and value elements are inserted
352 and value was not well-defined. In CPython, the value was evaluated before
353 the key. Starting with 3.8, the key is evaluated before the value, as
359 Generator expressions
360 ---------------------
363 pair: generator; expression
364 pair: object; generator
365 single: () (parentheses); generator expression
367 A generator expression is a compact generator notation in parentheses:
369 .. productionlist:: python-grammar
372 A generator expression yields a new generator object. Its syntax is the same as
373 for comprehensions, except that it is enclosed in parentheses instead of
376 Variables used in the generator expression are evaluated lazily when the
377 :meth:`~generator.__next__` method is called for the generator object (in the same
379 leftmost :keyword:`!for` clause is immediately evaluated, so that an error
380 produced by it will be emitted at the point where the generator expression
381 is defined, rather than at the point where the first value is retrieved.
390 To avoid interfering with the expected operation of the generator expression
392 implicitly defined generator.
394 If a generator expression contains either :keyword:`!async for`
395 clauses or :keyword:`await` expressions it is called an
396 :dfn:`asynchronous generator expression`. An asynchronous generator
397 expression returns a new asynchronous generator object,
398 which is an asynchronous iterator (see :ref:`async-iterators`).
401 Asynchronous generator expressions were introduced.
404 Prior to Python 3.7, asynchronous generator expressions could
406 with 3.7, any function can use asynchronous generator expressions.
415 -----------------
421 pair: generator; function
423 .. productionlist:: python-grammar
427 The yield expression is used when defining a :term:`generator` function
428 or an :term:`asynchronous generator` function and
429 thus can only be used in the body of a function definition. Using a yield
430 expression in a function's body causes that function to be a generator function,
431 and using it in an :keyword:`async def` function's body causes that
432 coroutine function to be an asynchronous generator function. For example::
434 def gen(): # defines a generator function
437 async def agen(): # defines an asynchronous generator function
442 implement comprehensions and generator expressions.
446 implement comprehensions and generator expressions.
448 Generator functions are described below, while asynchronous generator
450 :ref:`asynchronous-generator-functions`.
452 When a generator function is called, it returns an iterator known as a
453 generator. That generator then controls the execution of the generator
454 function. The execution starts when one of the generator's methods is called.
455 At that time, the execution proceeds to the first yield expression, where it is
456 suspended again, returning the value of :token:`~python-grammar:expression_list`
457 to the generator's caller,
458 or ``None`` if :token:`~python-grammar:expression_list` is omitted.
459 By suspended, we mean that all local state is
462 When the execution is resumed by calling one of the generator's methods, the
463 function can proceed exactly as if the yield expression were just another
465 method which resumed the execution. If :meth:`~generator.__next__` is used
467 result is :const:`None`. Otherwise, if :meth:`~generator.send` is used, then
472 All of this makes generator functions quite similar to coroutines; they yield
474 suspended. The only difference is that a generator function cannot control
475 where the execution should continue after it yields; the control is always
476 transferred to the generator's caller.
479 generator is not resumed before it is
481 the generator-iterator's :meth:`~generator.close` method will be called,
487 When ``yield from <expr>`` is used, the supplied expression must be an
489 to the caller of the current generator's methods. Any values passed in with
490 :meth:`~generator.send` and any exceptions passed in with
491 :meth:`~generator.throw` are passed to the underlying iterator if it has the
492 appropriate methods. If this is not the case, then :meth:`~generator.send`
494 :meth:`~generator.throw` will just raise the passed in exception immediately.
496 When the underlying iterator is complete, the :attr:`~StopIteration.value`
499 :exc:`StopIteration`, or automatically when the subiterator is a generator
505 The parentheses may be omitted when the yield expression is the sole expression
510 :pep:`255` - Simple Generators
513 :pep:`342` - Coroutines via Enhanced Generators
517 :pep:`380` - Syntax for Delegating to a Subgenerator
518 The proposal to introduce the :token:`~python-grammar:yield_from` syntax,
521 :pep:`525` - Asynchronous Generators
522 The proposal that expanded on :pep:`492` by adding generator capabilities to
525 .. index:: pair: object; generator
526 .. _generator-methods:
528 Generator-iterator methods
531 This subsection describes the methods of a generator iterator. They can
532 be used to control the execution of a generator function.
534 Note that calling any of the generator methods below when the generator
535 is already executing raises a :exc:`ValueError` exception.
540 .. method:: generator.__next__()
542 Starts the execution of a generator function or resumes it at the last
543 executed yield expression. When a generator function is resumed with a
544 :meth:`~generator.__next__` method, the current yield expression always
546 expression, where the generator is suspended again, and the value of the
547 :token:`~python-grammar:expression_list` is returned to :meth:`__next__`'s
548 caller. If the generator exits without yielding another value, a
549 :exc:`StopIteration` exception is raised.
551 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
552 by the built-in :func:`next` function.
555 .. method:: generator.send(value)
557 Resumes the execution and "sends" a value into the generator function. The
559 :meth:`send` method returns the next value yielded by the generator, or
560 raises :exc:`StopIteration` if the generator exits without yielding another
561 value. When :meth:`send` is called to start the generator, it must be called
562 with :const:`None` as the argument, because there is no yield expression that
566 .. method:: generator.throw(value)
567 generator.throw(type[, value[, traceback]])
569 Raises an exception at the point where the generator was paused,
570 and returns the next value yielded by the generator function. If the generator
571 exits without yielding another value, a :exc:`StopIteration` exception is
572 raised. If the generator function does not catch the passed-in exception, or
575 In typical use, this is called with a single exception instance similar to the
576 way the :keyword:`raise` keyword is used.
578 For backwards compatibility, however, the second signature is
581 should be an exception instance. If the *value* is not provided, the
582 *type* constructor is called to get an instance. If *traceback*
583 is provided, it is set on the exception, otherwise any existing
590 .. method:: generator.close()
592 Raises a :exc:`GeneratorExit` at the point where the generator function was
593 paused. If the generator function then exits gracefully, is already closed,
595 returns to its caller. If the generator yields a value, a
596 :exc:`RuntimeError` is raised. If the generator raises any other exception,
597 it is propagated to the caller. :meth:`close` does nothing if the generator
605 Here is a simple example that demonstrates the behavior of generators and
606 generator functions::
609 ... print("Execution starts when 'next()' is called for the first time.")
617 ... print("Don't forget to clean up when 'close()' is called.")
619 >>> generator = echo(1)
620 >>> print(next(generator))
621 Execution starts when 'next()' is called for the first time.
623 >>> print(next(generator))
625 >>> print(generator.send(2))
627 >>> generator.throw(TypeError, "spam")
629 >>> generator.close()
630 Don't forget to clean up when 'close()' is called.
632 For examples using ``yield from``, see :ref:`pep-380` in "What's New in
635 .. _asynchronous-generator-functions:
637 Asynchronous generator functions
640 The presence of a yield expression in a function or method defined using
641 :keyword:`async def` further defines the function as an
642 :term:`asynchronous generator` function.
644 When an asynchronous generator function is called, it returns an
645 asynchronous iterator known as an asynchronous generator object.
646 That object then controls the execution of the generator function.
647 An asynchronous generator object is typically used in an
648 :keyword:`async for` statement in a coroutine function analogously to
649 how a generator object would be used in a :keyword:`for` statement.
651 Calling one of the asynchronous generator's methods returns an :term:`awaitable`
652 object, and the execution starts when this object is awaited on. At that time,
653 the execution proceeds to the first yield expression, where it is suspended
654 again, returning the value of :token:`~python-grammar:expression_list` to the
655 awaiting coroutine. As with a generator, suspension means that all local state
656 is retained, including the current bindings of local variables, the instruction
658 When the execution is resumed by awaiting on the next object returned by the
659 asynchronous generator's methods, the function can proceed exactly as if the
662 :meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if
663 :meth:`~agen.asend` is used, then the result will be the value passed in to that
666 If an asynchronous generator happens to exit early by :keyword:`break`, the caller
667 task being cancelled, or other exceptions, the generator's async cleanup code
669 unexpected context--perhaps after the lifetime of tasks it depends, or
670 during the event loop shutdown when the async-generator garbage collection hook
671 is called.
672 To prevent this, the caller must explicitly close the async generator by calling
673 :meth:`~agen.aclose` method to finalize the generator and ultimately detach it
676 In an asynchronous generator function, yield expressions are allowed anywhere
677 in a :keyword:`try` construct. However, if an asynchronous generator is not
678 resumed before it is finalized (by reaching a zero reference count or by
681 clauses. In this case, it is the responsibility of the event loop or
682 scheduler running the asynchronous generator to call the asynchronous
683 generator-iterator's :meth:`~agen.aclose` method and run the resulting
688 define a *finalizer* function which takes an asynchronous generator-iterator and
691 When first iterated over, an asynchronous generator-iterator will store the
696 The expression ``yield from <expr>`` is a syntax error when used in an
697 asynchronous generator function.
699 .. index:: pair: object; asynchronous-generator
700 .. _asynchronous-generator-methods:
702 Asynchronous generator-iterator methods
705 This subsection describes the methods of an asynchronous generator iterator,
706 which are used to control the execution of a generator function.
714 generator or resumes it at the last executed yield expression. When an
715 asynchronous generator function is resumed with an :meth:`~agen.__anext__`
718 expression. The value of the :token:`~python-grammar:expression_list` of the
719 yield expression is the value of the :exc:`StopIteration` exception raised by
720 the completing coroutine. If the asynchronous generator exits without
725 This method is normally called implicitly by a :keyword:`async for` loop.
731 asynchronous generator. As with the :meth:`~generator.send()` method for a
732 generator, this "sends" a value into the asynchronous generator function,
735 value yielded by the generator as the value of the raised
737 asynchronous generator exits without yielding another value. When
738 :meth:`asend` is called to start the asynchronous
739 generator, it must be called with :const:`None` as the argument,
740 because there is no yield expression that could receive the value.
746 where the asynchronous generator was paused, and returns the next value
747 yielded by the generator function as the value of the raised
748 :exc:`StopIteration` exception. If the asynchronous generator exits
749 without yielding another value, a :exc:`StopAsyncIteration` exception is
751 If the generator function does not catch the passed-in exception, or
752 raises a different exception, then when the awaitable is run that exception
761 the asynchronous generator function at the point where it was paused.
762 If the asynchronous generator function then exits gracefully, is already
766 generator will raise a :exc:`StopAsyncIteration` exception. If the
767 asynchronous generator yields a value, a :exc:`RuntimeError` is raised
768 by the awaitable. If the asynchronous generator raises any other exception,
769 it is propagated to the caller of the awaitable. If the asynchronous
770 generator has already exited due to an exception or normal exit, then
781 syntax is:
783 .. productionlist:: python-grammar
787 .. _attribute-references:
790 --------------------
796 An attribute reference is a primary followed by a period and a name:
798 .. productionlist:: python-grammar
807 references, which most objects do. This object is then asked to produce the
808 attribute whose name is the identifier. This production can be customized by
809 overriding the :meth:`__getattr__` method. If this attribute is not available,
810 the exception :exc:`AttributeError` is raised. Otherwise, the type and value of
811 the object produced is determined by the object. Multiple evaluations of the
818 -------------
833 The subscription of an instance of a :ref:`container class <sequence-types>`
836 :ref:`GenericAlias <types-genericalias>` object.
838 .. productionlist:: python-grammar
841 When an object is subscripted, the interpreter will evaluate the primary and
847 primary is subscripted, the evaluated result of the expression list will be
849 is called instead of ``__getitem__``, see :ref:`classgetitem-versus-getitem`.
855 For built-in objects, there are two types of objects that support subscription
858 1. Mappings. If the primary is a :term:`mapping`, the expression list must
859 evaluate to an object whose value is one of the keys of the mapping, and the
861 An example of a builtin mapping class is the :class:`dict` class.
862 2. Sequences. If the primary is a :term:`sequence`, the expression list must
868 :term:`sequences <sequence>`. However, built-in sequences all provide a :meth:`~object.__getitem__`
870 to the index so that, for example, ``x[-1]`` selects the last item of ``x``. The
872 the sequence, and the subscription selects the item whose index is that value
881 A :class:`string <str>` is a special kind of sequence whose items are
882 *characters*. A character is not a separate data type but a
889 --------
907 .. productionlist:: python-grammar
916 There is ambiguity in the formal syntax here: anything that looks like an
918 interpreted as a slicing. Rather than further complicating the syntax, this is
920 takes priority over the interpretation as a slicing (this is the case if the
928 The semantics for a slicing are as follows. The primary is indexed (using the
930 normal subscription) with a key that is constructed from the slice list, as
931 follows. If the slice list contains at least one comma, the key is a tuple
933 lone slice item is the key. The conversion of a slice item that is an
934 expression is that expression. The conversion of a proper slice is a slice
947 single: = (equals); in function calls
952 -----
954 A call calls a callable object (e.g., a :term:`function`) with a possibly empty
957 .. productionlist:: python-grammar
977 The primary must evaluate to a callable object (user-defined functions, built-in
978 functions, methods of built-in objects, class objects, methods of class
980 argument expressions are evaluated before the call is attempted. Please refer
981 to section :ref:`function` for the syntax of formal :term:`parameter` lists.
986 arguments, as follows. First, a list of unfilled slots is created for the
988 first N slots. Next, for each keyword argument, the identifier is used to
989 determine the corresponding slot (if the identifier is the same as the first
990 formal parameter name, the first slot is used, and so on). If the slot is
991 already filled, a :exc:`TypeError` exception is raised. Otherwise, the
992 argument is placed in the slot, filling it (even if the expression is
995 function definition. (Default values are calculated, once, when the function is
999 slots for which no default value is specified, a :exc:`TypeError` exception is
1000 raised. Otherwise, the list of filled slots is used as the argument list for
1003 .. impl-detail::
1005 An implementation may provide built-in functions whose positional parameters
1007 and which therefore cannot be supplied by keyword. In CPython, this is the
1012 :exc:`TypeError` exception is raised, unless a formal parameter using the syntax
1013 ``*identifier`` is present; in this case, that formal parameter receives a tuple
1018 :exc:`TypeError` exception is raised, unless a formal parameter using the syntax
1019 ``**identifier`` is present; in this case, that formal parameter receives a
1025 single: * (asterisk); in function calls
1026 single: unpacking; in function calls
1028 If the syntax ``*expression`` appears in the function call, ``expression`` must
1032 this is equivalent to a call with M+4 positional arguments *x1*, *x2*,
1035 A consequence of this is that although the ``*expression`` syntax may appear
1036 *after* explicit keyword arguments, it is processed *before* the
1037 keyword arguments (and any ``**expression`` arguments -- see below). So::
1051 It is unusual for both keyword arguments and the ``*expression`` syntax to be
1055 single: **; in function calls
1057 If the syntax ``**expression`` appears in the function call, ``expression`` must
1061 a :exc:`TypeError` exception is raised.
1063 When ``**expression`` is used, each key in this mapping must be
1065 Each value from the mapping is assigned to the first formal parameter
1066 eligible for keyword assignment whose name is equal to the key.
1067 A key need not be a Python identifier (e.g. ``"max-temp °F"`` is acceptable,
1069 If there is no match to a formal parameter
1070 the key-value pair is collected by the ``**`` parameter, if there is one,
1071 or if there is not, a :exc:`TypeError` exception is raised.
1077 Function calls accept any number of ``*`` and ``**`` unpackings,
1083 exception. How this value is computed depends on the type of the callable
1086 If it is---
1088 a user-defined function:
1090 pair: function; call
1091 triple: user-defined; function; call
1092 pair: object; user-defined function
1093 pair: object; function
1095 The code block for the function is executed, passing it the argument list. The
1096 first thing the code block will do is bind the formal parameters to the
1097 arguments; this is described in section :ref:`function`. When the code block
1099 function call.
1101 a built-in function or method:
1103 pair: function; call
1104 pair: built-in function; call
1106 pair: built-in method; call
1107 pair: object; built-in method
1108 pair: object; built-in function
1110 pair: object; function
1112 The result is up to the interpreter; see :ref:`built-in-funcs` for the
1113 descriptions of built-in functions and methods.
1120 A new instance of that class is returned.
1128 The corresponding user-defined function is called, with an argument list that is
1137 The class must define a :meth:`__call__` method; the effect is then the same as
1148 Can only be used inside a :term:`coroutine function`.
1150 .. productionlist:: python-grammar
1166 less tightly than unary operators on its right. The syntax is:
1168 .. productionlist:: python-grammar
1173 for the operands): ``-1**2`` results in ``-1``.
1175 The power operator has the same semantics as the built-in :func:`pow` function,
1178 type, and the result is of that type.
1181 argument is negative; in that case, all arguments are converted to float and a
1182 float result is delivered. For example, ``10**2`` returns ``100``, but
1183 ``10**-2`` returns ``0.01``.
1202 .. productionlist:: python-grammar
1203 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
1208 single: operator; - (minus)
1209 single: - (minus); unary operator
1211 The unary ``-`` (minus) operator yields the negation of its numeric argument; the
1227 argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
1236 :exc:`TypeError` exception is raised.
1247 that some of these operations also apply to certain non-numeric types. Apart
1251 .. productionlist:: python-grammar
1255 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
1265 repetition is performed; a negative repetition factor yields an empty sequence.
1274 The ``@`` (at) operator is intended to be used for matrix multiplication. No
1288 integer; the result is that of mathematical division with the 'floor' function
1305 the result is strictly smaller than the absolute value of the second operand
1310 connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
1313 In addition to performing the modulo operation on numbers, the ``%`` operator is
1314 also overloaded by string objects to perform old-style string formatting (also
1315 known as interpolation). The syntax for string formatting is described in the
1316 Python Library Reference, section :ref:`old-string-formatting`.
1321 function are not defined for complex numbers. Instead, convert to a floating
1322 point number using the :func:`abs` function if appropriate.
1339 single: operator; - (minus)
1340 single: - (minus); binary operator
1342 The ``-`` (subtraction) operator yields the difference of its arguments. The
1360 .. productionlist:: python-grammar
1371 A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left
1372 shift by *n* bits is defined as multiplication with ``pow(2,n)``.
1384 .. productionlist:: python-grammar
1431 Unlike C, all comparison operations in Python have the same priority, which is
1433 C, expressions like ``a < b < c`` have the interpretation that is conventional
1436 .. productionlist:: python-grammar
1439 : | "is" ["not"] | ["not"] "in"
1442 :dfn:`rich comparison methods` may return non-boolean values. In this case
1447 Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1448 ``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1449 cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1452 *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1453 to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1457 *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1460 .. _expressions-value-comparisons:
1463 -----------------
1469 and identity). The value of an object is a rather abstract notion in Python:
1470 For example, there is no canonical access method for an object's value. Also,
1471 there is no requirement that the value of an object should be constructed in a
1473 implement a particular notion of what the value of an object is. One can think
1483 The default behavior for equality comparison (``==`` and ``!=``) is based on
1487 behavior is the desire that all objects should be reflexive (i.e. ``x is y``
1490 A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided;
1491 an attempt raises :exc:`TypeError`. A motivation for this default behavior is
1496 have a sensible definition of object value and value-based equality. Such
1498 of built-in types have done that.
1501 built-in types.
1503 * Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
1510 The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are
1511 special. Any ordered comparison of a number to a not-a-number value is false.
1512 A counter-intuitive implication is that not-a-number values are not equal to
1514 ``x == x`` are all false, while ``x != x`` is true. This behavior is
1518 comparisons for singletons should always be done with ``is`` or ``is not``,
1526 numerical Unicode code points (the result of the built-in function
1538 elements. The built-in containers typically assume identical objects are
1542 Lexicographical comparison between built-in collections works as follows:
1544 - For two collections to compare equal, they must be of the same type, have
1546 equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
1549 - Collections that support order comparison are ordered the same as their
1552 shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
1574 * Most other built-in types have no comparison methods implemented, so they
1577 User-defined classes that customize their comparison behavior should follow
1583 ``x is y`` implies ``x == y``
1597 The following (non-exhaustive) examples illustrate that:
1620 Python does not enforce these consistency rules. In fact, the not-a-number
1626 .. _membership-test-details:
1629 --------------------------
1632 s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
1633 ``x not in s`` returns the negation of ``x in s``. All built-in sequences and
1636 set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
1637 to ``any(x is e or x == e for e in y)``.
1639 For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
1640 substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1644 For user-defined classes which define the :meth:`__contains__` method, ``x in
1648 For user-defined classes which do not define :meth:`__contains__` but do define
1649 :meth:`__iter__`, ``x in y`` is ``True`` if some value ``z``, for which the
1650 expression ``x is z or x == z`` is true, is produced while iterating over ``y``.
1651 If an exception is raised during the iteration, it is as if :keyword:`in` raised
1654 Lastly, the old-style iteration protocol is tried: if a class defines
1655 :meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
1656 integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index
1657 raises the :exc:`IndexError` exception. (If any other exception is raised, it is as
1666 The operator :keyword:`not in` is defined to have the inverse truth value of
1670 pair: operator; is
1671 pair: operator; is not
1679 --------------------
1681 The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x
1682 is y`` is true if and only if *x* and *y* are the same object. An Object's identity
1683 is determined using the :meth:`id` function. ``x is not y`` yields the inverse
1699 .. productionlist:: python-grammar
1708 other values are interpreted as true. User-defined objects can customize their
1713 The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1718 The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1719 returned; otherwise, *y* is evaluated and the resulting value is returned.
1723 The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1724 returned; otherwise, *y* is evaluated and the resulting value is returned.
1728 argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1729 replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1744 .. productionlist:: python-grammar
1748 "walrus") assigns an :token:`~python-grammar:expression` to an
1749 :token:`~python-grammar:identifier`, while also returning the value of the
1750 :token:`~python-grammar:expression`.
1752 One common use case is when handling matched regular expressions:
1754 .. code-block:: python
1761 .. code-block:: python
1767 as sub-expressions in slicing, conditional, lambda,
1768 keyword-argument, and comprehension-if expressions
1788 .. productionlist:: python-grammar
1796 If *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1797 evaluated and its value is returned.
1811 pair: anonymous; function
1814 .. productionlist:: python-grammar
1818 functions. The expression ``lambda parameters: expression`` yields a function
1819 object. The unnamed object behaves like a function object defined with:
1821 .. code-block:: none
1826 See section :ref:`function` for the syntax of parameter lists. Note that
1840 .. productionlist:: python-grammar
1850 the tuple is the number of expressions in the list. The expressions are
1858 an :term:`iterable`. The iterable is expanded into a sequence of items,
1867 The trailing comma is required only to create a single tuple (a.k.a. a
1868 *singleton*); it is optional in all other cases. A single expression without a
1882 an assignment, the right-hand side is evaluated before the left-hand side.
1890 expr1 + expr2 * (expr3 - expr4)
1895 .. _operator-summary:
1905 the same box have the same precedence. Unless the syntax is explicitly given,
1910 precedence and have a left-to-right chaining feature as described in the
1914 +-----------------------------------------------+-------------------------------------+
1922 +-----------------------------------------------+-------------------------------------+
1925 +-----------------------------------------------+-------------------------------------+
1927 +-----------------------------------------------+-------------------------------------+
1929 +-----------------------------------------------+-------------------------------------+
1930 | ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1931 +-----------------------------------------------+-------------------------------------+
1935 +-----------------------------------------------+-------------------------------------+
1936 | ``+``, ``-`` | Addition and subtraction |
1937 +-----------------------------------------------+-------------------------------------+
1939 +-----------------------------------------------+-------------------------------------+
1941 +-----------------------------------------------+-------------------------------------+
1943 +-----------------------------------------------+-------------------------------------+
1945 +-----------------------------------------------+-------------------------------------+
1947 | :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
1949 +-----------------------------------------------+-------------------------------------+
1951 +-----------------------------------------------+-------------------------------------+
1953 +-----------------------------------------------+-------------------------------------+
1955 +-----------------------------------------------+-------------------------------------+
1956 | :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
1957 +-----------------------------------------------+-------------------------------------+
1959 +-----------------------------------------------+-------------------------------------+
1961 +-----------------------------------------------+-------------------------------------+
1966 .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1968 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1969 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1970 1e100``, which is numerically exactly equal to ``1e100``. The function
1972 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1973 is more appropriate depends on the application.
1975 .. [#] If x is very close to an exact integer multiple of y, it's possible for
1976 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
1983 code point, there is a number of abstract characters that can in addition be
1992 points. This may be counter-intuitive to humans. For example,
1993 ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings
1996 To compare strings at the level of abstract characters (that is, in a way
1999 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
2001 the :keyword:`is` operator, like those involving comparisons between instance
2005 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
2007 .. [#] The ``%`` operator is also used for string formatting; the same