diff --git a/Doc/reference/compound_stmts.rst b/Doc/reference/compound_stmts.rst index e95fa3a6424e23..d90e96b68fe21f 100644 --- a/Doc/reference/compound_stmts.rst +++ b/Doc/reference/compound_stmts.rst @@ -7,15 +7,15 @@ Compound statements .. index:: pair: compound; statement Compound statements contain (groups of) other statements; they affect or control -the execution of those other statements in some way. In general, compound +the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line. The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement -traditional control flow constructs. :keyword:`try` specifies exception +traditional control flow constructs. :keyword:`try` specifies exception handlers and/or cleanup code for a group of statements, while the :keyword:`with` statement allows the execution of initialization and -finalization code around a block of code. Function and class definitions are +finalization code around a block of code. Function and class definitions are also syntactically compound statements. .. index:: @@ -23,13 +23,13 @@ also syntactically compound statements. single: suite single: ; (semicolon) -A compound statement consists of one or more 'clauses.' A clause consists of a -header and a 'suite.' The clause headers of a particular compound statement are +A compound statement consists of one or more 'clauses.' A clause consists of a +header and a 'suite.' The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely -identifying keyword and ends with a colon. A suite is a group of statements -controlled by a clause. A suite can be one or more semicolon-separated simple +identifying keyword and ends with a colon. A suite is a group of statements +controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header's colon, or it -can be one or more indented statements on subsequent lines. Only the latter +can be one or more indented statements on subsequent lines. Only the latter form of a suite can contain nested compound statements; the following is illegal, mostly because it wouldn't be clear to which :keyword:`if` clause a following :keyword:`else` clause would belong:: @@ -67,7 +67,7 @@ Summarizing: pair: dangling; else Note that statements always end in a ``NEWLINE`` possibly followed by a -``DEDENT``. Also note that optional continuation clauses always begin with a +``DEDENT``. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the 'dangling :keyword:`else`' problem is solved in Python by requiring nested :keyword:`if` statements to be indented). @@ -99,7 +99,7 @@ The :keyword:`if` statement is used for conditional execution: It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section :ref:`booleans` for the definition of true and false); then that suite is executed (and no other part of the -:keyword:`if` statement is executed or evaluated). If all expressions are +:keyword:`if` statement is executed or evaluated). If all expressions are false, the suite of the :keyword:`else` clause, if present, is executed. @@ -131,7 +131,7 @@ terminates. pair: statement; continue A :keyword:`break` statement executed in the first suite terminates the loop -without executing the :keyword:`!else` clause's suite. A :keyword:`continue` +without executing the :keyword:`!else` clause's suite. A :keyword:`continue` statement executed in the first suite skips the rest of the suite and goes back to testing the expression. @@ -171,7 +171,7 @@ if present, is executed, and the loop terminates. pair: statement; continue A :keyword:`break` statement executed in the first suite terminates the loop -without executing the :keyword:`!else` clause's suite. A :keyword:`continue` +without executing the :keyword:`!else` clause's suite. A :keyword:`continue` statement executed in the first suite skips the rest of the suite and continues with the next item, or with the :keyword:`!else` clause if there is no next item. @@ -191,7 +191,7 @@ those made in the suite of the for-loop:: pair: built-in function; range Names in the target list are not deleted when the loop is finished, but if the -sequence is empty, they will not have been assigned to at all by the loop. Hint: +sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type :func:`range` represents immutable arithmetic sequences of integers. For instance, iterating ``range(3)`` successively yields 0, 1, and then 2. @@ -257,7 +257,7 @@ or to a tuple that contains such a class. If no :keyword:`!except` clause matches the exception, the search for an exception handler -continues in the surrounding code and on the invocation stack. [#]_ +continues in the surrounding code and on the invocation stack. [#]_ If the evaluation of an expression in the header of an :keyword:`!except` clause raises an exception, @@ -279,7 +279,7 @@ and the exception occurs in the :keyword:`!try` clause of the inner handler, the outer handler will not handle the exception.) When an exception has been assigned using ``as target``, it is cleared at the -end of the :keyword:`!except` clause. This is as if :: +end of the :keyword:`!except` clause. This is as if :: except E as N: foo @@ -342,7 +342,7 @@ partial matches when the type matches some of the exceptions in the group. This means that multiple :keyword:`!except*` clauses can execute, each handling part of the exception group. Each clause executes at most once and handles an exception group -of all matching exceptions. Each exception in the group is handled by at most +of all matching exceptions. Each exception in the group is handled by at most one :keyword:`!except*` clause, the first that matches it. :: >>> try: @@ -403,7 +403,7 @@ cannot appear in an :keyword:`!except*` clause. The optional :keyword:`!else` clause is executed if the control flow leaves the :keyword:`try` suite, no exception was raised, and no :keyword:`return`, -:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in +:keyword:`continue`, or :keyword:`break` statement was executed. Exceptions in the :keyword:`!else` clause are not handled by the preceding :keyword:`except` clauses. @@ -415,12 +415,12 @@ clauses. :keyword:`!finally` clause -------------------------- -If :keyword:`!finally` is present, it specifies a 'cleanup' handler. The +If :keyword:`!finally` is present, it specifies a 'cleanup' handler. The :keyword:`try` clause is executed, including any :keyword:`except` and -:keyword:`else` clauses. If an exception occurs in any of the clauses and is +:keyword:`else` clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The :keyword:`!finally` clause -is executed. If there is a saved exception it is re-raised at the end of the -:keyword:`!finally` clause. If the :keyword:`!finally` clause raises another +is executed. If there is a saved exception it is re-raised at the end of the +:keyword:`!finally` clause. If the :keyword:`!finally` clause raises another exception, the saved exception is set as the context of the new exception. If the :keyword:`!finally` clause executes a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement, the saved exception is discarded. For example, @@ -447,7 +447,7 @@ executed in the :keyword:`try` suite of a :keyword:`!try`...\ :keyword:`!finally statement, the :keyword:`!finally` clause is also executed 'on the way out.' The return value of a function is determined by the last :keyword:`return` -statement executed. Since the :keyword:`!finally` clause always executes, a +statement executed. Since the :keyword:`!finally` clause always executes, a :keyword:`!return` statement executed in the :keyword:`!finally` clause will always be the last one executed. The following function returns 'finally'. @@ -516,13 +516,13 @@ The execution of the :keyword:`with` statement with one "item" proceeds as follo #. The suite is executed. -#. The context manager's :meth:`~object.__exit__` method is invoked. If an exception +#. The context manager's :meth:`~object.__exit__` method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to :meth:`~object.__exit__`. Otherwise, three :const:`None` arguments are supplied. If the suite was exited due to an exception, and the return value from the - :meth:`~object.__exit__` method was false, the exception is reraised. If the return + :meth:`~object.__exit__` method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the :keyword:`with` statement. @@ -604,7 +604,7 @@ The :keyword:`!match` statement .. versionadded:: 3.10 -The match statement is used for pattern matching. Syntax: +The match statement is used for pattern matching. Syntax: .. productionlist:: python-grammar match_stmt: 'match' `subject_expr` ":" NEWLINE INDENT `case_block`+ DEDENT @@ -617,12 +617,12 @@ The match statement is used for pattern matching. Syntax: :ref:`soft keywords `. Pattern matching takes a pattern as input (following ``case``) and a subject -value (following ``match``). The pattern (which may contain subpatterns) is -matched against the subject value. The outcomes are: +value (following ``match``). The pattern (which may contain subpatterns) is +matched against the subject value. The outcomes are: * A match success or failure (also termed a pattern success or failure). -* Possible binding of matched values to a name. The prerequisites for this are +* Possible binding of matched values to a name. The prerequisites for this are further discussed below. The ``match`` and ``case`` keywords are :ref:`soft keywords `. @@ -647,15 +647,15 @@ Here's an overview of the logical flow of a match statement: specific rules for success or failure are described below. The match attempt can also bind some or all of the standalone names within the pattern. The precise pattern binding rules vary per pattern type and are - specified below. **Name bindings made during a successful pattern match + specified below. **Name bindings made during a successful pattern match outlive the executed block and can be used after the match statement**. .. note:: - During failed pattern matches, some subpatterns may succeed. Do not - rely on bindings being made for a failed match. Conversely, do not - rely on variables remaining unchanged after a failed match. The exact - behavior is dependent on implementation and may vary. This is an + During failed pattern matches, some subpatterns may succeed. Do not + rely on bindings being made for a failed match. Conversely, do not + rely on variables remaining unchanged after a failed match. The exact + behavior is dependent on implementation and may vary. This is an intentional decision made to allow different implementations to add optimizations. @@ -671,7 +671,7 @@ Here's an overview of the logical flow of a match statement: .. note:: - Users should generally never rely on a pattern being evaluated. Depending on + Users should generally never rely on a pattern being evaluated. Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations. @@ -691,7 +691,7 @@ A sample match statement:: Case 3, y: 200 -In this case, ``if flag`` is a guard. Read more about that in the next section. +In this case, ``if flag`` is a guard. Read more about that in the next section. Guards ------ @@ -702,13 +702,13 @@ Guards guard: "if" `named_expression` A ``guard`` (which is part of the ``case``) must succeed for code inside -the ``case`` block to execute. It takes the form: :keyword:`if` followed by an +the ``case`` block to execute. It takes the form: :keyword:`if` followed by an expression. The logical flow of a ``case`` block with a ``guard`` follows: -#. Check that the pattern in the ``case`` block succeeded. If the pattern +#. Check that the pattern in the ``case`` block succeeded. If the pattern failed, the ``guard`` is not evaluated and the next ``case`` block is checked. @@ -723,7 +723,7 @@ The logical flow of a ``case`` block with a ``guard`` follows: * If the ``guard`` raises an exception during evaluation, the exception bubbles up. -Guards are allowed to have side effects as they are expressions. Guard +Guards are allowed to have side effects as they are expressions. Guard evaluation must proceed from the first to the last case block, one at a time, skipping case blocks whose pattern(s) don't all succeed. (I.e., guard evaluation must happen in order.) Guard evaluation must stop once a case @@ -737,12 +737,12 @@ Irrefutable Case Blocks .. index:: irrefutable case block, case block -An irrefutable case block is a match-all case block. A match statement may have +An irrefutable case block is a match-all case block. A match statement may have at most one irrefutable case block, and it must be last. A case block is considered irrefutable if it has no guard and its pattern is -irrefutable. A pattern is considered irrefutable if we can prove from its -syntax alone that it will always succeed. Only the following patterns are +irrefutable. A pattern is considered irrefutable if we can prove from its +syntax alone that it will always succeed. Only the following patterns are irrefutable: * :ref:`as-patterns` whose left-hand side is irrefutable @@ -789,7 +789,7 @@ The descriptions below will include a description "in simple terms" of what a pa does for illustration purposes (credits to Raymond Hettinger for a document that inspired most of the descriptions). Note that these descriptions are purely for illustration purposes and **may not** reflect -the underlying implementation. Furthermore, they do not cover all valid forms. +the underlying implementation. Furthermore, they do not cover all valid forms. .. _or-patterns: @@ -798,7 +798,7 @@ OR Patterns ^^^^^^^^^^^ An OR pattern is two or more patterns separated by vertical -bars ``|``. Syntax: +bars ``|``. Syntax: .. productionlist:: python-grammar or_pattern: "|".`closed_pattern`+ @@ -807,7 +807,7 @@ Only the final subpattern may be :ref:`irrefutable `, and each subpattern must bind the same set of names to avoid ambiguity. An OR pattern matches each of its subpatterns in turn to the subject value, -until one succeeds. The OR pattern is then considered successful. Otherwise, +until one succeeds. The OR pattern is then considered successful. Otherwise, if none of the subpatterns succeed, the OR pattern fails. In simple terms, ``P1 | P2 | ...`` will try to match ``P1``, if it fails it will try to @@ -819,12 +819,12 @@ AS Patterns ^^^^^^^^^^^ An AS pattern matches an OR pattern on the left of the :keyword:`as` -keyword against a subject. Syntax: +keyword against a subject. Syntax: .. productionlist:: python-grammar as_pattern: `or_pattern` "as" `capture_pattern` -If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds +If the OR pattern fails, the AS pattern fails. Otherwise, the AS pattern binds the subject to the name on the right of the as keyword and succeeds. ``capture_pattern`` cannot be a ``_``. @@ -838,7 +838,7 @@ Literal Patterns ^^^^^^^^^^^^^^^^ A literal pattern corresponds to most -:ref:`literals ` in Python. Syntax: +:ref:`literals ` in Python. Syntax: .. productionlist:: python-grammar literal_pattern: `signed_number` @@ -851,8 +851,8 @@ A literal pattern corresponds to most signed_number: ["-"] NUMBER The rule ``strings`` and the token ``NUMBER`` are defined in the -:doc:`standard Python grammar <./grammar>`. Triple-quoted strings are -supported. Raw strings and byte strings are supported. :ref:`f-strings` are +:doc:`standard Python grammar <./grammar>`. Triple-quoted strings are +supported. Raw strings and byte strings are supported. :ref:`f-strings` are not supported. The forms ``signed_number '+' NUMBER`` and ``signed_number '-' NUMBER`` are @@ -877,10 +877,10 @@ A single underscore ``_`` is not a capture pattern (this is what ``!'_'`` expresses). It is instead treated as a :token:`~python-grammar:wildcard_pattern`. -In a given pattern, a given name can only be bound once. E.g. +In a given pattern, a given name can only be bound once. E.g. ``case x, x: ...`` is invalid while ``case [x] | x: ...`` is allowed. -Capture patterns always succeed. The binding follows scoping rules +Capture patterns always succeed. The binding follows scoping rules established by the assignment expression operator in :pep:`572`; the name becomes a local variable in the closest containing function scope unless there's an applicable :keyword:`global` or :keyword:`nonlocal` statement. @@ -893,13 +893,13 @@ Wildcard Patterns ^^^^^^^^^^^^^^^^^ A wildcard pattern always succeeds (matches anything) -and binds no name. Syntax: +and binds no name. Syntax: .. productionlist:: python-grammar wildcard_pattern: '_' ``_`` is a :ref:`soft keyword ` within any pattern, -but only within patterns. It is an identifier, as usual, even within +but only within patterns. It is an identifier, as usual, even within ``match`` subject expressions, ``guard``\ s, and ``case`` blocks. In simple terms, ``_`` will always succeed. @@ -918,7 +918,7 @@ Syntax: name_or_attr: `attr` | NAME The dotted name in the pattern is looked up using standard Python -:ref:`name resolution rules `. The pattern succeeds if the +:ref:`name resolution rules `. The pattern succeeds if the value found compares equal to the subject value (using the ``==`` equality operator). @@ -928,7 +928,7 @@ In simple terms ``NAME1.NAME2`` will succeed only if `` == NAME1.NAME2` If the same value occurs multiple times in the same match statement, the interpreter may cache the first value found and reuse it rather than repeat - the same lookup. This cache is strictly tied to a given execution of a + the same lookup. This cache is strictly tied to a given execution of a given match statement. .. _group-patterns: @@ -937,7 +937,7 @@ Group Patterns ^^^^^^^^^^^^^^ A group pattern allows users to add parentheses around patterns to -emphasize the intended grouping. Otherwise, it has no additional syntax. +emphasize the intended grouping. Otherwise, it has no additional syntax. Syntax: .. productionlist:: python-grammar @@ -961,7 +961,7 @@ The syntax is similar to the unpacking of a list or tuple. maybe_star_pattern: `star_pattern` | `pattern` star_pattern: "*" (`capture_pattern` | `wildcard_pattern`) -There is no difference if parentheses or square brackets +There is no difference if parentheses or square brackets are used for sequence patterns (i.e. ``(...)`` vs ``[...]`` ). .. note:: @@ -970,7 +970,7 @@ are used for sequence patterns (i.e. ``(...)`` vs ``[...]`` ). While a single pattern enclosed in square brackets (e.g. ``[3 | 4]``) is still a sequence pattern. -At most one star subpattern may be in a sequence pattern. The star subpattern +At most one star subpattern may be in a sequence pattern. The star subpattern may occur in any position. If no star subpattern is present, the sequence pattern is a fixed-length sequence pattern; otherwise it is a variable-length sequence pattern. @@ -993,8 +993,8 @@ subject value: subpatterns, the sequence pattern fails #. Subpatterns in the sequence pattern are matched to their corresponding - items in the subject sequence from left to right. Matching stops as soon - as a subpattern fails. If all subpatterns succeed in matching their + items in the subject sequence from left to right. Matching stops as soon + as a subpattern fails. If all subpatterns succeed in matching their corresponding item, the sequence pattern succeeds. Otherwise, if the sequence pattern is variable-length: @@ -1013,7 +1013,7 @@ subject value: items, as for a fixed-length sequence. .. note:: The length of the subject sequence is obtained via - :func:`len` (i.e. via the :meth:`__len__` protocol). This length may be + :func:`len` (i.e. via the :meth:`__len__` protocol). This length may be cached by the interpreter in a similar manner as :ref:`value patterns `. @@ -1032,7 +1032,7 @@ happens: Mapping Patterns ^^^^^^^^^^^^^^^^ -A mapping pattern contains one or more key-value patterns. The syntax is +A mapping pattern contains one or more key-value patterns. The syntax is similar to the construction of a dictionary. Syntax: @@ -1043,7 +1043,7 @@ Syntax: : | `double_star_pattern` double_star_pattern: "**" `capture_pattern` -At most one double star pattern may be in a mapping pattern. The double star +At most one double star pattern may be in a mapping pattern. The double star pattern must be the last subpattern in the mapping pattern. Duplicate keys in mapping patterns are disallowed. Duplicate literal keys will @@ -1064,7 +1064,7 @@ subject value: values; or a :exc:`ValueError` for named keys of the same value. .. note:: Key-value pairs are matched using the two-argument form of the mapping - subject's ``get()`` method. Matched key-value pairs must already be present + subject's ``get()`` method. Matched key-value pairs must already be present in the mapping, and not created on-the-fly via :meth:`__missing__` or :meth:`~object.__getitem__`. @@ -1083,7 +1083,7 @@ Class Patterns ^^^^^^^^^^^^^^ A class pattern represents a class and its positional and keyword arguments -(if any). Syntax: +(if any). Syntax: .. productionlist:: python-grammar class_pattern: `name_or_attr` "(" [`pattern_arguments` ","?] ")" @@ -1104,7 +1104,7 @@ subject value: #. If the subject value is not an instance of ``name_or_attr`` (tested via :func:`isinstance`), the class pattern fails. -#. If no pattern arguments are present, the pattern succeeds. Otherwise, +#. If no pattern arguments are present, the pattern succeeds. Otherwise, the subsequent steps depend on whether keyword or positional argument patterns are present. @@ -1123,7 +1123,7 @@ subject value: * If this raises :exc:`AttributeError`, the class pattern has failed. * Else, the subpattern associated with the keyword pattern is matched - against the subject's attribute value. If this fails, the class + against the subject's attribute value. If this fails, the class pattern fails; if this succeeds, the match proceeds to the next keyword. @@ -1144,7 +1144,7 @@ subject value: :exc:`TypeError` is raised. * Otherwise, positional pattern ``i`` is converted to a keyword pattern - using ``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must + using ``__match_args__[i]`` as the keyword. ``__match_args__[i]`` must be a string; if not :exc:`TypeError` is raised. * If there are duplicate keywords, :exc:`TypeError` is raised. @@ -1234,9 +1234,9 @@ A function definition defines a user-defined function object (see section funcname: `identifier` -A function definition is an executable statement. Its execution binds the +A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper -around the executable code for the function). This function object contains a +around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called. @@ -1248,9 +1248,9 @@ only when the function is called. [#]_ A function definition may be wrapped by one or more :term:`decorator` expressions. Decorator expressions are evaluated when the function is defined, in the scope -that contains the function definition. The result must be a callable, which is +that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is -bound to the function name instead of the function object. Multiple decorators +bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code :: @f1(arg) @@ -1285,20 +1285,20 @@ attribute. See :ref:`generic-functions` for more. single: = (equals); function definition When one or more :term:`parameters ` have the form *parameter* ``=`` -*expression*, the function is said to have "default parameter values." For a +*expression*, the function is said to have "default parameter values." For a parameter with a default value, the corresponding :term:`argument` may be omitted from a call, in which -case the parameter's default value is substituted. If a parameter has a default +case the parameter's default value is substituted. If a parameter has a default value, all following parameters up until the "``*``" must also have a default value --- this is a syntactic restriction that is not expressed by the grammar. **Default parameter values are evaluated from left to right when the function definition is executed.** This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each -call. This is especially important to understand when a default parameter value is a +call. This is especially important to understand when a default parameter value is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default parameter value is in effect -modified. This is generally not what was intended. A way around this is to use +modified. This is generally not what was intended. A way around this is to use ``None`` as the default, and explicitly test for it in the body of the function, e.g.:: @@ -1316,13 +1316,13 @@ e.g.:: Function call semantics are described in more detail in section :ref:`calls`. A function call always assigns values to all parameters mentioned in the parameter list, either from positional arguments, from keyword arguments, or from default -values. If the form "``*identifier``" is present, it is initialized to a tuple +values. If the form "``*identifier``" is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form "``**identifier``" is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a -new empty mapping of the same type. Parameters after "``*``" or +new empty mapping of the same type. Parameters after "``*``" or "``*identifier``" are keyword-only parameters and may only be passed -by keyword arguments. Parameters before "``/``" are positional-only parameters +by keyword arguments. Parameters before "``/``" are positional-only parameters and may only be passed by positional arguments. .. versionchanged:: 3.8 @@ -1335,11 +1335,11 @@ and may only be passed by positional arguments. single: : (colon); function annotations Parameters may have an :term:`annotation ` of the form "``: expression``" -following the parameter name. Any parameter may have an annotation, even those of the form +following the parameter name. Any parameter may have an annotation, even those of the form ``*identifier`` or ``**identifier``. (As a special case, parameters of the form ``*identifier`` may have an annotation "``: *expression``".) Functions may have "return" annotation of -the form "``-> expression``" after the parameter list. These annotations can be -any valid Python expression. The presence of annotations does not change the +the form "``-> expression``" after the parameter list. These annotations can be +any valid Python expression. The presence of annotations does not change the semantics of a function. See :ref:`annotations` for more information on annotations. .. versionchanged:: 3.11 @@ -1349,17 +1349,17 @@ semantics of a function. See :ref:`annotations` for more information on annotati .. index:: pair: lambda; expression It is also possible to create anonymous functions (functions not bound to a -name), for immediate use in expressions. This uses lambda expressions, described in -section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a +name), for immediate use in expressions. This uses lambda expressions, described in +section :ref:`lambda`. Note that the lambda expression is merely a shorthand for a simplified function definition; a function defined in a ":keyword:`def`" statement can be passed around or assigned to another name just like a function -defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful +defined by a lambda expression. The ":keyword:`!def`" form is actually more powerful since it allows the execution of multiple statements and annotations. -**Programmer's note:** Functions are first-class objects. A "``def``" statement +**Programmer's note:** Functions are first-class objects. A "``def``" statement executed inside a function definition defines a local function that can be -returned or passed around. Free variables used in the nested function can -access the local variables of the function containing the def. See section +returned or passed around. Free variables used in the nested function can +access the local variables of the function containing the def. See section :ref:`naming` for details. .. seealso:: @@ -1407,10 +1407,10 @@ A class definition defines a class object (see section :ref:`types`): inheritance: "(" [`argument_list`] ")" classname: `identifier` -A class definition is an executable statement. The inheritance list usually +A class definition is an executable statement. The inheritance list usually gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so each item in the list should evaluate to a class object which allows -subclassing. Classes without an inheritance list inherit, by default, from the +subclassing. Classes without an inheritance list inherit, by default, from the base class :class:`object`; hence, :: class Foo: @@ -1423,15 +1423,15 @@ is equivalent to :: The class's suite is then executed in a new execution frame (see :ref:`naming`), using a newly created local namespace and the original global namespace. -(Usually, the suite contains mostly function definitions.) When the class's +(Usually, the suite contains mostly function definitions.) When the class's suite finishes execution, its execution frame is discarded but its local namespace is saved. [#]_ A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute -dictionary. The class name is bound to this class object in the original local +dictionary. The class name is bound to this class object in the original local namespace. The order in which attributes are defined in the class body is preserved -in the new class's :attr:`~type.__dict__`. Note that this is reliable only right +in the new class's :attr:`~type.__dict__`. Note that this is reliable only right after the class is created and only for classes that were defined using the definition syntax. @@ -1452,7 +1452,7 @@ is roughly equivalent to :: Foo = f1(arg)(f2(Foo)) The evaluation rules for the decorator expressions are the same as for function -decorators. The result is then bound to the class name. +decorators. The result is then bound to the class name. .. versionchanged:: 3.9 Classes may be decorated with any valid @@ -1469,12 +1469,12 @@ the type parameters can be retrieved from the class's Type parameter lists are new in Python 3.12. **Programmer's note:** Variables defined in the class definition are class -attributes; they are shared by instances. Instance attributes can be set in a -method with ``self.name = value``. Both class and instance attributes are +attributes; they are shared by instances. Instance attributes can be set in a +method with ``self.name = value``. Both class and instance attributes are accessible through the notation "``self.name``", and an instance attribute hides -a class attribute with the same name when accessed in this way. Class +a class attribute with the same name when accessed in this way. Class attributes can be used as defaults for instance attributes, but using mutable -values there can lead to unexpected results. :ref:`Descriptors ` +values there can lead to unexpected results. :ref:`Descriptors ` can be used to create instance variables with different implementation details. @@ -1486,7 +1486,7 @@ can be used to create instance variables with different implementation details. constructed. :pep:`3129` - Class Decorators - The proposal that added class decorators. Function and method decorators + The proposal that added class decorators. Function and method decorators were introduced in :pep:`318`. diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 4a099e81daccb3..825698530f4eac 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -15,7 +15,7 @@ Objects, values and types single: object single: data -:dfn:`Objects` are Python's abstraction for data. All data in a Python program +:dfn:`Objects` are Python's abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann's model of a "stored program computer", code is also represented by objects.) @@ -32,9 +32,9 @@ represented by objects.) .. XXX it *is* now possible in some cases to change an object's type, under certain controlled conditions -Every object has an identity, a type and a value. An object's *identity* never +Every object has an identity, a type and a value. An object's *identity* never changes once it has been created; you may think of it as the object's address in -memory. The :keyword:`is` operator compares the identity of two objects; the +memory. The :keyword:`is` operator compares the identity of two objects; the :func:`id` function returns an integer representing its identity. .. impl-detail:: @@ -43,16 +43,16 @@ memory. The :keyword:`is` operator compares the identity of two objects; the An object's type determines the operations that the object supports (e.g., "does it have a length?") and also defines the possible values for objects of that -type. The :func:`type` function returns an object's type (which is an object -itself). Like its identity, an object's :dfn:`type` is also unchangeable. +type. The :func:`type` function returns an object's type (which is an object +itself). Like its identity, an object's :dfn:`type` is also unchangeable. [#]_ -The *value* of some objects can change. Objects whose value can +The *value* of some objects can change. Objects whose value can change are said to be *mutable*; objects whose value is unchangeable once they are created are called *immutable*. (The value of an immutable container object that contains a reference to a mutable object can change when the latter's value is changed; however the container is still considered immutable, because the -collection of objects it contains cannot be changed. So, immutability is not +collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object's mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable. @@ -63,7 +63,7 @@ and tuples are immutable, while dictionaries and lists are mutable. single: unreachable object Objects are never explicitly destroyed; however, when they become unreachable -they may be garbage-collected. An implementation is allowed to postpone garbage +they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether --- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. @@ -73,7 +73,7 @@ are still reachable. CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage - containing circular references. See the documentation of the :mod:`gc` + containing circular references. See the documentation of the :mod:`gc` module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become @@ -85,25 +85,25 @@ an exception with a :keyword:`try`...\ :keyword:`except` statement may keep objects alive. Some objects contain references to "external" resources such as open files or -windows. It is understood that these resources are freed when the object is +windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a :meth:`!close` method. Programs are strongly recommended to explicitly -close such objects. The :keyword:`try`...\ :keyword:`finally` statement +close such objects. The :keyword:`try`...\ :keyword:`finally` statement and the :keyword:`with` statement provide convenient ways to do this. .. index:: single: container Some objects contain references to other objects; these are called *containers*. -Examples of containers are tuples, lists and dictionaries. The references are -part of a container's value. In most cases, when we talk about the value of a +Examples of containers are tuples, lists and dictionaries. The references are +part of a container's value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities -of the immediately contained objects are implied. So, if an immutable container +of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed. -Types affect almost all aspects of object behavior. Even the importance of +Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. @@ -130,9 +130,9 @@ The standard type hierarchy pair: extension; module pair: C; language -Below is a list of the types that are built into Python. Extension modules +Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can -define additional types. Future versions of Python may add types to the type +define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), although such additions will often be provided via the standard library instead. @@ -142,8 +142,8 @@ although such additions will often be provided via the standard library instead. triple: generic; special; attribute Some of the type descriptions below contain a paragraph listing 'special -attributes.' These are attributes that provide access to the implementation and -are not intended for general use. Their definition may change in the future. +attributes.' These are attributes that provide access to the implementation and +are not intended for general use. Their definition may change in the future. None @@ -151,7 +151,7 @@ None .. index:: pair: object; None -This type has a single value. There is a single object with this value. This +This type has a single value. There is a single object with this value. This object is accessed through the built-in name ``None``. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don't explicitly return anything. Its truth value is false. @@ -162,11 +162,11 @@ NotImplemented .. index:: pair: object; NotImplemented -This type has a single value. There is a single object with this value. This +This type has a single value. There is a single object with this value. This object is accessed through the built-in name :data:`NotImplemented`. Numeric methods and rich comparison methods should return this value if they do not implement the -operation for the operands provided. (The interpreter will then try the -reflected operation, or some other fallback, depending on the operator.) It +operation for the operands provided. (The interpreter will then try the +reflected operation, or some other fallback, depending on the operator.) It should not be evaluated in a boolean context. See @@ -188,9 +188,9 @@ Ellipsis pair: object; Ellipsis single: ...; ellipsis literal -This type has a single value. There is a single object with this value. This +This type has a single value. There is a single object with this value. This object is accessed through the literal ``...`` or the built-in name -``Ellipsis``. Its truth value is true. +``Ellipsis``. Its truth value is true. :class:`numbers.Number` @@ -199,8 +199,8 @@ object is accessed through the literal ``...`` or the built-in name .. index:: pair: object; numeric These are created by numeric literals and returned as results by arithmetic -operators and arithmetic built-in functions. Numeric objects are immutable; -once created their value never changes. Python numbers are of course strongly +operators and arithmetic built-in functions. Numeric objects are immutable; +once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers. @@ -244,7 +244,7 @@ There are two types of integers: Integers (:class:`int`) These represent numbers in an unlimited range, subject to available (virtual) - memory only. For the purpose of shift and mask operations, a binary + memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left. @@ -255,7 +255,7 @@ Booleans (:class:`bool`) single: False single: True - These represent the truth values False and True. The two objects representing + These represent the truth values False and True. The two objects representing the values ``False`` and ``True`` are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to @@ -290,7 +290,7 @@ language with two kinds of floating-point numbers. pair: complex; number These represent complex numbers as a pair of machine-level double precision -floating-point numbers. The same caveats apply as for floating-point numbers. +floating-point numbers. The same caveats apply as for floating-point numbers. The real and imaginary parts of a complex number ``z`` can be retrieved through the read-only attributes ``z.real`` and ``z.imag``. @@ -308,7 +308,7 @@ Sequences These represent finite ordered sets indexed by non-negative numbers. The built-in function :func:`len` returns the number of items of a sequence. When the length of a sequence is *n*, the index set contains the numbers 0, 1, -..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``. Some sequences, +..., *n*-1. Item *i* of sequence *a* is selected by ``a[i]``. Some sequences, including built-in sequences, interpret negative subscripts by adding the sequence length. For example, ``a[-2]`` equals ``a[n-2]``, the second to last item of sequence a with length ``n``. @@ -316,7 +316,7 @@ item of sequence a with length ``n``. .. index:: single: slicing Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such -that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a +that *i* ``<=`` *k* ``<`` *j*. When used as an expression, a slice is a sequence of the same type. The comment above about negative indexes also applies to negative slice positions. @@ -334,7 +334,7 @@ Immutable sequences pair: object; immutable sequence pair: object; immutable -An object of an immutable sequence type cannot change once it is created. (If +An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.) @@ -354,9 +354,9 @@ Strings A string is a sequence of values that represent Unicode code points. All the code points in the range ``U+0000 - U+10FFFF`` can be - represented in a string. Python doesn't have a :c:expr:`char` type; + represented in a string. Python doesn't have a :c:expr:`char` type; instead, every code point in the string is represented as a string - object with length ``1``. The built-in function :func:`ord` + object with length ``1``. The built-in function :func:`ord` converts a code point from its string form to an integer in the range ``0 - 10FFFF``; :func:`chr` converts an integer in the range ``0 - 10FFFF`` to the corresponding length ``1`` string object. @@ -371,19 +371,19 @@ Tuples pair: empty; tuple The items of a tuple are arbitrary Python objects. Tuples of two or - more items are formed by comma-separated lists of expressions. A tuple + more items are formed by comma-separated lists of expressions. A tuple of one item (a 'singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since - parentheses must be usable for grouping of expressions). An empty + parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses. Bytes .. index:: bytes, byte - A bytes object is an immutable array. The items are 8-bit bytes, - represented by integers in the range 0 <= x < 256. Bytes literals + A bytes object is an immutable array. The items are 8-bit bytes, + represented by integers in the range 0 <= x < 256. Bytes literals (like ``b'abc'``) and the built-in :func:`bytes` constructor - can be used to create bytes objects. Also, bytes objects can be + can be used to create bytes objects. Also, bytes objects can be decoded to strings via the :meth:`~bytes.decode` method. @@ -397,7 +397,7 @@ Mutable sequences single: subscription single: slicing -Mutable sequences can be changed after they are created. The subscription and +Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and :keyword:`del` (delete) statements. @@ -413,7 +413,7 @@ There are currently two intrinsic mutable sequence types: Lists .. index:: pair: object; list - The items of a list are arbitrary Python objects. Lists are formed by + The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.) @@ -421,7 +421,7 @@ Byte Arrays .. index:: bytearray A bytearray object is a mutable array. They are created by the built-in - :func:`bytearray` constructor. Aside from being mutable + :func:`bytearray` constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable :class:`bytes` objects. @@ -459,8 +459,8 @@ Sets Frozen sets .. index:: pair: object; frozenset - These represent an immutable set. They are created by the built-in - :func:`frozenset` constructor. As a frozenset is immutable and + These represent an immutable set. They are created by the built-in + :func:`frozenset` constructor. As a frozenset is immutable and :term:`hashable`, it can be used again as an element of another set, or as a dictionary key. @@ -487,7 +487,7 @@ Dictionaries .. index:: pair: object; dictionary -These represent finite sets of objects indexed by nearly arbitrary values. The +These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of @@ -542,7 +542,7 @@ User-defined functions pair: object; user-defined function A user-defined function object is created by a function definition (see -section :ref:`function`). It should be called with an argument list +section :ref:`function`). It should be called with an argument list containing the same number of items as the function's formal parameter list. @@ -654,7 +654,7 @@ Most of these attributes check the type of the assigned value: .. versionadded:: 3.12 Function objects also support getting and setting arbitrary attributes, which -can be used, for example, to attach metadata to functions. Regular attribute +can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. .. impl-detail:: @@ -727,7 +727,7 @@ user-defined :ref:`function object ` or a When an instance method object is created by retrieving a user-defined :ref:`function object ` from a class via one of its instances, its :attr:`~method.__self__` attribute is the instance, and the -method object is said to be *bound*. The new method's :attr:`~method.__func__` +method object is said to be *bound*. The new method's :attr:`~method.__func__` attribute is the original function object. When an instance method object is created by retrieving a :class:`classmethod` @@ -737,7 +737,7 @@ underlying the class method. When an instance method object is called, the underlying function (:attr:`~method.__func__`) is called, inserting the class instance -(:attr:`~method.__self__`) in front of the argument list. For instance, when +(:attr:`~method.__self__`) in front of the argument list. For instance, when :class:`!C` is a class which contains a definition for a function :meth:`!f`, and ``x`` is an instance of :class:`!C`, calling ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``. @@ -761,11 +761,11 @@ Generator functions single: generator; iterator A function or method which uses the :keyword:`yield` statement (see section -:ref:`yield`) is called a :dfn:`generator function`. Such a function, when +:ref:`yield`) is called a :dfn:`generator function`. Such a function, when called, always returns an :term:`iterator` object which can be used to -execute the body of the function: calling the iterator's +execute the body of the function: calling the iterator's :meth:`iterator.__next__` method will cause the function to execute until -it provides a value using the :keyword:`!yield` statement. When the +it provides a value using the :keyword:`!yield` statement. When the function executes a :keyword:`return` statement or falls off the end, a :exc:`StopIteration` exception is raised and the iterator will have reached the end of the set of values to be returned. @@ -778,8 +778,8 @@ Coroutine functions single: coroutine; function A function or method which is defined using :keyword:`async def` is called -a :dfn:`coroutine function`. Such a function, when called, returns a -:term:`coroutine` object. It may contain :keyword:`await` expressions, +a :dfn:`coroutine function`. Such a function, when called, returns a +:term:`coroutine` object. It may contain :keyword:`await` expressions, as well as :keyword:`async with` and :keyword:`async for` statements. See also the :ref:`coroutine-objects` section. @@ -793,7 +793,7 @@ Asynchronous generator functions A function or method which is defined using :keyword:`async def` and which uses the :keyword:`yield` statement is called a -:dfn:`asynchronous generator function`. Such a function, when called, +:dfn:`asynchronous generator function`. Such a function, when called, returns an :term:`asynchronous iterator` object which can be used in an :keyword:`async for` statement to execute the body of the function. @@ -801,7 +801,7 @@ Calling the asynchronous iterator's :meth:`aiterator.__anext__ ` method will return an :term:`awaitable` which when awaited will execute until it provides a value using the :keyword:`yield` -expression. When the function executes an empty :keyword:`return` +expression. When the function executes an empty :keyword:`return` statement or falls off the end, a :exc:`StopAsyncIteration` exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded. @@ -817,7 +817,7 @@ Built-in functions pair: object; function pair: C; language -A built-in function object is a wrapper around a C function. Examples of +A built-in function object is a wrapper around a C function. Examples of built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: @@ -842,7 +842,7 @@ Built-in methods pair: built-in; method This is really a different disguise of a built-in function, this time containing -an object passed to the C function as an implicit extra argument. An example of +an object passed to the C function as an implicit extra argument. An example of a built-in method is ``alist.append()``, assuming *alist* is a list object. In this case, the special read-only attribute :attr:`!__self__` is set to the object denoted by *alist*. (The attribute has the same semantics as it does with @@ -853,9 +853,9 @@ denoted by *alist*. (The attribute has the same semantics as it does with Classes ^^^^^^^ -Classes are callable. These objects normally act as factories for new +Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that -override :meth:`~object.__new__`. The arguments of the call are passed to +override :meth:`~object.__new__`. The arguments of the call are passed to :meth:`!__new__` and, in the typical case, to :meth:`~object.__init__` to initialize the new instance. @@ -880,10 +880,10 @@ Modules are a basic organizational unit of Python code, and are created by the :ref:`import system ` as invoked either by the :keyword:`import` statement, or by calling functions such as :func:`importlib.import_module` and built-in -:func:`__import__`. A module object has a namespace implemented by a +:func:`__import__`. A module object has a namespace implemented by a :class:`dictionary ` object (this is the dictionary referenced by the :attr:`~function.__globals__` -attribute of functions defined in the module). Attribute references are +attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., ``m.x`` is equivalent to ``m.__dict__["x"]``. A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is @@ -1063,16 +1063,16 @@ this approach. has no semantic meaning (for example, a module loaded from a database). If :attr:`!__file__` is set then the :attr:`!__cached__` attribute might - also be set, which is the path to any compiled version of + also be set, which is the path to any compiled version of the code (for example, a byte-compiled file). The file does not need to exist to set this attribute; the path can simply point to where the compiled file *would* exist (see :pep:`3147`). Note that :attr:`!__cached__` may be set even if :attr:`!__file__` is not - set. However, that scenario is quite atypical. Ultimately, the + set. However, that scenario is quite atypical. Ultimately, the :term:`loader` is what makes use of the module spec provided by the :term:`finder` (from which :attr:`!__file__` and :attr:`!__cached__` are - derived). So if a loader can load from a cached module but otherwise does + derived). So if a loader can load from a cached module but otherwise does not load from a file, that atypical scenario may be appropriate. It is **strongly** recommended that you use @@ -1099,7 +1099,7 @@ the following writable attributes: .. attribute:: module.__annotations__ A dictionary containing :term:`variable annotations ` - collected during module body execution. For best practices on working with + collected during module body execution. For best practices on working with :attr:`!__annotations__`, see :mod:`annotationlib`. .. versionchanged:: 3.14 @@ -1129,7 +1129,7 @@ Module objects also have the following special read-only attribute: Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the - dictionary still has live references. To avoid this, copy the dictionary + dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly. @@ -1139,7 +1139,7 @@ Custom classes -------------- Custom class types are typically created by class definitions (see section -:ref:`class`). A class has a namespace implemented by a dictionary object. +:ref:`class`). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., ``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of hooks which allow for other means of locating attributes). When the attribute @@ -1291,7 +1291,7 @@ have the following two methods available: .. method:: type.mro This method can be overridden by a metaclass to customize the method - resolution order for its instances. It is called at class instantiation, + resolution order for its instances. It is called at class instantiation, and its result is stored in :attr:`~type.__mro__`. .. method:: type.__subclasses__ @@ -1316,24 +1316,24 @@ Class instances pair: class; instance pair: class instance; attribute -A class instance is created by calling a class object (see above). A class +A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place -in which attribute references are searched. When an attribute is not found +in which attribute references are searched. When an attribute is not found there, and the instance's class has an attribute by that name, the search -continues with the class attributes. If a class attribute is found that is a +continues with the class attributes. If a class attribute is found that is a user-defined function object, it is transformed into an instance method -object whose :attr:`~method.__self__` attribute is the instance. Static method and -class method objects are also transformed; see above under "Classes". See +object whose :attr:`~method.__self__` attribute is the instance. Static method and +class method objects are also transformed; see above under "Classes". See section :ref:`descriptors` for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in -the class's :attr:`~object.__dict__`. If no class attribute is found, and the +the class's :attr:`~object.__dict__`. If no class attribute is found, and the object's class has a :meth:`~object.__getattr__` method, that is called to satisfy the lookup. .. index:: triple: class instance; attribute; assignment Attribute assignments and deletions update the instance's dictionary, never a -class's dictionary. If the class has a :meth:`~object.__setattr__` or +class's dictionary. If the class has a :meth:`~object.__setattr__` or :meth:`~object.__delattr__` method, this is called instead of updating the instance dictionary directly. @@ -1343,7 +1343,7 @@ dictionary directly. pair: object; mapping Class instances can pretend to be numbers, sequences, or mappings if they have -methods with certain special names. See section :ref:`specialnames`. +methods with certain special names. See section :ref:`specialnames`. Special attributes ^^^^^^^^^^^^^^^^^^ @@ -1379,7 +1379,7 @@ I/O objects (also known as file objects) single: stdout (in module sys) single: stderr (in module sys) -A :term:`file object` represents an open file. Various shortcuts are +A :term:`file object` represents an open file. Various shortcuts are available to create file objects: the :func:`open` built-in function, and also :func:`os.popen`, :func:`os.fdopen`, and the :meth:`~socket.socket.makefile` method of socket objects (and perhaps by @@ -1416,7 +1416,7 @@ The difference between a code object and a function object is that the function object contains an explicit reference to the function's globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object -(because they represent values calculated at run-time). Unlike function +(because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects. @@ -1627,7 +1627,7 @@ Frame objects .. index:: pair: object; frame -Frame objects represent execution frames. They may occur in +Frame objects represent execution frames. They may occur in :ref:`traceback objects `, and are also passed to registered trace functions. @@ -1704,7 +1704,7 @@ Special writable attributes * - .. attribute:: frame.f_lineno - The current line number of the frame -- writing to this from within a trace function jumps to the given line (only for the bottom-most - frame). A debugger can implement a Jump command (aka Set Next Statement) + frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to this attribute. Frame object methods @@ -1715,8 +1715,8 @@ Frame objects support one method: .. method:: frame.clear() This method clears all references to :ref:`local variables ` held by the - frame. Also, if the frame belonged to a :term:`generator`, the generator - is finalized. This helps break reference cycles involving frame + frame. Also, if the frame belonged to a :term:`generator`, the generator + is finalized. This helps break reference cycles involving frame objects (for example when catching an :ref:`exception ` and storing its :ref:`traceback ` for later use). @@ -1756,7 +1756,7 @@ created by calling :class:`types.TracebackType`. For implicitly created tracebacks, when the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is -inserted in front of the current traceback. When an exception handler is +inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section :ref:`try`.) It is accessible as the third item of the tuple returned by :func:`sys.exc_info`, and as the @@ -1822,7 +1822,7 @@ Slice objects Slice objects are used to represent slices for :meth:`~object.__getitem__` -methods. They are also created by the built-in :func:`slice` function. +methods. They are also created by the built-in :func:`slice` function. .. index:: single: start (slice object attribute) @@ -1831,7 +1831,7 @@ methods. They are also created by the built-in :func:`slice` function. Special read-only attributes: :attr:`~slice.start` is the lower bound; :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step -value; each is ``None`` if omitted. These attributes can have any type. +value; each is ``None`` if omitted. These attributes can have any type. Slice objects support one method: @@ -1839,7 +1839,7 @@ Slice objects support one method: This method takes a single integer argument *length* and computes information about the slice that the slice object would describe if - applied to a sequence of *length* items. It returns a tuple of three + applied to a sequence of *length* items. It returns a tuple of three integers; respectively these are the *start* and *stop* indices and the *step* or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices. @@ -1880,23 +1880,23 @@ A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python's approach to :dfn:`operator overloading`, allowing classes to define their own behavior with respect to language -operators. For instance, if a class defines a method named +operators. For instance, if a class defines a method named :meth:`~object.__getitem__`, and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent -to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an +to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically :exc:`AttributeError` or :exc:`TypeError`). Setting a special method to ``None`` indicates that the corresponding -operation is not available. For example, if a class sets +operation is not available. For example, if a class sets :meth:`~object.__iter__` to ``None``, the class is not iterable, so calling :func:`iter` on its instances will raise a :exc:`TypeError` (without falling back to :meth:`~object.__getitem__`). [#]_ When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the -object being modelled. For example, some sequences may work well with retrieval -of individual elements, but extracting a slice may not make sense. (One example +object being modelled. For example, some sequences may work well with retrieval +of individual elements, but extracting a slice may not make sense. (One example of this is the :class:`~xml.dom.NodeList` interface in the W3C's Document Object Model.) @@ -1910,11 +1910,11 @@ Basic customization .. index:: pair: subclassing; immutable types - Called to create a new instance of class *cls*. :meth:`__new__` is a static + Called to create a new instance of class *cls*. :meth:`__new__` is a static method (special-cased so you need not declare it as such) that takes the class - of which an instance was requested as its first argument. The remaining + of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the - class). The return value of :meth:`__new__` should be the new object instance + class). The return value of :meth:`__new__` should be the new object instance (usually an instance of *cls*). Typical implementations create a new instance of the class by invoking the @@ -1931,7 +1931,7 @@ Basic customization :meth:`__init__` method will not be invoked. :meth:`__new__` is intended mainly to allow subclasses of immutable types (like - int, str, or tuple) to customize instance creation. It is also commonly + int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation. @@ -1940,8 +1940,8 @@ Basic customization .. index:: pair: class; constructor Called after the instance has been created (by :meth:`__new__`), but before - it is returned to the caller. The arguments are those passed to the - class constructor expression. If a base class has an :meth:`__init__` + it is returned to the caller. The arguments are those passed to the + class constructor expression. If a base class has an :meth:`__init__` method, the derived class's :meth:`__init__` method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: ``super().__init__([args...])``. @@ -1959,15 +1959,15 @@ Basic customization single: finalizer pair: statement; del - Called when the instance is about to be destroyed. This is also called a - finalizer or (improperly) a destructor. If a base class has a + Called when the instance is about to be destroyed. This is also called a + finalizer or (improperly) a destructor. If a base class has a :meth:`__del__` method, the derived class's :meth:`__del__` method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. It is possible (though not recommended!) for the :meth:`__del__` method to postpone destruction of the instance by creating a new reference to - it. This is called object *resurrection*. It is implementation-dependent + it. This is called object *resurrection*. It is implementation-dependent whether :meth:`__del__` is called a second time when a resurrected object is about to be destroyed; the current :term:`CPython` implementation only calls it once. @@ -1985,10 +1985,10 @@ Basic customization .. impl-detail:: It is possible for a reference cycle to prevent the reference count - of an object from going to zero. In this case, the cycle will be + of an object from going to zero. In this case, the cycle will be later detected and deleted by the :term:`cyclic garbage collector - `. A common cause of reference cycles is when - an exception has been caught in a local variable. The frame's + `. A common cause of reference cycles is when + an exception has been caught in a local variable. The frame's locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback. @@ -2000,15 +2000,15 @@ Basic customization Due to the precarious circumstances under which :meth:`__del__` methods are invoked, exceptions that occur during their execution are ignored, and a warning - is printed to ``sys.stderr`` instead. In particular: + is printed to ``sys.stderr`` instead. In particular: * :meth:`__del__` can be invoked when arbitrary code is being executed, - including from any arbitrary thread. If :meth:`__del__` needs to take + including from any arbitrary thread. If :meth:`__del__` needs to take a lock or invoke any other blocking resource, it may deadlock as the resource may already be taken by the code that gets interrupted to execute :meth:`__del__`. - * :meth:`__del__` can be executed during interpreter shutdown. As a + * :meth:`__del__` can be executed during interpreter shutdown. As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to ``None``. Python guarantees that globals whose name begins with a single underscore @@ -2024,9 +2024,9 @@ Basic customization .. method:: object.__repr__(self) Called by the :func:`repr` built-in function to compute the "official" string - representation of an object. If at all possible, this should look like a + representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the - same value (given an appropriate environment). If this is not possible, a + same value (given an appropriate environment). If this is not possible, a string of the form ``<...some useful description...>`` should be returned. The return value must be a string object. If a class defines :meth:`__repr__` but not :meth:`__str__`, then :meth:`__repr__` is also used when an @@ -2046,7 +2046,7 @@ Basic customization Called by :func:`str(object) `, the default :meth:`__format__` implementation, and the built-in function :func:`print`, to compute the "informal" or nicely - printable string representation of an object. The return value must be a + printable string representation of an object. The return value must be a :ref:`str ` object. This method differs from :meth:`object.__repr__` in that there is no @@ -2129,7 +2129,7 @@ Basic customization :data:`NotImplemented` in the case of a false comparison: ``True if x is y else NotImplemented``. For :meth:`__ne__`, by default it delegates to :meth:`__eq__` and inverts the result unless it is - :data:`!NotImplemented`. There are no other implied relationships among the + :data:`!NotImplemented`. There are no other implied relationships among the comparison operators or default implementations; for example, the truth of ``(x` and :func:`@classmethod `) are -implemented as non-data descriptors. Accordingly, instances can redefine and -override methods. This allows individual instances to acquire behaviors that +implemented as non-data descriptors. Accordingly, instances can redefine and +override methods. This allows individual instances to acquire behaviors that differ from other instances of the same class. The :func:`property` function is implemented as a data descriptor. Accordingly, @@ -2570,7 +2570,7 @@ Attribute lookup speed can be significantly improved as well. .. data:: object.__slots__ This class variable can be assigned a string, iterable, or sequence of - strings with variable names used by instances. *__slots__* reserves space + strings with variable names used by instances. *__slots__* reserves space for the declared variables and prevents the automatic creation of :attr:`~object.__dict__` and *__weakref__* for each instance. @@ -2586,7 +2586,7 @@ Notes on using *__slots__*: * Without a :attr:`~object.__dict__` variable, instances cannot be assigned new variables not - listed in the *__slots__* definition. Attempts to assign to an unlisted + listed in the *__slots__* definition. Attempts to assign to an unlisted variable name raises :exc:`AttributeError`. If dynamic assignment of new variables is desired, then add ``'__dict__'`` to the sequence of strings in the *__slots__* declaration. @@ -2598,13 +2598,13 @@ Notes on using *__slots__*: *__slots__* declaration. * *__slots__* are implemented at the class level by creating :ref:`descriptors ` - for each variable name. As a result, class attributes + for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by *__slots__*; otherwise, the class attribute would overwrite the descriptor assignment. * The action of a *__slots__* declaration is not limited to the class - where it is defined. *__slots__* declared in parents are available in + where it is defined. *__slots__* declared in parents are available in child classes. However, instances of a child subclass will get a :attr:`~object.__dict__` and *__weakref__* unless the subclass also defines *__slots__* (which should only contain names of any *additional* slots). @@ -2612,7 +2612,7 @@ Notes on using *__slots__*: * If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the - program undefined. In the future, a check may be added to prevent this. + program undefined. In the future, a check may be added to prevent this. * :exc:`TypeError` will be raised if nonempty *__slots__* are defined for a class derived from a @@ -2930,12 +2930,12 @@ ABCs. .. method:: type.__subclasscheck__(self, subclass) Return true if *subclass* should be considered a (direct or indirect) - subclass of *class*. If defined, called to implement ``issubclass(subclass, + subclass of *class*. If defined, called to implement ``issubclass(subclass, class)``. -Note that these methods are looked up on the type (metaclass) of a class. They -cannot be defined as class methods in the actual class. This is consistent with +Note that these methods are looked up on the type (metaclass) of a class. They +cannot be defined as class methods in the actual class. This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class. @@ -3115,15 +3115,15 @@ are provided by the :class:`object` class itself. Containers usually are :term:`sequences ` (such as :class:`lists ` or :class:`tuples `) or :term:`mappings ` (like :term:`dictionaries `), -but can represent other containers as well. The first set of methods is used +but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers *k* for which ``0 <= k < N`` where *N* is the length of the sequence, or :class:`slice` objects, which define a -range of items. It is also recommended that mappings provide the methods +range of items. It is also recommended that mappings provide the methods :meth:`!keys`, :meth:`!values`, :meth:`!items`, :meth:`!get`, :meth:`!clear`, :meth:`!setdefault`, :meth:`!pop`, :meth:`!popitem`, :meth:`!copy`, and :meth:`!update` behaving similar to those for Python's standard :class:`dictionary ` -objects. The :mod:`collections.abc` module provides a +objects. The :mod:`collections.abc` module provides a :class:`~collections.abc.MutableMapping` :term:`abstract base class` to help create those methods from a base set of :meth:`~object.__getitem__`, :meth:`~object.__setitem__`, @@ -3137,11 +3137,11 @@ multiplication (meaning repetition) by defining the methods :meth:`~object.__add__`, :meth:`~object.__radd__`, :meth:`~object.__iadd__`, :meth:`~object.__mul__`, :meth:`~object.__rmul__` and :meth:`~object.__imul__` described below; they should not define other numerical -operators. It is recommended that both mappings and sequences implement the +operators. It is recommended that both mappings and sequences implement the :meth:`~object.__contains__` method to allow efficient use of the ``in`` operator; for mappings, ``in`` should search the mapping's keys; for sequences, it should -search through the values. It is further recommended that both mappings and +search through the values. It is further recommended that both mappings and sequences implement the :meth:`~object.__iter__` method to allow efficient iteration through the container; for mappings, :meth:`!__iter__` should iterate through the object's keys; for sequences, it should iterate through the values. @@ -3152,8 +3152,8 @@ through the object's keys; for sequences, it should iterate through the values. pair: built-in function; len single: __bool__() (object method) - Called to implement the built-in function :func:`len`. Should return the length - of the object, an integer ``>=`` 0. Also, an object that doesn't define a + Called to implement the built-in function :func:`len`. Should return the length + of the object, an integer ``>=`` 0. Also, an object that doesn't define a :meth:`~object.__bool__` method and whose :meth:`!__len__` method returns zero is considered to be false in a Boolean context. @@ -3161,7 +3161,7 @@ through the object's keys; for sequences, it should iterate through the values. In CPython, the length is required to be at most :data:`sys.maxsize`. If the length is larger than :data:`!sys.maxsize` some features (such as - :func:`len`) may raise :exc:`OverflowError`. To prevent raising + :func:`len`) may raise :exc:`OverflowError`. To prevent raising :exc:`!OverflowError` by truth value testing, an object must define a :meth:`~object.__bool__` method. @@ -3182,7 +3182,7 @@ through the object's keys; for sequences, it should iterate through the values. .. note:: - Slicing is done exclusively with the following three methods. A call like :: + Slicing is done exclusively with the following three methods. A call like :: a[1:2] = b @@ -3190,14 +3190,14 @@ through the object's keys; for sequences, it should iterate through the values. a[slice(1, 2, None)] = b - and so forth. Missing slice items are always filled in with ``None``. + and so forth. Missing slice items are always filled in with ``None``. .. method:: object.__getitem__(self, key) Called to implement evaluation of ``self[key]``. For :term:`sequence` types, the accepted keys should be integers. Optionally, they may support - :class:`slice` objects as well. Negative index support is also optional. + :class:`slice` objects as well. Negative index support is also optional. If *key* is of an inappropriate type, :exc:`TypeError` may be raised; if *key* is a value outside the set of indexes for the sequence (after any special @@ -3220,19 +3220,19 @@ through the object's keys; for sequences, it should iterate through the values. .. method:: object.__setitem__(self, key, value) - Called to implement assignment to ``self[key]``. Same note as for - :meth:`__getitem__`. This should only be implemented for mappings if the + Called to implement assignment to ``self[key]``. Same note as for + :meth:`__getitem__`. This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or - for sequences if elements can be replaced. The same exceptions should be raised + for sequences if elements can be replaced. The same exceptions should be raised for improper *key* values as for the :meth:`__getitem__` method. .. method:: object.__delitem__(self, key) - Called to implement deletion of ``self[key]``. Same note as for - :meth:`__getitem__`. This should only be implemented for mappings if the + Called to implement deletion of ``self[key]``. Same note as for + :meth:`__getitem__`. This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed - from the sequence. The same exceptions should be raised for improper *key* + from the sequence. The same exceptions should be raised for improper *key* values as for the :meth:`__getitem__` method. @@ -3246,19 +3246,19 @@ through the object's keys; for sequences, it should iterate through the values. This method is called when an :term:`iterator` is required for a container. This method should return a new iterator object that can iterate over all the - objects in the container. For mappings, it should iterate over the keys of + objects in the container. For mappings, it should iterate over the keys of the container. .. method:: object.__reversed__(self) Called (if present) by the :func:`reversed` built-in to implement - reverse iteration. It should return a new iterator object that iterates + reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order. If the :meth:`__reversed__` method is not provided, the :func:`reversed` built-in will fall back to using the sequence protocol (:meth:`__len__` and - :meth:`__getitem__`). Objects that support the sequence protocol should + :meth:`__getitem__`). Objects that support the sequence protocol should only provide :meth:`__reversed__` if they can provide an implementation that is more efficient than the one provided by :func:`reversed`. @@ -3270,8 +3270,8 @@ also does not require the object be iterable. .. method:: object.__contains__(self, item) - Called to implement membership test operators. Should return true if *item* - is in *self*, false otherwise. For mapping objects, this should consider the + Called to implement membership test operators. Should return true if *item* + is in *self*, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs. For objects that don't define :meth:`__contains__`, the membership test first @@ -3313,12 +3313,12 @@ left undefined. These methods are called to implement the binary arithmetic operations (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, - :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to + :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to evaluate the expression ``x + y``, where *x* is an instance of a class that - has an :meth:`__add__` method, ``type(x).__add__(x, y)`` is called. The + has an :meth:`__add__` method, ``type(x).__add__(x, y)`` is called. The :meth:`__divmod__` method should be the equivalent to using :meth:`__floordiv__` and :meth:`__mod__`; it should not be related to - :meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept + :meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept an optional third argument if the three-argument version of the built-in :func:`pow` function is to be supported. @@ -3348,7 +3348,7 @@ left undefined. These methods are called to implement the binary arithmetic operations (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected - (swapped) operands. These functions are only called if the operands + (swapped) operands. These functions are only called if the operands are of different types, when the left operand does not support the corresponding operation [#]_, or the right operand's class is derived from the left operand's class. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is @@ -3390,11 +3390,11 @@ left undefined. These methods are called to implement the augmented arithmetic assignments (``+=``, ``-=``, ``*=``, ``@=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, - ``>>=``, ``&=``, ``^=``, ``|=``). These methods should attempt to do the + ``>>=``, ``&=``, ``^=``, ``|=``). These methods should attempt to do the operation in-place (modifying *self*) and return the result (which could be, - but does not have to be, *self*). If a specific method is not defined, or if + but does not have to be, *self*). If a specific method is not defined, or if that method returns :data:`NotImplemented`, the - augmented assignment falls back to the normal methods. For instance, if *x* + augmented assignment falls back to the normal methods. For instance, if *x* is an instance of a class with an :meth:`__iadd__` method, ``x += y`` is equivalent to ``x = x.__iadd__(y)`` . If :meth:`__iadd__` does not exist, or if ``x.__iadd__(y)`` returns :data:`!NotImplemented`, ``x.__add__(y)`` and @@ -3425,7 +3425,7 @@ left undefined. pair: built-in function; float Called to implement the built-in functions :func:`complex`, - :func:`int` and :func:`float`. Should return a value + :func:`int` and :func:`float`. Should return a value of the appropriate type. @@ -3435,7 +3435,7 @@ left undefined. losslessly convert the numeric object to an integer object (such as in slicing, or in the built-in :func:`bin`, :func:`hex` and :func:`oct` functions). Presence of this method indicates that the numeric object is - an integer type. Must return an integer. + an integer type. Must return an integer. If :meth:`__int__`, :meth:`__float__` and :meth:`__complex__` are not defined then corresponding built-in functions :func:`int`, :func:`float` @@ -3467,7 +3467,7 @@ With Statement Context Managers A :dfn:`context manager` is an object that defines the runtime context to be established when executing a :keyword:`with` statement. The context manager handles the entry into, and the exit from, the desired runtime context for the -execution of the block of code. Context managers are normally invoked using the +execution of the block of code. Context managers are normally invoked using the :keyword:`!with` statement (described in section :ref:`with`), but can also be used by directly invoking their methods. @@ -3614,7 +3614,7 @@ with a symbol. :attr:`~annotationlib.Format.VALUE` format; they must not raise :exc:`NotImplementedError()` when called with this format. - When called with :attr:`~annotationlib.Format.VALUE` format, an annotate function may raise + When called with :attr:`~annotationlib.Format.VALUE` format, an annotate function may raise :exc:`NameError`; it must not raise :exc:`!NameError` when called requesting any other format. If an object does not have any annotations, :attr:`~object.__annotate__` should preferably be set @@ -3635,7 +3635,7 @@ Special method lookup For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object's type, not in the object's instance -dictionary. That behaviour is the reason why the following code raises an +dictionary. That behaviour is the reason why the following code raises an exception:: >>> class C: @@ -3726,8 +3726,8 @@ are awaitable. .. method:: object.__await__(self) - Must return an :term:`iterator`. Should be used to implement - :term:`awaitable` objects. For instance, :class:`asyncio.Future` implements + Must return an :term:`iterator`. Should be used to implement + :term:`awaitable` objects. For instance, :class:`asyncio.Future` implements this method to be compatible with the :keyword:`await` expression. The :class:`object` class itself is not awaitable and does not provide this method. @@ -3752,14 +3752,14 @@ Coroutine Objects :term:`Coroutine objects ` are :term:`awaitable` objects. A coroutine's execution can be controlled by calling :meth:`~object.__await__` and -iterating over the result. When the coroutine has finished executing and +iterating over the result. When the coroutine has finished executing and returns, the iterator raises :exc:`StopIteration`, and the exception's -:attr:`~StopIteration.value` attribute holds the return value. If the -coroutine raises an exception, it is propagated by the iterator. Coroutines +:attr:`~StopIteration.value` attribute holds the return value. If the +coroutine raises an exception, it is propagated by the iterator. Coroutines should not directly raise unhandled :exc:`StopIteration` exceptions. Coroutines also have the methods listed below, which are analogous to -those of generators (see :ref:`generator-methods`). However, unlike +those of generators (see :ref:`generator-methods`). However, unlike generators, coroutines do not directly support iteration. .. versionchanged:: 3.5.2 @@ -3768,24 +3768,24 @@ generators, coroutines do not directly support iteration. .. method:: coroutine.send(value) - Starts or resumes execution of the coroutine. If *value* is ``None``, + Starts or resumes execution of the coroutine. If *value* is ``None``, this is equivalent to advancing the iterator returned by - :meth:`~object.__await__`. If *value* is not ``None``, this method delegates + :meth:`~object.__await__`. If *value* is not ``None``, this method delegates to the :meth:`~generator.send` method of the iterator that caused - the coroutine to suspend. The result (return value, + the coroutine to suspend. The result (return value, :exc:`StopIteration`, or other exception) is the same as when iterating over the :meth:`!__await__` return value, described above. .. method:: coroutine.throw(value) coroutine.throw(type[, value[, traceback]]) - Raises the specified exception in the coroutine. This method delegates + Raises the specified exception in the coroutine. This method delegates to the :meth:`~generator.throw` method of the iterator that caused - the coroutine to suspend, if it has such a method. Otherwise, - the exception is raised at the suspension point. The result + the coroutine to suspend, if it has such a method. Otherwise, + the exception is raised at the suspension point. The result (return value, :exc:`StopIteration`, or other exception) is the same as when iterating over the :meth:`~object.__await__` return value, described - above. If the exception is not caught in the coroutine, it propagates + above. If the exception is not caught in the coroutine, it propagates back to the caller. .. versionchanged:: 3.12 @@ -3795,10 +3795,10 @@ generators, coroutines do not directly support iteration. .. method:: coroutine.close() - Causes the coroutine to clean itself up and exit. If the coroutine + Causes the coroutine to clean itself up and exit. If the coroutine is suspended, this method first delegates to the :meth:`~generator.close` method of the iterator that caused the coroutine to suspend, if it - has such a method. Then it raises :exc:`GeneratorExit` at the + has such a method. Then it raises :exc:`GeneratorExit` at the suspension point, causing the coroutine to immediately clean itself up. Finally, the coroutine is marked as having finished executing, even if it was never started. @@ -3825,7 +3825,7 @@ The :class:`object` class itself does not provide these methods. .. method:: object.__anext__(self) - Must return an *awaitable* resulting in a next value of the iterator. Should + Must return an *awaitable* resulting in a next value of the iterator. Should raise a :exc:`StopAsyncIteration` error when the iteration is over. An example of an asynchronous iterable object:: @@ -3851,7 +3851,7 @@ An example of an asynchronous iterable object:: :term:`asynchronous iterator `. Starting with Python 3.7, :meth:`~object.__aiter__` must return an - asynchronous iterator object. Returning anything else + asynchronous iterator object. Returning anything else will result in a :exc:`TypeError` error. @@ -3903,7 +3903,7 @@ An example of an asynchronous context manager class:: the behavior that ``None`` is not callable. .. [#] "Does not support" here means that the class has no such method, or - the method returns :data:`NotImplemented`. Do not set the method to + the method returns :data:`NotImplemented`. Do not set the method to ``None`` if you want to force fallback to the right operand's reflected method—that will instead have the opposite effect of explicitly *blocking* such fallback. diff --git a/Doc/reference/executionmodel.rst b/Doc/reference/executionmodel.rst index cb6c524dd97a30..cebbe197738b79 100644 --- a/Doc/reference/executionmodel.rst +++ b/Doc/reference/executionmodel.rst @@ -19,9 +19,9 @@ Structure of a program A Python program is constructed from code blocks. A :dfn:`block` is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. -Each command typed interactively is a block. A script file (a file given as +Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the -interpreter) is a code block. A script command (a command specified on the +interpreter) is a code block. A script command (a command specified on the interpreter command line with the :option:`-c` option) is a code block. A module run as a top level script (as module ``__main__``) from the command line using a :option:`-m` argument is also a code block. The string @@ -30,7 +30,7 @@ code block. .. index:: pair: execution; frame -A code block is executed in an :dfn:`execution frame`. A frame contains some +A code block is executed in an :dfn:`execution frame`. A frame contains some administrative information (used for debugging) and determines where and how execution continues after the code block's execution has completed. @@ -52,7 +52,7 @@ Binding of names single: name pair: binding; name -:dfn:`Names` refer to objects. Names are introduced by name binding operations. +:dfn:`Names` refer to objects. Names are introduced by name binding operations. .. index:: single: from; import statement @@ -87,9 +87,9 @@ function definition or at the module level (the top-level code block). .. index:: pair: free; variable If a name is bound in a block, it is a local variable of that block, unless -declared as :keyword:`nonlocal` or :keyword:`global`. If a name is bound at -the module level, it is a global variable. (The variables of the module code -block are local and global.) If a variable is used in a code block but not +declared as :keyword:`nonlocal` or :keyword:`global`. If a name is bound at +the module level, it is a global variable. (The variables of the module code +block are local and global.) If a variable is used in a code block but not defined there, it is a :term:`free variable`. Each occurrence of a name in the program text refers to the :dfn:`binding` of @@ -102,8 +102,8 @@ Resolution of names .. index:: scope -A :dfn:`scope` defines the visibility of a name within a block. If a local -variable is defined in a block, its scope includes that block. If the +A :dfn:`scope` defines the visibility of a name within a block. If a local +variable is defined in a block, its scope includes that block. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name. @@ -111,7 +111,7 @@ for the name. .. index:: single: environment When a name is used in a code block, it is resolved using the nearest enclosing -scope. The set of all such scopes visible to a code block is called the block's +scope. The set of all such scopes visible to a code block is called the block's :dfn:`environment`. .. index:: @@ -125,26 +125,26 @@ used, an :exc:`UnboundLocalError` exception is raised. :exc:`UnboundLocalError` is a subclass of :exc:`NameError`. If a name binding operation occurs anywhere within a code block, all uses of the -name within the block are treated as references to the current block. This can -lead to errors when a name is used within a block before it is bound. This rule -is subtle. Python lacks declarations and allows name binding operations to -occur anywhere within a code block. The local variables of a code block can be +name within the block are treated as references to the current block. This can +lead to errors when a name is used within a block before it is bound. This rule +is subtle. Python lacks declarations and allows name binding operations to +occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations. See :ref:`the FAQ entry on UnboundLocalError ` for examples. If the :keyword:`global` statement occurs within a block, all uses of the names specified in the statement refer to the bindings of those names in the top-level -namespace. Names are resolved in the top-level namespace by searching the +namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, -and the builtins namespace, the namespace of the module :mod:`builtins`. The -global namespace is searched first. If the names are not found there, the +and the builtins namespace, the namespace of the module :mod:`builtins`. The +global namespace is searched first. If the names are not found there, the builtins namespace is searched next. If the names are also not found in the builtins namespace, new variables are created in the global namespace. The global statement must precede all uses of the listed names. The :keyword:`global` statement has the same scope as a name binding operation -in the same block. If the nearest enclosing scope for a free variable contains +in the same block. If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global. .. XXX say more about "nonlocal" semantics here @@ -158,7 +158,7 @@ cannot be rebound with the :keyword:`!nonlocal` statement. .. index:: pair: module; __main__ The namespace for a module is automatically created the first time a module is -imported. The main module for a script is always called :mod:`__main__`. +imported. The main module for a script is always called :mod:`__main__`. Class definition blocks and arguments to :func:`exec` and :func:`eval` are special in the context of name resolution. @@ -301,14 +301,14 @@ Builtins and restricted execution .. impl-detail:: Users should not touch ``__builtins__``; it is strictly an implementation - detail. Users wanting to override values in the builtins namespace should + detail. Users wanting to override values in the builtins namespace should :keyword:`import` the :mod:`builtins` module and modify its attributes appropriately. The builtins namespace associated with the execution of a code block is actually found by looking up the name ``__builtins__`` in its global namespace; this should be a dictionary or a module (in the -latter case the module's dictionary is used). By default, when in the +latter case the module's dictionary is used). By default, when in the :mod:`__main__` module, ``__builtins__`` is the built-in module :mod:`builtins`; when in any other module, ``__builtins__`` is an alias for the dictionary of the :mod:`builtins` module itself. @@ -331,11 +331,11 @@ This means that the following code will print 42:: .. XXX from * also invalid with relative imports (at least currently) The :func:`eval` and :func:`exec` functions do not have access to the full -environment for resolving names. Names may be resolved in the local and global -namespaces of the caller. Free variables are not resolved in the nearest -enclosing namespace, but in the global namespace. [#]_ The :func:`exec` and +environment for resolving names. Names may be resolved in the local and global +namespaces of the caller. Free variables are not resolved in the nearest +enclosing namespace, but in the global namespace. [#]_ The :func:`exec` and :func:`eval` functions have optional arguments to override the global and local -namespace. If only one namespace is specified, it is used for both. +namespace. If only one namespace is specified, it is used for both. .. XXX(ncoghlan) above is only accurate for string execution. When executing code objects, closure cells may now be passed explicitly to resolve co_freevars references. @@ -356,15 +356,15 @@ Exceptions single: error handling Exceptions are a means of breaking out of the normal flow of control of a code -block in order to handle errors or other exceptional conditions. An exception +block in order to handle errors or other exceptional conditions. An exception is *raised* at the point where the error is detected; it may be *handled* by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred. The Python interpreter raises an exception when it detects a run-time error -(such as division by zero). A Python program can also explicitly raise an +(such as division by zero). A Python program can also explicitly raise an exception with the :keyword:`raise` statement. Exception handlers are specified -with the :keyword:`try` ... :keyword:`except` statement. The :keyword:`finally` +with the :keyword:`try` ... :keyword:`except` statement. The :keyword:`finally` clause of such a statement can be used to specify cleanup code which does not handle the exception, but is executed whether an exception occurred or not in the preceding code. @@ -379,10 +379,10 @@ re-entering the offending piece of code from the top). .. index:: single: SystemExit (built-in exception) When an exception is not handled at all, the interpreter terminates execution of -the program, or returns to its interactive main loop. In either case, it prints +the program, or returns to its interactive main loop. In either case, it prints a stack traceback, except when the exception is :exc:`SystemExit`. -Exceptions are identified by class instances. The :keyword:`except` clause is +Exceptions are identified by class instances. The :keyword:`except` clause is selected depending on the class of the instance: it must reference the class of the instance or a :term:`non-virtual base class ` thereof. The instance can be received by the handler and can carry additional information @@ -390,7 +390,7 @@ about the exceptional condition. .. note:: - Exception messages are not part of the Python API. Their contents may change + Exception messages are not part of the Python API. Their contents may change from one version of Python to the next without warning and should not be relied on by code which will run under multiple versions of the interpreter. diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index 24544a055c3ed2..803a4d346533a5 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -10,7 +10,7 @@ Expressions This chapter explains the meaning of the elements of expressions in Python. **Syntax Notes:** In this and the following chapters, extended BNF notation will -be used to describe syntax, not lexical analysis. When (one alternative of) a +be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rule has the form .. productionlist:: python-grammar @@ -38,7 +38,7 @@ implementation for built-in types works as follows: * otherwise, both must be integers and no conversion is necessary. Some additional rules apply for certain operators (e.g., a string as a left -argument to the '%' operator). Extensions must define their own conversion +argument to the '%' operator). Extensions must define their own conversion behavior. @@ -49,9 +49,9 @@ Atoms .. index:: atom -Atoms are the most basic elements of expressions. The simplest atoms are -identifiers or literals. Forms enclosed in parentheses, brackets or braces are -also categorized syntactically as atoms. The syntax for atoms is: +Atoms are the most basic elements of expressions. The simplest atoms are +identifiers or literals. Forms enclosed in parentheses, brackets or braces are +also categorized syntactically as atoms. The syntax for atoms is: .. productionlist:: python-grammar atom: `identifier` | `literal` | `enclosure` @@ -66,7 +66,7 @@ Identifiers (Names) .. index:: name, identifier -An identifier occurring as an atom is a name. See section :ref:`identifiers` +An identifier occurring as an atom is a name. See section :ref:`identifiers` for lexical definition and section :ref:`naming` for documentation of naming and binding. @@ -94,7 +94,7 @@ is considered a :dfn:`private name` of that class. The :ref:`class specifications `. More precisely, private names are transformed to a longer form before code is -generated for them. If the transformed name is longer than 255 characters, +generated for them. If the transformed name is longer than 255 characters, implementation-defined truncation may happen. The transformation is independent of the syntactical context in which the @@ -137,16 +137,16 @@ Python supports string and bytes literals and various numeric literals: literal: `stringliteral` | `bytesliteral` | `NUMBER` Evaluation of a literal yields an object of the given type (string, bytes, -integer, floating-point number, complex number) with the given value. The value +integer, floating-point number, complex number) with the given value. The value may be approximated in the case of floating-point and imaginary (complex) -literals. See section :ref:`literals` for details. +literals. See section :ref:`literals` for details. .. index:: triple: immutable; data; type pair: immutable; object All literals correspond to immutable data types, and hence the object's identity -is less important than its value. Multiple evaluations of literals with the +is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value. @@ -172,7 +172,7 @@ the single expression that makes up the expression list. .. index:: pair: empty; tuple -An empty pair of parentheses yields an empty tuple object. Since tuples are +An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object). @@ -181,7 +181,7 @@ tuple may or may not yield the same object). single: , (comma) Note that tuples are not formed by the parentheses, but rather by use of the -comma. The exception is the empty tuple, for which parentheses *are* +comma. The exception is the empty tuple, for which parentheses *are* required --- allowing unparenthesized "nothing" in expressions would cause ambiguities and allow common typos to pass uncaught. @@ -285,9 +285,9 @@ brackets: list_display: "[" [`flexible_expression_list` | `comprehension`] "]" A list display yields a new list object, the contents being specified by either -a list of expressions or a comprehension. When a comma-separated list of +a list of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and -placed into the list object in that order. When a comprehension is supplied, +placed into the list object in that order. When a comprehension is supplied, the list is constructed from the elements resulting from the comprehension. @@ -310,9 +310,9 @@ displays by the lack of colons separating keys and values: set_display: "{" (`flexible_expression_list` | `comprehension`) "}" A set display yields a new mutable set object, the contents being specified by -either a sequence of expressions or a comprehension. When a comma-separated +either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right -and added to the set object. When a comprehension is supplied, the set is +and added to the set object. When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension. An empty set cannot be constructed with ``{}``; this literal constructs an empty @@ -346,7 +346,7 @@ A dictionary display yields a new dictionary object. If a comma-separated sequence of dict items is given, they are evaluated from left to right to define the entries of the dictionary: each key object is -used as a key into the dictionary to store the corresponding value. This means +used as a key into the dictionary to store the corresponding value. This means that you can specify the same key multiple times in the dict item list, and the final dictionary's value for that key will be the last one given. @@ -355,8 +355,8 @@ final dictionary's value for that key will be the last one given. single: **; in dictionary displays A double asterisk ``**`` denotes :dfn:`dictionary unpacking`. -Its operand must be a :term:`mapping`. Each mapping item is added -to the new dictionary. Later values replace values already set by +Its operand must be a :term:`mapping`. Each mapping item is added +to the new dictionary. Later values replace values already set by earlier dict items and earlier dictionary unpackings. .. versionadded:: 3.5 @@ -371,15 +371,15 @@ in the new dictionary in the order they are produced. hashable Restrictions on the types of the key values are listed earlier in section -:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes -all mutable objects.) Clashes between duplicate keys are not detected; the last +:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes +all mutable objects.) Clashes between duplicate keys are not detected; the last value (textually rightmost in the display) stored for a given key value prevails. .. versionchanged:: 3.8 Prior to Python 3.8, in dict comprehensions, the evaluation order of key - and value was not well-defined. In CPython, the value was evaluated before - the key. Starting with 3.8, the key is evaluated before the value, as + and value was not well-defined. In CPython, the value was evaluated before + the key. Starting with 3.8, the key is evaluated before the value, as proposed by :pep:`572`. @@ -398,13 +398,13 @@ A generator expression is a compact generator notation in parentheses: .. productionlist:: python-grammar generator_expression: "(" `expression` `comp_for` ")" -A generator expression yields a new generator object. Its syntax is the same as +A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces. Variables used in the generator expression are evaluated lazily when the :meth:`~generator.__next__` method is called for the generator object (in the same -fashion as normal generators). However, the iterable expression in the +fashion as normal generators). However, the iterable expression in the leftmost :keyword:`!for` clause is immediately evaluated, and the :term:`iterator` is immediately created for that iterable, so that an error produced while creating the iterator will be emitted at the point where the generator expression @@ -414,7 +414,7 @@ Subsequent :keyword:`!for` clauses and any filter condition in the leftmost depend on the values obtained from the leftmost iterable. For example: ``(x*y for x in range(10) for y in range(x, x+10))``. -The parentheses can be omitted on calls with only one argument. See section +The parentheses can be omitted on calls with only one argument. See section :ref:`calls` for details. To avoid interfering with the expected operation of the generator expression @@ -423,7 +423,7 @@ implicitly defined generator. If a generator expression contains either :keyword:`!async for` clauses or :keyword:`await` expressions it is called an -:dfn:`asynchronous generator expression`. An asynchronous generator +:dfn:`asynchronous generator expression`. An asynchronous generator expression returns a new asynchronous generator object, which is an asynchronous iterator (see :ref:`async-iterators`). @@ -432,7 +432,7 @@ which is an asynchronous iterator (see :ref:`async-iterators`). .. versionchanged:: 3.7 Prior to Python 3.7, asynchronous generator expressions could - only appear in :keyword:`async def` coroutines. Starting + only appear in :keyword:`async def` coroutines. Starting with 3.7, any function can use asynchronous generator expressions. .. versionchanged:: 3.8 @@ -457,7 +457,7 @@ Yield expressions The yield expression is used when defining a :term:`generator` function or an :term:`asynchronous generator` function and -thus can only be used in the body of a function definition. Using a yield +thus can only be used in the body of a function definition. Using a yield expression in a function's body causes that function to be a generator function, and using it in an :keyword:`async def` function's body causes that coroutine function to be an asynchronous generator function. For example:: @@ -481,8 +481,8 @@ functions are described separately in section :ref:`asynchronous-generator-functions`. When a generator function is called, it returns an iterator known as a -generator. That generator then controls the execution of the generator -function. The execution starts when one of the generator's methods is called. +generator. That generator then controls the execution of the generator +function. The execution starts when one of the generator's methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of :token:`~python-grammar:yield_list` to the generator's caller, @@ -492,21 +492,21 @@ retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the yield expression were just another -external call. The value of the yield expression after resuming depends on the -method which resumed the execution. If :meth:`~generator.__next__` is used +external call. The value of the yield expression after resuming depends on the +method which resumed the execution. If :meth:`~generator.__next__` is used (typically via either a :keyword:`for` or the :func:`next` builtin) then the -result is :const:`None`. Otherwise, if :meth:`~generator.send` is used, then +result is :const:`None`. Otherwise, if :meth:`~generator.send` is used, then the result will be the value passed in to that method. .. index:: single: coroutine All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be -suspended. The only difference is that a generator function cannot control +suspended. The only difference is that a generator function cannot control where the execution should continue after it yields; the control is always transferred to the generator's caller. -Yield expressions are allowed anywhere in a :keyword:`try` construct. If the +Yield expressions are allowed anywhere in a :keyword:`try` construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator's :meth:`~generator.close` method will be called, @@ -520,7 +520,7 @@ iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator's methods. Any values passed in with :meth:`~generator.send` and any exceptions passed in with :meth:`~generator.throw` are passed to the underlying iterator if it has the -appropriate methods. If this is not the case, then :meth:`~generator.send` +appropriate methods. If this is not the case, then :meth:`~generator.send` will raise :exc:`AttributeError` or :exc:`TypeError`, while :meth:`~generator.throw` will just raise the passed in exception immediately. @@ -559,7 +559,7 @@ on the right hand side of an assignment statement. Generator-iterator methods ^^^^^^^^^^^^^^^^^^^^^^^^^^ -This subsection describes the methods of a generator iterator. They can +This subsection describes the methods of a generator iterator. They can be used to control the execution of a generator function. Note that calling any of the generator methods below when the generator @@ -571,12 +571,12 @@ is already executing raises a :exc:`ValueError` exception. .. method:: generator.__next__() Starts the execution of a generator function or resumes it at the last - executed yield expression. When a generator function is resumed with a + executed yield expression. When a generator function is resumed with a :meth:`~generator.__next__` method, the current yield expression always - evaluates to :const:`None`. The execution then continues to the next yield + evaluates to :const:`None`. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the :token:`~python-grammar:yield_list` is returned to :meth:`__next__`'s - caller. If the generator exits without yielding another value, a + caller. If the generator exits without yielding another value, a :exc:`StopIteration` exception is raised. This method is normally called implicitly, e.g. by a :keyword:`for` loop, or @@ -585,11 +585,11 @@ is already executing raises a :exc:`ValueError` exception. .. method:: generator.send(value) - Resumes the execution and "sends" a value into the generator function. The - *value* argument becomes the result of the current yield expression. The + Resumes the execution and "sends" a value into the generator function. The + *value* argument becomes the result of the current yield expression. The :meth:`send` method returns the next value yielded by the generator, or raises :exc:`StopIteration` if the generator exits without yielding another - value. When :meth:`send` is called to start the generator, it must be called + value. When :meth:`send` is called to start the generator, it must be called with :const:`None` as the argument, because there is no yield expression that could receive the value. @@ -598,9 +598,9 @@ is already executing raises a :exc:`ValueError` exception. generator.throw(type[, value[, traceback]]) Raises an exception at the point where the generator was paused, - and returns the next value yielded by the generator function. If the generator + and returns the next value yielded by the generator function. If the generator exits without yielding another value, a :exc:`StopIteration` exception is - raised. If the generator function does not catch the passed-in exception, or + raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller. In typical use, this is called with a single exception instance similar to the @@ -629,11 +629,11 @@ is already executing raises a :exc:`ValueError` exception. function was paused (equivalent to calling ``throw(GeneratorExit)``). The exception is raised by the yield expression where the generator was paused. If the generator function catches the exception and returns a - value, this value is returned from :meth:`close`. If the generator function + value, this value is returned from :meth:`close`. If the generator function is already closed, or raises :exc:`GeneratorExit` (by not catching the - exception), :meth:`close` returns :const:`None`. If the generator yields a - value, a :exc:`RuntimeError` is raised. If the generator raises any other - exception, it is propagated to the caller. If the generator has already + exception), :meth:`close` returns :const:`None`. If the generator yields a + value, a :exc:`RuntimeError` is raised. If the generator raises any other + exception, it is propagated to the caller. If the generator has already exited due to an exception or normal exit, :meth:`close` returns :const:`None` and has no other effect. @@ -703,7 +703,7 @@ pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by awaiting on the next object returned by the asynchronous generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield -expression after resuming depends on the method which resumed the execution. If +expression after resuming depends on the method which resumed the execution. If :meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if :meth:`~agen.asend` is used, then the result will be the value passed in to that method. @@ -723,7 +723,7 @@ in a :keyword:`try` construct. However, if an asynchronous generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), then a yield expression within a :keyword:`!try` construct could result in a failure to execute pending :keyword:`finally` -clauses. In this case, it is the responsibility of the event loop or +clauses. In this case, it is the responsibility of the event loop or scheduler running the asynchronous generator to call the asynchronous generator-iterator's :meth:`~agen.aclose` method and run the resulting coroutine object, thus allowing any pending :keyword:`!finally` clauses @@ -732,7 +732,7 @@ to execute. To take care of finalization upon event loop termination, an event loop should define a *finalizer* function which takes an asynchronous generator-iterator and presumably calls :meth:`~agen.aclose` and executes the coroutine. -This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. +This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. When first iterated over, an asynchronous generator-iterator will store the registered *finalizer* to be called upon finalization. For a reference example of a *finalizer* method see the implementation of @@ -757,13 +757,13 @@ which are used to control the execution of a generator function. :async: Returns an awaitable which when run starts to execute the asynchronous - generator or resumes it at the last executed yield expression. When an + generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an :meth:`~agen.__anext__` method, the current yield expression always evaluates to :const:`None` in the returned awaitable, which when run will continue to the next yield expression. The value of the :token:`~python-grammar:yield_list` of the yield expression is the value of the :exc:`StopIteration` exception raised by - the completing coroutine. If the asynchronous generator exits without + the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a :exc:`StopAsyncIteration` exception, signalling that the asynchronous iteration has completed. @@ -781,7 +781,7 @@ which are used to control the execution of a generator function. The awaitable returned by the :meth:`asend` method will return the next value yielded by the generator as the value of the raised :exc:`StopIteration`, or raises :exc:`StopAsyncIteration` if the - asynchronous generator exits without yielding another value. When + asynchronous generator exits without yielding another value. When :meth:`asend` is called to start the asynchronous generator, it must be called with :const:`None` as the argument, because there is no yield expression that could receive the value. @@ -794,7 +794,7 @@ which are used to control the execution of a generator function. Returns an awaitable that raises an exception of type ``type`` at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised - :exc:`StopIteration` exception. If the asynchronous generator exits + :exc:`StopIteration` exception. If the asynchronous generator exits without yielding another value, a :exc:`StopAsyncIteration` exception is raised by the awaitable. If the generator function does not catch the passed-in exception, or @@ -818,10 +818,10 @@ which are used to control the execution of a generator function. closed, or raises :exc:`GeneratorExit` (by not catching the exception), then the returned awaitable will raise a :exc:`StopIteration` exception. Any further awaitables returned by subsequent calls to the asynchronous - generator will raise a :exc:`StopAsyncIteration` exception. If the + generator will raise a :exc:`StopAsyncIteration` exception. If the asynchronous generator yields a value, a :exc:`RuntimeError` is raised - by the awaitable. If the asynchronous generator raises any other exception, - it is propagated to the caller of the awaitable. If the asynchronous + by the awaitable. If the asynchronous generator raises any other exception, + it is propagated to the caller of the awaitable. If the asynchronous generator has already exited due to an exception or normal exit, then further calls to :meth:`aclose` will return an awaitable that does nothing. @@ -859,14 +859,14 @@ An attribute reference is a primary followed by a period and a name: pair: object; list The primary must evaluate to an object of a type that supports attribute -references, which most objects do. This object is then asked to produce the +references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. The type and value produced is -determined by the object. Multiple evaluations of the same attribute +determined by the object. Multiple evaluations of the same attribute reference may yield different objects. This production can be customized by overriding the :meth:`~object.__getattribute__` method or the :meth:`~object.__getattr__` -method. The :meth:`!__getattribute__` method is called first and either +method. The :meth:`!__getattribute__` method is called first and either returns a value or raises :exc:`AttributeError` if the attribute is not available. @@ -966,8 +966,8 @@ Slicings pair: object; list A slicing selects a range of items in a sequence object (e.g., a string, tuple -or list). Slicings may be used as expressions or as targets in assignment or -:keyword:`del` statements. The syntax for a slicing: +or list). Slicings may be used as expressions or as targets in assignment or +:keyword:`del` statements. The syntax for a slicing: .. productionlist:: python-grammar slicing: `primary` "[" `slice_list` "]" @@ -980,7 +980,7 @@ or list). Slicings may be used as expressions or as targets in assignment or There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be -interpreted as a slicing. Rather than further complicating the syntax, this is +interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice). @@ -990,13 +990,13 @@ slice list contains no proper slice). single: stop (slice object attribute) single: step (slice object attribute) -The semantics for a slicing are as follows. The primary is indexed (using the +The semantics for a slicing are as follows. The primary is indexed (using the same :meth:`~object.__getitem__` method as normal subscription) with a key that is constructed from the slice list, as -follows. If the slice list contains at least one comma, the key is a tuple +follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the -lone slice item is the key. The conversion of a slice item that is an -expression is that expression. The conversion of a proper slice is a slice +lone slice item is the key. The conversion of a slice item that is an +expression is that expression. The conversion of a proper slice is a slice object (see section :ref:`types`) whose :attr:`~slice.start`, :attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, @@ -1022,7 +1022,7 @@ series of :term:`arguments `: .. productionlist:: python-grammar call: `primary` "(" [`argument_list` [","] | `comprehension`] ")" argument_list: `positional_arguments` ["," `starred_and_keywords`] - : ["," `keywords_arguments`] + : ["," `keywords_arguments`] : | `starred_and_keywords` ["," `keywords_arguments`] : | `keywords_arguments` positional_arguments: `positional_item` ("," `positional_item`)* @@ -1041,35 +1041,35 @@ but does not affect the semantics. The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class -instances, and all objects having a :meth:`~object.__call__` method are callable). All -argument expressions are evaluated before the call is attempted. Please refer +instances, and all objects having a :meth:`~object.__call__` method are callable). All +argument expressions are evaluated before the call is attempted. Please refer to section :ref:`function` for the syntax of formal :term:`parameter` lists. .. XXX update with kwonly args PEP If keyword arguments are present, they are first converted to positional -arguments, as follows. First, a list of unfilled slots is created for the -formal parameters. If there are N positional arguments, they are placed in the -first N slots. Next, for each keyword argument, the identifier is used to +arguments, as follows. First, a list of unfilled slots is created for the +formal parameters. If there are N positional arguments, they are placed in the +first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first -formal parameter name, the first slot is used, and so on). If the slot is +formal parameter name, the first slot is used, and so on). If the slot is already filled, a :exc:`TypeError` exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is -``None``, it fills the slot). When all arguments have been processed, the slots +``None``, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the -function definition. (Default values are calculated, once, when the function is +function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the -corresponding slot; this should usually be avoided.) If there are any unfilled +corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a :exc:`TypeError` exception is -raised. Otherwise, the list of filled slots is used as the argument list for +raised. Otherwise, the list of filled slots is used as the argument list for the call. .. impl-detail:: An implementation may provide built-in functions whose positional parameters do not have names, even if they are 'named' for the purpose of documentation, - and which therefore cannot be supplied by keyword. In CPython, this is the + and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to parse their arguments. @@ -1091,15 +1091,15 @@ there were no excess keyword arguments. single: unpacking; in function calls If the syntax ``*expression`` appears in the function call, ``expression`` must -evaluate to an :term:`iterable`. Elements from these iterables are -treated as if they were additional positional arguments. For the call +evaluate to an :term:`iterable`. Elements from these iterables are +treated as if they were additional positional arguments. For the call ``f(x1, x2, *y, x3, x4)``, if *y* evaluates to a sequence *y1*, ..., *yM*, this is equivalent to a call with M+4 positional arguments *x1*, *x2*, *y1*, ..., *yM*, *x3*, *x4*. A consequence of this is that although the ``*expression`` syntax may appear *after* explicit keyword arguments, it is processed *before* the -keyword arguments (and any ``**expression`` arguments -- see below). So:: +keyword arguments (and any ``**expression`` arguments -- see below). So:: >>> def f(a, b): ... print(a, b) @@ -1145,7 +1145,7 @@ used as positional argument slots or as keyword argument names. Originally proposed by :pep:`448`. A call always returns some value, possibly ``None``, unless it raises an -exception. How this value is computed depends on the type of the callable +exception. How this value is computed depends on the type of the callable object. If it is--- @@ -1157,11 +1157,11 @@ a user-defined function: pair: object; user-defined function pair: object; function - The code block for the function is executed, passing it the argument list. The + The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the - arguments; this is described in section :ref:`function`. When the code block + arguments; this is described in section :ref:`function`. When the code block executes a :keyword:`return` statement, this specifies the return value of the - function call. If execution reaches the end of the code block without + function call. If execution reaches the end of the code block without executing a :keyword:`return` statement, the return value is ``None``. a built-in function or method: @@ -1229,7 +1229,7 @@ The power operator pair: operator; ** The power operator binds more tightly than unary operators on its left; it binds -less tightly than unary operators on its right. The syntax is: +less tightly than unary operators on its right. The syntax is: .. productionlist:: python-grammar power: (`await_expr` | `primary`) ["**" `u_expr`] @@ -1240,7 +1240,7 @@ for the operands): ``-1**2`` results in ``-1``. The power operator has the same semantics as the built-in :func:`pow` function, when called with two arguments: it yields its left argument raised to the power -of its right argument. The numeric arguments are first converted to a common +of its right argument. The numeric arguments are first converted to a common type, and the result is of that type. For int operands, the result has the same type as the operands unless the second @@ -1291,7 +1291,7 @@ operation can be overridden with the :meth:`~object.__pos__` special method. pair: operator; ~ (tilde) The unary ``~`` (invert) operator yields the bitwise inversion of its integer -argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only +argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only applies to integral numbers or to custom objects that override the :meth:`~object.__invert__` special method. @@ -1310,8 +1310,8 @@ Binary arithmetic operations .. index:: triple: binary; arithmetic; operation -The binary arithmetic operations have the conventional priority levels. Note -that some of these operations also apply to certain non-numeric types. Apart +The binary arithmetic operations have the conventional priority levels. Note +that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators: @@ -1325,10 +1325,10 @@ operators and one for additive operators: single: multiplication pair: operator; * (asterisk) -The ``*`` (multiplication) operator yields the product of its arguments. The +The ``*`` (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are converted to a -common real type and then multiplied together. In the latter case, sequence +common real type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence. This operation can be customized using the special :meth:`~object.__mul__` and @@ -1342,7 +1342,7 @@ This operation can be customized using the special :meth:`~object.__mul__` and single: matrix multiplication pair: operator; @ (at) -The ``@`` (at) operator is intended to be used for matrix multiplication. No +The ``@`` (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator. This operation can be customized using the special :meth:`~object.__matmul__` and @@ -1357,10 +1357,10 @@ This operation can be customized using the special :meth:`~object.__matmul__` an pair: operator; // The ``/`` (division) and ``//`` (floor division) operators yield the quotient of -their arguments. The numeric arguments are first converted to a common type. +their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function -applied to the result. Division by zero raises the :exc:`ZeroDivisionError` +applied to the result. Division by zero raises the :exc:`ZeroDivisionError` exception. The division operation can be customized using the special :meth:`~object.__truediv__` @@ -1373,29 +1373,29 @@ The floor division operation can be customized using the special pair: operator; % (percent) The ``%`` (modulo) operator yields the remainder from the division of the first -argument by the second. The numeric arguments are first converted to a common -type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The +argument by the second. The numeric arguments are first converted to a common +type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The arguments may be floating-point numbers, e.g., ``3.14%0.7`` equals ``0.34`` -(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a +(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [#]_. The floor division and modulo operators are connected by the following -identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also +identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, x%y)``. [#]_. In addition to performing the modulo operation on numbers, the ``%`` operator is also overloaded by string objects to perform old-style string formatting (also -known as interpolation). The syntax for string formatting is described in the +known as interpolation). The syntax for string formatting is described in the Python Library Reference, section :ref:`old-string-formatting`. The *modulo* operation can be customized using the special :meth:`~object.__mod__` and :meth:`~object.__rmod__` methods. The floor division operator, the modulo operator, and the :func:`divmod` -function are not defined for complex numbers. Instead, convert to a +function are not defined for complex numbers. Instead, convert to a floating-point number using the :func:`abs` function if appropriate. .. index:: @@ -1403,8 +1403,8 @@ floating-point number using the :func:`abs` function if appropriate. single: operator; + (plus) single: + (plus); binary operator -The ``+`` (addition) operator yields the sum of its arguments. The arguments -must either both be numbers or both be sequences of the same type. In the +The ``+`` (addition) operator yields the sum of its arguments. The arguments +must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common real type and then added together. In the latter case, the sequences are concatenated. @@ -1420,7 +1420,7 @@ This operation can be customized using the special :meth:`~object.__add__` and single: operator; - (minus) single: - (minus); binary operator -The ``-`` (subtraction) operator yields the difference of its arguments. The +The ``-`` (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common real type. This operation can be customized using the special :meth:`~object.__sub__` and @@ -1446,7 +1446,7 @@ The shifting operations have lower priority than the arithmetic operations: .. productionlist:: python-grammar shift_expr: `a_expr` | `shift_expr` ("<<" | ">>") `a_expr` -These operators accept integers as arguments. They shift the first argument to +These operators accept integers as arguments. They shift the first argument to the left or right by the number of bits given by the second argument. The left shift operation can be customized using the special :meth:`~object.__lshift__` @@ -1456,7 +1456,7 @@ and :meth:`~object.__rrshift__` methods. .. index:: pair: exception; ValueError -A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left +A right shift by *n* bits is defined as floor division by ``pow(2,n)``. A left shift by *n* bits is defined as multiplication with ``pow(2,n)``. @@ -1517,7 +1517,7 @@ Comparisons pair: operator; != Unlike C, all comparison operations in Python have the same priority, which is -lower than that of any arithmetic, shifting or bitwise operation. Also unlike +lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like ``a < b < c`` have the interpretation that is conventional in mathematics: @@ -1551,37 +1551,37 @@ Value comparisons ----------------- The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the -values of two objects. The objects do not need to have the same type. +values of two objects. The objects do not need to have the same type. Chapter :ref:`objects` states that objects have a value (in addition to type -and identity). The value of an object is a rather abstract notion in Python: -For example, there is no canonical access method for an object's value. Also, +and identity). The value of an object is a rather abstract notion in Python: +For example, there is no canonical access method for an object's value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators -implement a particular notion of what the value of an object is. One can think +implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation. Because all types are (direct or indirect) subtypes of :class:`object`, they -inherit the default comparison behavior from :class:`object`. Types can +inherit the default comparison behavior from :class:`object`. Types can customize their comparison behavior by implementing :dfn:`rich comparison methods` like :meth:`~object.__lt__`, described in :ref:`customization`. The default behavior for equality comparison (``==`` and ``!=``) is based on -the identity of the objects. Hence, equality comparison of instances with the +the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with -different identities results in inequality. A motivation for this default +different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. ``x is y`` implies ``x == y``). A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; -an attempt raises :exc:`TypeError`. A motivation for this default behavior is +an attempt raises :exc:`TypeError`. A motivation for this default behavior is the lack of a similar invariant as for equality. The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that -have a sensible definition of object value and value-based equality. Such +have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that. @@ -1591,23 +1591,23 @@ built-in types. * Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be compared within and across their types, with the restriction that complex - numbers do not support order comparison. Within the limits of the types + numbers do not support order comparison. Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision. The not-a-number values ``float('NaN')`` and ``decimal.Decimal('NaN')`` are - special. Any ordered comparison of a number to a not-a-number value is false. + special. Any ordered comparison of a number to a not-a-number value is false. A counter-intuitive implication is that not-a-number values are not equal to - themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and - ``x == x`` are all false, while ``x != x`` is true. This behavior is + themselves. For example, if ``x = float('NaN')``, ``3 < x``, ``x < 3`` and + ``x == x`` are all false, while ``x != x`` is true. This behavior is compliant with IEEE 754. -* ``None`` and :data:`NotImplemented` are singletons. :PEP:`8` advises that +* ``None`` and :data:`NotImplemented` are singletons. :PEP:`8` advises that comparisons for singletons should always be done with ``is`` or ``is not``, never the equality operators. * Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be - compared within and across their types. They compare lexicographically using + compared within and across their types. They compare lexicographically using the numeric values of their elements. * Strings (instances of :class:`str`) compare lexicographically using the @@ -1618,13 +1618,13 @@ built-in types. * Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can be compared only within each of their types, with the restriction that ranges - do not support order comparison. Equality comparison across these types + do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises :exc:`TypeError`. Sequences compare lexicographically using comparison of corresponding - elements. The built-in containers typically assume identical objects are - equal to themselves. That lets them bypass equality tests for identical + elements. The built-in containers typically assume identical objects are + equal to themselves. That lets them bypass equality tests for identical objects to improve performance and to maintain their internal invariants. Lexicographical comparison between built-in collections works as follows: @@ -1636,7 +1636,7 @@ built-in types. - Collections that support order comparison are ordered the same as their first unequal elements (for example, ``[1,2,x] <= [1,2,y]`` has the same - value as ``x <= y``). If a corresponding element does not exist, the + value as ``x <= y``). If a corresponding element does not exist, the shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is true). @@ -1650,10 +1650,10 @@ built-in types. and across their types. They define order - comparison operators to mean subset and superset tests. Those relations do + comparison operators to mean subset and superset tests. Those relations do not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` are not equal, nor subsets of one another, nor supersets of one - another). Accordingly, sets are not appropriate arguments for functions + another). Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, :func:`min`, :func:`max`, and :func:`sorted` produce undefined results given a list of sets as inputs). @@ -1716,16 +1716,16 @@ values are an example for not following these rules. Membership test operations -------------------------- -The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in +The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. -``x not in s`` returns the negation of ``x in s``. All built-in sequences and +``x not in s`` returns the negation of ``x in s``. All built-in sequences and set types support this as well as dictionary, for which :keyword:`!in` tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent to ``any(x is e or x == e for e in y)``. For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a -substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are +substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are always considered to be a substring of any other string, so ``"" in "abc"`` will return ``True``. @@ -1742,7 +1742,7 @@ that exception. Lastly, the old-style iteration protocol is tried: if a class defines :meth:`~object.__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative integer index *i* such that ``x is y[i] or x == y[i]``, and no lower integer index -raises the :exc:`IndexError` exception. (If any other exception is raised, it is as +raises the :exc:`IndexError` exception. (If any other exception is raised, it is as if :keyword:`in` raised that exception). .. index:: @@ -1767,8 +1767,8 @@ Identity comparisons -------------------- The operators :keyword:`is` and :keyword:`is not` test for an object's identity: ``x -is y`` is true if and only if *x* and *y* are the same object. An Object's identity -is determined using the :meth:`id` function. ``x is not y`` yields the inverse +is y`` is true if and only if *x* and *y* are the same object. An Object's identity +is determined using the :meth:`id` function. ``x is not y`` yields the inverse truth value. [#]_ @@ -1792,8 +1792,8 @@ Boolean operations In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: ``False``, ``None``, numeric zero of all types, and empty strings and containers -(including strings, tuples, lists, dictionaries, sets and frozensets). All -other values are interpreted as true. User-defined objects can customize their +(including strings, tuples, lists, dictionaries, sets and frozensets). All +other values are interpreted as true. User-defined objects can customize their truth value by providing a :meth:`~object.__bool__` method. .. index:: pair: operator; not @@ -1813,9 +1813,9 @@ returned; otherwise, *y* is evaluated and the resulting value is returned. Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type they return to ``False`` and ``True``, but rather return the last evaluated -argument. This is sometimes useful, e.g., if ``s`` is a string that should be +argument. This is sometimes useful, e.g., if ``s`` is a string that should be replaced by a default value if it is empty, the expression ``s or 'foo'`` yields -the desired value. Because :keyword:`not` has to create a new value, it +the desired value. Because :keyword:`not` has to create a new value, it returns a boolean value regardless of the type of its argument (for example, ``not 'foo'`` produces ``False`` rather than ``''``.) @@ -1908,14 +1908,14 @@ Lambdas Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression ``lambda parameters: expression`` yields a function -object. The unnamed object behaves like a function object defined with: +object. The unnamed object behaves like a function object defined with: .. code-block:: none def (parameters): return expression -See section :ref:`function` for the syntax of parameter lists. Note that +See section :ref:`function` for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations. @@ -1940,16 +1940,16 @@ Expression lists .. index:: pair: object; tuple Except when part of a list or set display, an expression list -containing at least one comma yields a tuple. The length of -the tuple is the number of expressions in the list. The expressions are +containing at least one comma yields a tuple. The length of +the tuple is the number of expressions in the list. The expressions are evaluated from left to right. .. index:: pair: iterable; unpacking single: * (asterisk); in expression lists -An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be -an :term:`iterable`. The iterable is expanded into a sequence of items, +An asterisk ``*`` denotes :dfn:`iterable unpacking`. Its operand must be +an :term:`iterable`. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking. @@ -1976,7 +1976,7 @@ Evaluation order .. index:: pair: evaluation; order -Python evaluates expressions from left to right. Notice that while evaluating +Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. In the following lines, expressions will be evaluated in the arithmetic order of @@ -1999,9 +1999,9 @@ Operator precedence pair: operator; precedence The following table summarizes the operator precedence in Python, from highest -precedence (most binding) to lowest precedence (least binding). Operators in -the same box have the same precedence. Unless the syntax is explicitly given, -operators are binary. Operators in the same box group left to right (except for +precedence (most binding) to lowest precedence (least binding). Operators in +the same box have the same precedence. Unless the syntax is explicitly given, +operators are binary. Operators in the same box group left to right (except for exponentiation and conditional expressions, which group from right to left). Note that comparisons, membership tests, and identity tests, all have the same @@ -2010,68 +2010,68 @@ precedence and have a left-to-right chaining feature as described in the +-----------------------------------------------+-------------------------------------+ -| Operator | Description | +| Operator | Description | +===============================================+=====================================+ -| ``(expressions...)``, | Binding or parenthesized | -| | expression, | -| ``[expressions...]``, | list display, | -| ``{key: value...}``, | dictionary display, | -| ``{expressions...}`` | set display | +| ``(expressions...)``, | Binding or parenthesized | +| | expression, | +| ``[expressions...]``, | list display, | +| ``{key: value...}``, | dictionary display, | +| ``{expressions...}`` | set display | +-----------------------------------------------+-------------------------------------+ -| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | -| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | +| ``x[index]``, ``x[index:index]``, | Subscription, slicing, | +| ``x(arguments...)``, ``x.attribute`` | call, attribute reference | +-----------------------------------------------+-------------------------------------+ -| :keyword:`await x ` | Await expression | +| :keyword:`await x ` | Await expression | +-----------------------------------------------+-------------------------------------+ -| ``**`` | Exponentiation [#]_ | +| ``**`` | Exponentiation [#]_ | +-----------------------------------------------+-------------------------------------+ -| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | +| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | +-----------------------------------------------+-------------------------------------+ -| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | -| | multiplication, division, floor | -| | division, remainder [#]_ | +| ``*``, ``@``, ``/``, ``//``, ``%`` | Multiplication, matrix | +| | multiplication, division, floor | +| | division, remainder [#]_ | +-----------------------------------------------+-------------------------------------+ -| ``+``, ``-`` | Addition and subtraction | +| ``+``, ``-`` | Addition and subtraction | +-----------------------------------------------+-------------------------------------+ -| ``<<``, ``>>`` | Shifts | +| ``<<``, ``>>`` | Shifts | +-----------------------------------------------+-------------------------------------+ -| ``&`` | Bitwise AND | +| ``&`` | Bitwise AND | +-----------------------------------------------+-------------------------------------+ -| ``^`` | Bitwise XOR | +| ``^`` | Bitwise XOR | +-----------------------------------------------+-------------------------------------+ -| ``|`` | Bitwise OR | +| ``|`` | Bitwise OR | +-----------------------------------------------+-------------------------------------+ -| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | -| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | -| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | +| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership | +| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests | +| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | | +-----------------------------------------------+-------------------------------------+ -| :keyword:`not x ` | Boolean NOT | +| :keyword:`not x ` | Boolean NOT | +-----------------------------------------------+-------------------------------------+ -| :keyword:`and` | Boolean AND | +| :keyword:`and` | Boolean AND | +-----------------------------------------------+-------------------------------------+ -| :keyword:`or` | Boolean OR | +| :keyword:`or` | Boolean OR | +-----------------------------------------------+-------------------------------------+ -| :keyword:`if ` -- :keyword:`!else` | Conditional expression | +| :keyword:`if ` -- :keyword:`!else` | Conditional expression | +-----------------------------------------------+-------------------------------------+ -| :keyword:`lambda` | Lambda expression | +| :keyword:`lambda` | Lambda expression | +-----------------------------------------------+-------------------------------------+ -| ``:=`` | Assignment expression | +| ``:=`` | Assignment expression | +-----------------------------------------------+-------------------------------------+ .. rubric:: Footnotes .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be - true numerically due to roundoff. For example, and assuming a platform on which + true numerically due to roundoff. For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + - 1e100``, which is numerically exactly equal to ``1e100``. The function + 1e100``, which is numerically exactly equal to ``1e100``. The function :func:`math.fmod` returns a result whose sign matches the sign of the first argument instead, and so returns ``-1e-100`` in this case. Which approach is more appropriate depends on the application. .. [#] If x is very close to an exact integer multiple of y, it's possible for - ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such + ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such cases, Python returns the latter result, in order to preserve that ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. @@ -2079,7 +2079,7 @@ precedence and have a left-to-right chaining feature as described in the (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A"). While most abstract characters in Unicode are only represented using one code point, there is a number of abstract characters that can in addition be - represented using a sequence of more than one code point. For example, the + represented using a sequence of more than one code point. For example, the abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented as a single :dfn:`precomposed character` at code position U+00C7, or as a sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL @@ -2087,7 +2087,7 @@ precedence and have a left-to-right chaining feature as described in the (COMBINING CEDILLA). The comparison operators on strings compare at the level of Unicode code - points. This may be counter-intuitive to humans. For example, + points. This may be counter-intuitive to humans. For example, ``"\u00C7" == "\u0043\u0327"`` is ``False``, even though both strings represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA". @@ -2097,7 +2097,7 @@ precedence and have a left-to-right chaining feature as described in the .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the :keyword:`is` operator, like those involving comparisons between instance - methods, or constants. Check their documentation for more info. + methods, or constants. Check their documentation for more info. .. [#] The power operator ``**`` binds less tightly than an arithmetic or bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. diff --git a/Doc/reference/import.rst b/Doc/reference/import.rst index d772d1f5345fcd..6cd50405430dc4 100644 --- a/Doc/reference/import.rst +++ b/Doc/reference/import.rst @@ -8,22 +8,22 @@ The import system .. index:: single: import machinery Python code in one :term:`module` gains access to the code in another module -by the process of :term:`importing` it. The :keyword:`import` statement is +by the process of :term:`importing` it. The :keyword:`import` statement is the most common way of invoking the import machinery, but it is not the only -way. Functions such as :func:`importlib.import_module` and built-in +way. Functions such as :func:`importlib.import_module` and built-in :func:`__import__` can also be used to invoke the import machinery. The :keyword:`import` statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local -scope. The search operation of the :keyword:`!import` statement is defined as +scope. The search operation of the :keyword:`!import` statement is defined as a call to the :func:`__import__` function, with the appropriate arguments. The return value of :func:`__import__` is used to perform the name -binding operation of the :keyword:`!import` statement. See the +binding operation of the :keyword:`!import` statement. See the :keyword:`!import` statement for the exact details of that name binding operation. A direct call to :func:`__import__` performs only the module search and, if -found, the module creation operation. While certain side-effects may occur, +found, the module creation operation. While certain side-effects may occur, such as the importing of parent packages, and the updating of various caches (including :data:`sys.modules`), only the :keyword:`import` statement performs a name binding operation. @@ -34,10 +34,10 @@ import system (such as :func:`importlib.import_module`) may choose to bypass :func:`__import__` and use their own solutions to implement import semantics. When a module is first imported, Python searches for the module and if found, -it creates a module object [#fnmo]_, initializing it. If the named module -cannot be found, a :exc:`ModuleNotFoundError` is raised. Python implements various +it creates a module object [#fnmo]_, initializing it. If the named module +cannot be found, a :exc:`ModuleNotFoundError` is raised. Python implements various strategies to search for the named module when the import machinery is -invoked. These strategies can be modified and extended by using various hooks +invoked. These strategies can be modified and extended by using various hooks described in the sections below. .. versionchanged:: 3.3 @@ -51,9 +51,9 @@ described in the sections below. ================ The :mod:`importlib` module provides a rich API for interacting with the -import system. For example :func:`importlib.import_module` provides a +import system. For example :func:`importlib.import_module` provides a recommended, simpler API than built-in :func:`__import__` for invoking the -import machinery. Refer to the :mod:`importlib` library documentation for +import machinery. Refer to the :mod:`importlib` library documentation for additional detail. @@ -66,24 +66,24 @@ Packages Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something -else. To help organize modules and provide a naming hierarchy, Python has a +else. To help organize modules and provide a naming hierarchy, Python has a concept of :term:`packages `. You can think of packages as the directories on a file system and modules as files within directories, but don't take this analogy too literally since -packages and modules need not originate from the file system. For the +packages and modules need not originate from the file system. For the purposes of this documentation, we'll use this convenient analogy of -directories and files. Like file system directories, packages are organized +directories and files. Like file system directories, packages are organized hierarchically, and packages may themselves contain subpackages, as well as regular modules. It's important to keep in mind that all packages are modules, but not all -modules are packages. Or put another way, packages are just a special kind of -module. Specifically, any module that contains a ``__path__`` attribute is +modules are packages. Or put another way, packages are just a special kind of +module. Specifically, any module that contains a ``__path__`` attribute is considered a package. -All modules have a name. Subpackage names are separated from their parent -package name by a dot, akin to Python's standard attribute access syntax. Thus +All modules have a name. Subpackage names are separated from their parent +package name by a dot, akin to Python's standard attribute access syntax. Thus you might have a package called :mod:`email`, which in turn has a subpackage called :mod:`email.mime` and a module within that subpackage called :mod:`email.mime.text`. @@ -96,12 +96,12 @@ Regular packages pair: package; regular Python defines two types of packages, :term:`regular packages ` and :term:`namespace packages `. Regular +package>` and :term:`namespace packages `. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an -``__init__.py`` file. When a regular package is imported, this +``__init__.py`` file. When a regular package is imported, this ``__init__.py`` file is implicitly executed, and the objects it defines are -bound to names in the package's namespace. The ``__init__.py`` file can +bound to names in the package's namespace. The ``__init__.py`` file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported. @@ -118,7 +118,7 @@ package with three subpackages:: __init__.py Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and -``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or +``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or ``parent.three`` will execute ``parent/two/__init__.py`` and ``parent/three/__init__.py`` respectively. @@ -133,10 +133,10 @@ Namespace packages pair: package; portion A namespace package is a composite of various :term:`portions `, -where each portion contributes a subpackage to the parent package. Portions -may reside in different locations on the file system. Portions may also be +where each portion contributes a subpackage to the parent package. Portions +may reside in different locations on the file system. Portions may also be found in zip files, on the network, or anywhere else that Python searches -during import. Namespace packages may or may not correspond directly to +during import. Namespace packages may or may not correspond directly to objects on the file system; they may be virtual modules that have no concrete representation. @@ -146,10 +146,10 @@ perform a new search for package portions on the next import attempt within that package if the path of their parent package (or :data:`sys.path` for a top level package) changes. -With namespace packages, there is no ``parent/__init__.py`` file. In fact, +With namespace packages, there is no ``parent/__init__.py`` file. In fact, there may be multiple ``parent`` directories found during import search, where -each one is provided by a different portion. Thus ``parent/one`` may not be -physically located next to ``parent/two``. In this case, Python will create a +each one is provided by a different portion. Thus ``parent/one`` may not be +physically located next to ``parent/two``. In this case, Python will create a namespace package for the top-level ``parent`` package whenever it or one of its subpackages is imported. @@ -161,12 +161,12 @@ Searching To begin the search, Python needs the :term:`fully qualified ` name of the module (or package, but for the purposes of this discussion, the -difference is immaterial) being imported. This name may come from various +difference is immaterial) being imported. This name may come from various arguments to the :keyword:`import` statement, or from the parameters to the :func:`importlib.import_module` or :func:`__import__` functions. This name will be used in various phases of the import search, and it may be -the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python +the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python first tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``. If any of the intermediate imports fail, a :exc:`ModuleNotFoundError` is raised. @@ -177,20 +177,20 @@ The module cache .. index:: single: sys.modules -The first place checked during import search is :data:`sys.modules`. This +The first place checked during import search is :data:`sys.modules`. This mapping serves as a cache of all modules that have been previously imported, -including the intermediate paths. So if ``foo.bar.baz`` was previously +including the intermediate paths. So if ``foo.bar.baz`` was previously imported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``, -and ``foo.bar.baz``. Each key will have as its value the corresponding module +and ``foo.bar.baz``. Each key will have as its value the corresponding module object. During import, the module name is looked up in :data:`sys.modules` and if present, the associated value is the module satisfying the import, and the -process completes. However, if the value is ``None``, then a -:exc:`ModuleNotFoundError` is raised. If the module name is missing, Python will +process completes. However, if the value is ``None``, then a +:exc:`ModuleNotFoundError` is raised. If the module name is missing, Python will continue searching for the module. -:data:`sys.modules` is writable. Deleting a key may not destroy the +:data:`sys.modules` is writable. Deleting a key may not destroy the associated module (as other modules may hold references to it), but it will invalidate the cache entry for the named module, causing Python to search anew for the named module upon its next @@ -215,24 +215,24 @@ Finders and loaders single: module spec If the named module is not found in :data:`sys.modules`, then Python's import -protocol is invoked to find and load the module. This protocol consists of +protocol is invoked to find and load the module. This protocol consists of two conceptual objects, :term:`finders ` and :term:`loaders `. A finder's job is to determine whether it can find the named module using whatever strategy it knows about. Objects that implement both of these interfaces are referred to as :term:`importers ` - they return themselves when they find that they can load the requested module. -Python includes a number of default finders and importers. The first one +Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate -frozen modules. A third default finder searches an :term:`import path` -for modules. The :term:`import path` is a list of locations that may -name file system paths or zip files. It can also be extended to search +frozen modules. A third default finder searches an :term:`import path` +for modules. The :term:`import path` is a list of locations that may +name file system paths or zip files. It can also be extended to search for any locatable resource, such as those identified by URLs. The import machinery is extensible, so new finders can be added to extend the range and scope of module searching. -Finders do not actually load modules. If they can find the named module, they +Finders do not actually load modules. If they can find the named module, they return a :dfn:`module spec`, an encapsulation of the module's import-related information, which the import machinery then uses when loading the module. @@ -257,18 +257,18 @@ Import hooks pair: hooks; path The import machinery is designed to be extensible; the primary mechanism for -this are the *import hooks*. There are two types of import hooks: *meta +this are the *import hooks*. There are two types of import hooks: *meta hooks* and *import path hooks*. Meta hooks are called at the start of import processing, before any other import processing has occurred, other than :data:`sys.modules` cache look up. This allows meta hooks to override :data:`sys.path` processing, frozen -modules, or even built-in modules. Meta hooks are registered by adding new +modules, or even built-in modules. Meta hooks are registered by adding new finder objects to :data:`sys.meta_path`, as described below. Import path hooks are called as part of :data:`sys.path` (or ``package.__path__``) processing, at the point where their associated path -item is encountered. Import path hooks are registered by adding new callables +item is encountered. Import path hooks are registered by adding new callables to :data:`sys.path_hooks` as described below. @@ -281,27 +281,27 @@ The meta path When the named module is not found in :data:`sys.modules`, Python next searches :data:`sys.meta_path`, which contains a list of meta path finder -objects. These finders are queried in order to see if they know how to handle -the named module. Meta path finders must implement a method called +objects. These finders are queried in order to see if they know how to handle +the named module. Meta path finders must implement a method called :meth:`~importlib.abc.MetaPathFinder.find_spec` which takes three arguments: -a name, an import path, and (optionally) a target module. The meta path +a name, an import path, and (optionally) a target module. The meta path finder can use any strategy it wants to determine whether it can handle the named module or not. If the meta path finder knows how to handle the named module, it returns a -spec object. If it cannot handle the named module, it returns ``None``. If +spec object. If it cannot handle the named module, it returns ``None``. If :data:`sys.meta_path` processing reaches the end of its list without returning -a spec, then a :exc:`ModuleNotFoundError` is raised. Any other exceptions +a spec, then a :exc:`ModuleNotFoundError` is raised. Any other exceptions raised are simply propagated up, aborting the import process. The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path -finders is called with two or three arguments. The first is the fully +finders is called with two or three arguments. The first is the fully qualified name of the module being imported, for example ``foo.bar.baz``. -The second argument is the path entries to use for the module search. For +The second argument is the path entries to use for the module search. For top-level modules, the second argument is ``None``, but for submodules or subpackages, the second argument is the value of the parent package's ``__path__`` attribute. If the appropriate ``__path__`` attribute cannot -be accessed, a :exc:`ModuleNotFoundError` is raised. The third argument +be accessed, a :exc:`ModuleNotFoundError` is raised. The third argument is an existing module object that will be the target of loading later. The import system passes in a target module only during reload. @@ -327,7 +327,7 @@ modules, and one that knows how to import modules from an :term:`import path` .. versionchanged:: 3.4 The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path finders replaced :meth:`!find_module`, which - is now deprecated. While it will continue to work without change, the + is now deprecated. While it will continue to work without change, the import machinery will try it only if the finder does not implement :meth:`~importlib.abc.MetaPathFinder.find_spec`. @@ -344,7 +344,7 @@ Loading ======= If and when a module spec is found, the import machinery will use it (and -the loader it contains) when loading the module. Here is an approximation +the loader it contains) when loading the module. Here is an approximation of what happens during the loading portion of import:: module = None @@ -382,15 +382,15 @@ Note the following details: :data:`sys.modules`, import will have already returned it. * The module will exist in :data:`sys.modules` before the loader - executes the module code. This is crucial because the module code may + executes the module code. This is crucial because the module code may (directly or indirectly) import itself; adding it to :data:`sys.modules` beforehand prevents unbounded recursion in the worst case and multiple loading in the best. * If loading fails, the failing module -- and only the failing module -- - gets removed from :data:`sys.modules`. Any module already in the + gets removed from :data:`sys.modules`. Any module already in the :data:`sys.modules` cache, and any module that was successfully loaded - as a side-effect, must remain in the cache. This contrasts with + as a side-effect, must remain in the cache. This contrasts with reloading where even the failing module is left in :data:`sys.modules`. * After the module is created but before execution, the import machinery @@ -399,7 +399,7 @@ Note the following details: :ref:`later section `. * Module execution is the key moment of loading in which the module's - namespace gets populated. Execution is entirely delegated to the + namespace gets populated. Execution is entirely delegated to the loader, which gets to decide what gets populated and how. * The module created during loading and passed to exec_module() may @@ -407,7 +407,7 @@ Note the following details: .. versionchanged:: 3.4 The import system has taken over the boilerplate responsibilities of - loaders. These were previously performed by the + loaders. These were previously performed by the :meth:`importlib.abc.Loader.load_module` method. Loaders @@ -415,7 +415,7 @@ Loaders Module loaders provide the critical function of loading: module execution. The import machinery calls the :meth:`importlib.abc.Loader.exec_module` -method with a single argument, the module object to execute. Any value +method with a single argument, the module object to execute. Any value returned from :meth:`~importlib.abc.Loader.exec_module` is ignored. Loaders must satisfy the following requirements: @@ -435,8 +435,8 @@ spec with the loader set to ``self``. Module loaders may opt in to creating the module object during loading by implementing a :meth:`~importlib.abc.Loader.create_module` method. It takes one argument, the module spec, and returns the new module object -to use during loading. ``create_module()`` does not need to set any attributes -on the module object. If the method returns ``None``, the +to use during loading. ``create_module()`` does not need to set any attributes +on the module object. If the method returns ``None``, the import machinery will create the new module itself. .. versionadded:: 3.4 @@ -449,16 +449,16 @@ import machinery will create the new module itself. For compatibility with existing loaders, the import machinery will use the ``load_module()`` method of loaders if it exists and the loader does - not also implement ``exec_module()``. However, ``load_module()`` has been + not also implement ``exec_module()``. However, ``load_module()`` has been deprecated and loaders should implement ``exec_module()`` instead. The ``load_module()`` method must implement all the boilerplate loading - functionality described above in addition to executing the module. All + functionality described above in addition to executing the module. All the same constraints apply, with some additional clarification: * If there is an existing module object with the given name in :data:`sys.modules`, the loader must use that existing module. - (Otherwise, :func:`importlib.reload` will not work correctly.) If the + (Otherwise, :func:`importlib.reload` will not work correctly.) If the named module does not exist in :data:`sys.modules`, the loader must create a new module object and add it to :data:`sys.modules`. @@ -490,7 +490,7 @@ When a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the binding is placed in the parent module's namespace to the submodule object. For example, if package ``spam`` has a submodule ``foo``, after importing ``spam.foo``, ``spam`` will have an attribute ``foo`` which is bound to the -submodule. Let's say you have the following directory structure:: +submodule. Let's say you have the following directory structure:: spam/ __init__.py @@ -510,7 +510,7 @@ then executing the following puts name bindings for ``foo`` and ``Foo`` in the Given Python's familiar name binding rules this might seem surprising, but -it's actually a fundamental feature of the import system. The invariant +it's actually a fundamental feature of the import system. The invariant holding is that if you have ``sys.modules['spam']`` and ``sys.modules['spam.foo']`` (as you would after the above import), the latter must appear as the ``foo`` attribute of the former. @@ -521,13 +521,13 @@ Module specs ------------ The import machinery uses a variety of information about each module -during import, especially before loading. Most of the information is -common to all modules. The purpose of a module's spec is to encapsulate +during import, especially before loading. Most of the information is +common to all modules. The purpose of a module's spec is to encapsulate this import-related information on a per-module basis. Using a spec during import allows state to be transferred between import system components, e.g. between the finder that creates the module spec -and the loader that executes it. Most importantly, it allows the +and the loader that executes it. Most importantly, it allows the import machinery to perform the boilerplate operations of loading, whereas without a module spec the loader had that responsibility. @@ -566,7 +566,7 @@ consulted when traversing a package's :attr:`!__path__`. A package's ``__init__.py`` file may set or alter the package's :attr:`~module.__path__` attribute, and this was typically the way namespace packages were implemented -prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no +prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no longer need to supply ``__init__.py`` files containing only :attr:`!__path__` manipulation code; the import machinery automatically sets :attr:`!__path__` correctly for the namespace package. @@ -579,16 +579,16 @@ attributes set above, and in the module's spec, you can more explicitly control the repr of module objects. If the module has a spec (``__spec__``), the import machinery will try -to generate a repr from it. If that fails or there is no spec, the import +to generate a repr from it. If that fails or there is no spec, the import system will craft a default repr using whatever information is available -on the module. It will try to use the ``module.__name__``, +on the module. It will try to use the ``module.__name__``, ``module.__file__``, and ``module.__loader__`` as input into the repr, with defaults for whatever information is missing. Here are the exact rules used: * If the module has a ``__spec__`` attribute, the information in the spec - is used to generate the repr. The "name", "loader", "origin", and + is used to generate the repr. The "name", "loader", "origin", and "has_location" attributes are consulted. * If the module has a ``__file__`` attribute, this is used as part of the @@ -641,7 +641,7 @@ The Path Based Finder As mentioned previously, Python comes with several default meta path finders. One of these, called the :term:`path based finder` (:class:`~importlib.machinery.PathFinder`), searches an :term:`import path`, -which contains a list of :term:`path entries `. Each path +which contains a list of :term:`path entries `. Each path entry names a location to search for modules. The path based finder itself doesn't know how to import anything. Instead, it @@ -655,21 +655,21 @@ shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport` module in the standard library, the default path entry finders also handle loading all of these file types (other than shared libraries) from zipfiles. -Path entries need not be limited to file system locations. They can refer to +Path entries need not be limited to file system locations. They can refer to URLs, database queries, or any other location that can be specified as a string. The path based finder provides additional hooks and protocols so that you -can extend and customize the types of searchable path entries. For example, +can extend and customize the types of searchable path entries. For example, if you wanted to support path entries as network URLs, you could write a hook -that implements HTTP semantics to find modules on the web. This hook (a +that implements HTTP semantics to find modules on the web. This hook (a callable) would return a :term:`path entry finder` supporting the protocol described below, which was then used to get a loader for the module from the web. A word of warning: this section and the previous both use the term *finder*, distinguishing between them by using the terms :term:`meta path finder` and -:term:`path entry finder`. These two types of finders are very similar, +:term:`path entry finder`. These two types of finders are very similar, support similar protocols, and function in similar ways during the import process, but it's important to keep in mind that they are subtly different. In particular, meta path finders operate at the beginning of the import @@ -692,7 +692,7 @@ Path entry finders The :term:`path based finder` is responsible for finding and loading Python modules and packages whose location is specified with a string -:term:`path entry`. Most path entries name locations in the file system, +:term:`path entry`. Most path entries name locations in the file system, but they need not be limited to this. As a meta path finder, the :term:`path based finder` implements the @@ -701,50 +701,50 @@ described, however it exposes additional hooks that can be used to customize how modules are found and loaded from the :term:`import path`. Three variables are used by the :term:`path based finder`, :data:`sys.path`, -:data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__`` -attributes on package objects are also used. These provide additional ways +:data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__`` +attributes on package objects are also used. These provide additional ways that the import machinery can be customized. :data:`sys.path` contains a list of strings providing search locations for -modules and packages. It is initialized from the :envvar:`PYTHONPATH` +modules and packages. It is initialized from the :envvar:`PYTHONPATH` environment variable and various other installation- and -implementation-specific defaults. Entries in :data:`sys.path` can name +implementation-specific defaults. Entries in :data:`sys.path` can name directories on the file system, zip files, and potentially other "locations" (see the :mod:`site` module) that should be searched for modules, such as -URLs, or database queries. Only strings should be present on +URLs, or database queries. Only strings should be present on :data:`sys.path`; all other data types are ignored. The :term:`path based finder` is a :term:`meta path finder`, so the import machinery begins the :term:`import path` search by calling the path based finder's :meth:`~importlib.machinery.PathFinder.find_spec` method as -described previously. When the ``path`` argument to +described previously. When the ``path`` argument to :meth:`~importlib.machinery.PathFinder.find_spec` is given, it will be a list of string paths to traverse - typically a package's ``__path__`` -attribute for an import within that package. If the ``path`` argument is +attribute for an import within that package. If the ``path`` argument is ``None``, this indicates a top level import and :data:`sys.path` is used. The path based finder iterates over every entry in the search path, and for each of these, looks for an appropriate :term:`path entry finder` (:class:`~importlib.abc.PathEntryFinder`) for the -path entry. Because this can be an expensive operation (e.g. there may be +path entry. Because this can be an expensive operation (e.g. there may be ``stat()`` call overheads for this search), the path based finder maintains -a cache mapping path entries to path entry finders. This cache is maintained +a cache mapping path entries to path entry finders. This cache is maintained in :data:`sys.path_importer_cache` (despite the name, this cache actually stores finder objects rather than being limited to :term:`importer` objects). In this way, the expensive search for a particular :term:`path entry` -location's :term:`path entry finder` need only be done once. User code is +location's :term:`path entry finder` need only be done once. User code is free to remove cache entries from :data:`sys.path_importer_cache` forcing the path based finder to perform the path entry search again. If the path entry is not present in the cache, the path based finder iterates -over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry +over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry hooks ` in this list is called with a single argument, the -path entry to be searched. This callable may either return a :term:`path +path entry to be searched. This callable may either return a :term:`path entry finder` that can handle the path entry, or it may raise -:exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to +:exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to signal that the hook cannot find a :term:`path entry finder` -for that :term:`path entry`. The -exception is ignored and :term:`import path` iteration continues. The hook +for that :term:`path entry`. The +exception is ignored and :term:`import path` iteration continues. The hook should expect either a string or bytes object; the encoding of bytes objects is up to the hook (e.g. it may be a file system encoding, UTF-8, or something else), and if the hook cannot decode the argument, it should raise @@ -780,7 +780,7 @@ the :meth:`~importlib.abc.PathEntryFinder.find_spec` method. :meth:`~importlib.abc.PathEntryFinder.find_spec` takes two arguments: the fully qualified name of the module being imported, and the (optional) target -module. ``find_spec()`` returns a fully populated spec for the module. +module. ``find_spec()`` returns a fully populated spec for the module. This spec will always have "loader" set (with one exception). To indicate to the import machinery that the spec represents a namespace @@ -794,12 +794,12 @@ a list containing the portion. are now deprecated, but will be used if ``find_spec()`` is not defined. Older path entry finders may implement one of these two deprecated methods - instead of ``find_spec()``. The methods are still respected for the - sake of backward compatibility. However, if ``find_spec()`` is + instead of ``find_spec()``. The methods are still respected for the + sake of backward compatibility. However, if ``find_spec()`` is implemented on the path entry finder, the legacy methods are ignored. :meth:`!find_loader` takes one argument, the - fully qualified name of the module being imported. ``find_loader()`` + fully qualified name of the module being imported. ``find_loader()`` returns a 2-tuple where the first item is the loader and the second item is a namespace :term:`portion`. @@ -812,7 +812,7 @@ a list containing the portion. The ``find_module()`` method on path entry finders is deprecated, as it does not allow the path entry finder to contribute portions to - namespace packages. If both ``find_loader()`` and ``find_module()`` + namespace packages. If both ``find_loader()`` and ``find_module()`` exist on a path entry finder, the import system will always call ``find_loader()`` in preference to ``find_module()``. @@ -892,10 +892,10 @@ Special considerations for __main__ =================================== The :mod:`__main__` module is a special case relative to Python's import -system. As noted :ref:`elsewhere `, the ``__main__`` module +system. As noted :ref:`elsewhere `, the ``__main__`` module is directly initialized at interpreter startup, much like :mod:`sys` and -:mod:`builtins`. However, unlike those two, it doesn't strictly -qualify as a built-in module. This is because the manner in which +:mod:`builtins`. However, unlike those two, it doesn't strictly +qualify as a built-in module. This is because the manner in which ``__main__`` is initialized depends on the flags and other options with which the interpreter is invoked. @@ -936,7 +936,7 @@ to populate the ``__main__`` namespace, and not during normal import. References ========== -The import machinery has evolved considerably since Python's early days. The +The import machinery has evolved considerably since Python's early days. The original `specification for packages `_ is still available to read, although some details have changed since the writing of that document. @@ -945,7 +945,7 @@ The original specification for :data:`sys.meta_path` was :pep:`302`, with subsequent extension in :pep:`420`. :pep:`420` introduced :term:`namespace packages ` for -Python 3.3. :pep:`420` also introduced the :meth:`!find_loader` protocol as an +Python 3.3. :pep:`420` also introduced the :meth:`!find_loader` protocol as an alternative to :meth:`!find_module`. :pep:`366` describes the addition of the ``__package__`` attribute for @@ -958,8 +958,8 @@ proposed ``__name__`` for semantics :pep:`366` would eventually specify for :pep:`338` defines executing modules as scripts. :pep:`451` adds the encapsulation of per-module import state in spec -objects. It also off-loads most of the boilerplate responsibilities of -loaders back onto the import machinery. These changes allow the +objects. It also off-loads most of the boilerplate responsibilities of +loaders back onto the import machinery. These changes allow the deprecation of several APIs in the import system and also addition of new methods to finders and loaders. @@ -969,7 +969,7 @@ methods to finders and loaders. .. [#fnlo] The importlib implementation avoids using the return value directly. Instead, it gets the module object by looking the module name up - in :data:`sys.modules`. The indirect effect of this is that an imported - module may replace itself in :data:`sys.modules`. This is + in :data:`sys.modules`. The indirect effect of this is that an imported + module may replace itself in :data:`sys.modules`. This is implementation-specific behavior that is not guaranteed to work in other Python implementations. diff --git a/Doc/reference/introduction.rst b/Doc/reference/introduction.rst index 444acac374a690..7947ddddc3440e 100644 --- a/Doc/reference/introduction.rst +++ b/Doc/reference/introduction.rst @@ -22,7 +22,7 @@ language, maybe you could volunteer your time --- or invent a cloning machine It is dangerous to add too many implementation details to a language reference document --- the implementation may change, and other implementations of the -same language may work differently. On the other hand, CPython is the one +same language may work differently. On the other hand, CPython is the one Python implementation in widespread use (although alternate implementations continue to gain support), and its particular quirks are sometimes worth being mentioned, especially where the implementation imposes additional limitations. @@ -30,7 +30,7 @@ Therefore, you'll find short "implementation notes" sprinkled throughout the text. Every Python implementation comes with a number of built-in and standard -modules. These are documented in :ref:`library-index`. A few built-in modules +modules. These are documented in :ref:`library-index`. A few built-in modules are mentioned when they interact in a significant way with the language definition. @@ -51,21 +51,21 @@ CPython New language features generally appear here first. Jython - Python implemented in Java. This implementation can be used as a scripting + Python implemented in Java. This implementation can be used as a scripting language for Java applications, or can be used to create applications using the - Java class libraries. It is also often used to create tests for Java libraries. + Java class libraries. It is also often used to create tests for Java libraries. More information can be found at `the Jython website `_. Python for .NET This implementation actually uses the CPython implementation, but is a managed - .NET application and makes .NET libraries available. It was created by Brian - Lloyd. For more information, see the `Python for .NET home page + .NET application and makes .NET libraries available. It was created by Brian + Lloyd. For more information, see the `Python for .NET home page `_. IronPython - An alternate Python for .NET. Unlike Python.NET, this is a complete Python + An alternate Python for .NET. Unlike Python.NET, this is a complete Python implementation that generates IL, and compiles Python code directly to .NET - assemblies. It was created by Jim Hugunin, the original creator of Jython. For + assemblies. It was created by Jim Hugunin, the original creator of Jython. For more information, see `the IronPython website `_. PyPy @@ -73,12 +73,12 @@ PyPy advanced features not found in other implementations like stackless support and a Just in Time compiler. One of the goals of the project is to encourage experimentation with the language itself by making it easier to modify the - interpreter (since it is written in Python). Additional information is + interpreter (since it is written in Python). Additional information is available on `the PyPy project's home page `_. Each of these implementations varies in some way from the language as documented in this manual, or introduces specific information beyond what's covered in the -standard Python documentation. Please refer to the implementation-specific +standard Python documentation. Please refer to the implementation-specific documentation to determine what else you need to know about the specific implementation you're using. diff --git a/Doc/reference/lexical_analysis.rst b/Doc/reference/lexical_analysis.rst index 567c70111c20ec..90d8c2f4b0e839 100644 --- a/Doc/reference/lexical_analysis.rst +++ b/Doc/reference/lexical_analysis.rst @@ -7,14 +7,14 @@ Lexical analysis .. index:: lexical analysis, parser, token -A Python program is read by a *parser*. Input to the parser is a stream of +A Python program is read by a *parser*. Input to the parser is a stream of :term:`tokens `, generated by the *lexical analyzer* (also known as the *tokenizer*). This chapter describes how the lexical analyzer breaks a file into tokens. Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see :pep:`3120` -for details. If the source file cannot be decoded, a :exc:`SyntaxError` is +for details. If the source file cannot be decoded, a :exc:`SyntaxError` is raised. @@ -48,10 +48,10 @@ Physical lines -------------- A physical line is a sequence of characters terminated by an end-of-line -sequence. In source files and strings, any of the standard platform line +sequence. In source files and strings, any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), -or the old Macintosh form using the ASCII CR (return) character. All of these +or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line. @@ -69,7 +69,7 @@ Comments single: # (hash); comment A comment starts with a hash character (``#``) that is not part of a string -literal, and ends at the end of the physical line. A comment signifies the end +literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax. @@ -97,7 +97,7 @@ which is recognized also by GNU Emacs, and :: which is recognized by Bram Moolenaar's VIM. -If no encoding declaration is found, the default encoding is UTF-8. If the +If no encoding declaration is found, the default encoding is UTF-8. If the implicit or explicit encoding of a file is UTF-8, an initial UTF-8 byte-order mark (``b'\xef\xbb\xbf'``) is ignored rather than being a syntax error. @@ -118,17 +118,17 @@ Two or more physical lines may be joined into logical lines using backslash characters (``\``), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line -character. For example:: +character. For example:: if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1 -A line ending in a backslash cannot carry a comment. A backslash does not -continue a comment. A backslash does not continue a token except for string +A line ending in a backslash cannot carry a comment. A backslash does not +continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across -physical lines using a backslash). A backslash is illegal elsewhere on a line +physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal. @@ -145,9 +145,9 @@ more than one physical line without using backslashes. For example:: 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year -Implicitly continued lines can carry comments. The indentation of the -continuation lines is not important. Blank continuation lines are allowed. -There is no NEWLINE token between implicit continuation lines. Implicitly +Implicitly continued lines can carry comments. The indentation of the +continuation lines is not important. Blank continuation lines are allowed. +There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments. @@ -181,9 +181,9 @@ the grouping of statements. Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of -eight (this is intended to be the same rule as used by Unix). The total number +eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line's -indentation. Indentation cannot be split over multiple physical lines using +indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation. @@ -193,11 +193,11 @@ in a way that makes the meaning dependent on the worth of a tab in spaces; a **Cross-platform compatibility note:** because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the -indentation in a single source file. It should also be noted that different +indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level. A formfeed character may be present at the start of the line; it will be ignored -for the indentation calculations above. Formfeed characters occurring elsewhere +for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero). @@ -208,11 +208,11 @@ The indentation levels of consecutive lines are used to generate as follows. Before the first line of the file is read, a single zero is pushed on the stack; -this will never be popped off again. The numbers pushed on the stack will -always be strictly increasing from bottom to top. At the beginning of each +this will never be popped off again. The numbers pushed on the stack will +always be strictly increasing from bottom to top. At the beginning of each logical line, the line's indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and -one :data:`!INDENT` token is generated. If it is smaller, it *must* be one of the +one :data:`!INDENT` token is generated. If it is smaller, it *must* be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a :data:`!DEDENT` token is generated. At the end of the file, a :data:`!DEDENT` token is generated for each number @@ -255,7 +255,7 @@ Whitespace between tokens Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate -tokens. Whitespace is needed between two tokens only if their concatenation +tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token. For example, ``ab`` is one token, but ``a b`` is two tokens. However, ``+a`` and ``+ a`` both produce two tokens, ``+`` and ``a``, as ``+a`` is not a valid token. @@ -375,7 +375,7 @@ Keywords single: reserved word The following names are used as reserved words, or *keywords* of the -language, and cannot be used as ordinary identifiers. They must be spelled +language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here: .. sourcecode:: text @@ -422,7 +422,7 @@ identifier names. Reserved classes of identifiers ------------------------------- -Certain classes of identifiers (besides keywords) have special meanings. These +Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters: @@ -454,12 +454,12 @@ characters: System-defined names, informally known as "dunder" names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the :ref:`specialnames` section and elsewhere. - More will likely be defined in future versions of Python. *Any* use of ``__*__`` names, + More will likely be defined in future versions of Python. *Any* use of ``__*__`` names, in any context, that does not follow explicitly documented use, is subject to breakage without warning. ``__*`` - Class-private names. Names in this category, when used within the context of a + Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between "private" attributes of base and derived classes. See section :ref:`atom-identifiers`. @@ -522,7 +522,7 @@ declaration is given in the source file; see section :ref:`encodings`. single: '''; string literal In plain English: Both types of literals can be enclosed in matching single quotes -(``'``) or double quotes (``"``). They can also be enclosed in matching groups +(``'``) or double quotes (``"``). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as *triple-quoted strings*). The backslash (``\``) character is used to give special meaning to otherwise ordinary characters like ``n``, which means 'newline' when @@ -535,7 +535,7 @@ See :ref:`escape sequences ` below for examples. single: b"; bytes literal Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an -instance of the :class:`bytes` type instead of the :class:`str` type. They +instance of the :class:`bytes` type instead of the :class:`str` type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes. @@ -546,7 +546,7 @@ must be expressed with escapes. Both string and bytes literals may optionally be prefixed with a letter ``'r'`` or ``'R'``; such constructs are called :dfn:`raw string literals` and :dfn:`raw bytes literals` respectively and treat backslashes as -literal characters. As a result, in raw string literals, ``'\U'`` and ``'\u'`` +literal characters. As a result, in raw string literals, ``'\U'`` and ``'\u'`` escapes are not treated specially. .. versionadded:: 3.3 @@ -562,12 +562,12 @@ escapes are not treated specially. single: f"; formatted string literal A string literal with ``'f'`` or ``'F'`` in its prefix is a -:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be +:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw formatted strings are possible, but formatted bytes literals are not. In triple-quoted literals, unescaped newlines and quotes are allowed (and are -retained), except that three unescaped quotes in a row terminate the literal. (A +retained), except that three unescaped quotes in a row terminate the literal. (A "quote" is the character used to open the literal, i.e. either ``'`` or ``"``.) .. index:: physical line, escape sequence, Standard C, C @@ -593,7 +593,7 @@ Escape sequences Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by -Standard C. The recognized escape sequences are: +Standard C. The recognized escape sequences are: +-------------------------+---------------------------------+-------+ | Escape Sequence | Meaning | Notes | @@ -682,16 +682,16 @@ Notes: Exactly four hex digits are required. (7) - Any Unicode character can be encoded this way. Exactly eight hex digits + Any Unicode character can be encoded this way. Exactly eight hex digits are required. .. index:: unrecognized escape sequence Unlike Standard C, all unrecognized escape sequences are left in the string -unchanged, i.e., *the backslash is left in the result*. (This behavior is +unchanged, i.e., *the backslash is left in the result*. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output -is more easily recognized as broken.) It is also important to note that the +is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals. @@ -706,8 +706,8 @@ Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, ``r"\""`` is a valid string literal consisting of two characters: a backslash and a double quote; ``r"\"`` is not a valid string literal (even a raw string cannot end in an odd number of -backslashes). Specifically, *a raw literal cannot end in a single backslash* -(since the backslash would escape the following quote character). Note also +backslashes). Specifically, *a raw literal cannot end in a single backslash* +(since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, *not* as a line continuation. @@ -719,8 +719,8 @@ String literal concatenation Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same -as their concatenation. Thus, ``"hello" 'world'`` is equivalent to -``"helloworld"``. This feature can be used to reduce the number of backslashes +as their concatenation. Thus, ``"hello" 'world'`` is equivalent to +``"helloworld"``. This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:: @@ -729,8 +729,8 @@ comments to parts of strings, for example:: ) Note that this feature is defined at the syntactical level, but implemented at -compile time. The '+' operator must be used to concatenate string expressions -at run time. Also note that literal concatenation can use different quoting +compile time. The '+' operator must be used to concatenate string expressions +at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings), and formatted string literals may be concatenated with plain string literals. @@ -756,13 +756,13 @@ f-strings .. versionadded:: 3.6 A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal -that is prefixed with ``'f'`` or ``'F'``. These strings may contain +that is prefixed with ``'f'`` or ``'F'``. These strings may contain replacement fields, which are expressions delimited by curly braces ``{}``. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time. Escape sequences are decoded like in ordinary string literals (except when -a literal is also marked as a raw string). After decoding, the grammar +a literal is also marked as a raw string). After decoding, the grammar for the contents of the string is: .. productionlist:: python-grammar @@ -777,22 +777,22 @@ for the contents of the string is: The parts of the string outside curly braces are treated literally, except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced -with the corresponding single curly brace. A single opening curly +with the corresponding single curly brace. A single opening curly bracket ``'{'`` marks a replacement field, which starts with a Python expression. To display both the expression text and its value after evaluation, (useful in debugging), an equal sign ``'='`` may be added after the expression. A conversion field, introduced by an exclamation point ``'!'`` may -follow. A format specifier may also be appended, introduced by a colon ``':'``. +follow. A format specifier may also be appended, introduced by a colon ``':'``. A replacement field ends with a closing curly bracket ``'}'``. Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. -An empty expression is not allowed, and both :keyword:`lambda` and +An empty expression is not allowed, and both :keyword:`lambda` and assignment expressions ``:=`` must be surrounded by explicit parentheses. Each expression is evaluated in the context where the formatted string literal -appears, in order from left to right. Replacement expressions can contain +appears, in order from left to right. Replacement expressions can contain newlines in both single-quoted and triple-quoted f-strings and they can contain -comments. Everything that comes after a ``#`` inside a replacement field +comments. Everything that comes after a ``#`` inside a replacement field is a comment (even closing braces and quotes). In that case, replacement fields must be closed in a different line. @@ -823,13 +823,13 @@ declared. The equal sign ``'='``. If a conversion is specified, the result of evaluating the expression -is converted before formatting. Conversion ``'!s'`` calls :func:`str` on +is converted before formatting. Conversion ``'!s'`` calls :func:`str` on the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`. -The result is then formatted using the :func:`format` protocol. The +The result is then formatted using the :func:`format` protocol. The format specifier is passed to the :meth:`~object.__format__` method of the -expression or conversion result. An empty string is passed when the -format specifier is omitted. The formatted result is then included in +expression or conversion result. An empty string is passed when the +format specifier is omitted. The formatted result is then included in the final value of the whole string. Top-level format specifiers may include nested replacement fields. These nested @@ -976,7 +976,7 @@ For example, ``_123``, ``321_``, and ``123__321`` are *not* valid literals. Integers can be specified in binary (base 2), octal (base 8), or hexadecimal (base 16) using the prefixes ``0b``, ``0o`` and ``0x``, respectively. Hexadecimal digits 10 through 15 are represented by letters ``A``-``F``, -case-insensitive. For example:: +case-insensitive. For example:: 0b100110111 0b_1110_0101 @@ -1175,7 +1175,7 @@ The following tokens serve as delimiters in the grammar: -> += -= *= /= //= %= @= &= |= ^= >>= <<= **= -The period can also occur in floating-point and imaginary literals. A sequence +The period can also occur in floating-point and imaginary literals. A sequence of three periods has a special meaning as an ellipsis literal. The second half of the list, the augmented assignment operators, serve lexically as delimiters, but also perform an operation. @@ -1187,7 +1187,7 @@ tokens or are otherwise significant to the lexical analyzer: ' " # \ -The following printing ASCII characters are not used in Python. Their +The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error: .. code-block:: none diff --git a/Doc/reference/simple_stmts.rst b/Doc/reference/simple_stmts.rst index 2a72af4e9a3299..3e265808c9190f 100644 --- a/Doc/reference/simple_stmts.rst +++ b/Doc/reference/simple_stmts.rst @@ -8,7 +8,7 @@ Simple statements .. index:: pair: simple; statement A simple statement is comprised within a single logical line. Several simple -statements may occur on a single line separated by semicolons. The syntax for +statements may occur on a single line separated by semicolons. The syntax for simple statements is: .. productionlist:: python-grammar @@ -43,8 +43,8 @@ Expression statements Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful -result; in Python, procedures return the value ``None``). Other uses of -expression statements are allowed and occasionally useful. The syntax for an +result; in Python, procedures return the value ``None``). Other uses of +expression statements are allowed and occasionally useful. The syntax for an expression statement is: .. productionlist:: python-grammar @@ -110,7 +110,7 @@ Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is -unacceptable. The rules observed by various types and the exceptions raised are +unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section :ref:`types`). .. index:: triple: target; list; assignment @@ -129,10 +129,10 @@ square brackets, is recursively defined as follows. * If the target list contains one target prefixed with an asterisk, called a "starred" target: The object must be an iterable with at least as many items - as there are targets in the target list, minus one. The first items of the + as there are targets in the target list, minus one. The first items of the iterable are assigned, from left to right, to the targets before the starred - target. The final items of the iterable are assigned to the targets after - the starred target. A list of the remaining items in the iterable is then + target. The final items of the iterable are assigned to the targets after + the starred target. A list of the remaining items in the iterable is then assigned to the starred target (the list can be empty). * Else: The object must be an iterable with the same number of items as there @@ -152,15 +152,15 @@ Assignment of an object to a single target is recursively defined as follows. .. index:: single: destructor - The name is rebound if it was already bound. This may cause the reference + The name is rebound if it was already bound. This may cause the reference count for the object previously bound to the name to reach zero, causing the object to be deallocated and its destructor (if it has one) to be called. .. index:: pair: attribute; assignment * If the target is an attribute reference: The primary expression in the - reference is evaluated. It should yield an object with assignable attributes; - if this is not the case, :exc:`TypeError` is raised. That object is then + reference is evaluated. It should yield an object with assignable attributes; + if this is not the case, :exc:`TypeError` is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily :exc:`AttributeError`). @@ -170,8 +170,8 @@ Assignment of an object to a single target is recursively defined as follows. Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the right-hand side expression, ``a.x`` can access either an instance attribute or (if no instance attribute exists) a class - attribute. The left-hand side target ``a.x`` is always set as an instance attribute, - creating it if necessary. Thus, the two occurrences of ``a.x`` do not + attribute. The left-hand side target ``a.x`` is always set as an instance attribute, + creating it if necessary. Thus, the two occurrences of ``a.x`` do not necessarily refer to the same attribute: if the right-hand side expression refers to a class attribute, the left-hand side creates a new instance attribute as the target of the assignment:: @@ -189,8 +189,8 @@ Assignment of an object to a single target is recursively defined as follows. pair: object; mutable * If the target is a subscription: The primary expression in the reference is - evaluated. It should yield either a mutable sequence object (such as a list) - or a mapping object (such as a dictionary). Next, the subscript expression is + evaluated. It should yield either a mutable sequence object (such as a list) + or a mapping object (such as a dictionary). Next, the subscript expression is evaluated. .. index:: @@ -198,10 +198,10 @@ Assignment of an object to a single target is recursively defined as follows. pair: object; list If the primary is a mutable sequence object (such as a list), the subscript - must yield an integer. If it is negative, the sequence's length is added to - it. The resulting value must be a nonnegative integer less than the + must yield an integer. If it is negative, the sequence's length is added to + it. The resulting value must be a nonnegative integer less than the sequence's length, and the sequence is asked to assign the assigned object to - its item with that index. If the index is out of range, :exc:`IndexError` is + its item with that index. If the index is out of range, :exc:`IndexError` is raised (assignment to a subscripted sequence cannot add new items to a list). .. index:: @@ -211,7 +211,7 @@ Assignment of an object to a single target is recursively defined as follows. If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping's key type, and the mapping is then asked to create a key/value pair which maps the subscript to the assigned - object. This can either replace an existing key/value pair with the same key + object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed). For user-defined objects, the :meth:`~object.__setitem__` method is called with @@ -220,14 +220,14 @@ Assignment of an object to a single target is recursively defined as follows. .. index:: pair: slicing; assignment * If the target is a slicing: The primary expression in the reference is - evaluated. It should yield a mutable sequence object (such as a list). The - assigned object should be a sequence object of the same type. Next, the lower + evaluated. It should yield a mutable sequence object (such as a list). The + assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults - are zero and the sequence's length. The bounds should evaluate to integers. - If either bound is negative, the sequence's length is added to it. The + are zero and the sequence's length. The bounds should evaluate to integers. + If either bound is negative, the sequence's length is added to it. The resulting bounds are clipped to lie between zero and the sequence's length, - inclusive. Finally, the sequence object is asked to replace the slice with - the items of the assigned sequence. The length of the slice may be different + inclusive. Finally, the sequence object is asked to replace the slice with + the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it. @@ -240,7 +240,7 @@ Assignment of an object to a single target is recursively defined as follows. Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are 'simultaneous' (for example ``a, b = b, a`` swaps two variables), overlaps *within* the collection of assigned-to -variables occur left-to-right, sometimes resulting in confusion. For instance, +variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints ``[0, 2]``:: x = [0, 1] @@ -291,7 +291,7 @@ symbols.) An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns -the result to the original target. The target is only evaluated once. +the result to the original target. The target is only evaluated once. An augmented assignment statement like ``x += 1`` can be rewritten as ``x = x + 1`` to achieve a similar, but not exactly equal effect. In the augmented @@ -300,7 +300,7 @@ is performed *in-place*, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead. Unlike normal assignments, augmented assignments evaluate the left-hand side -*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first +*before* evaluating the right-hand side. For example, ``a[i] += f(x)`` first looks-up ``a[i]``, then it evaluates ``f(x)`` and performs the addition, and lastly, it writes the result back to ``a[i]``. @@ -407,15 +407,15 @@ The extended form, ``assert expression1, expression2``, is equivalent to :: pair: exception; AssertionError These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to -the built-in variables with those names. In the current implementation, the +the built-in variables with those names. In the current implementation, the built-in variable ``__debug__`` is ``True`` under normal circumstances, -``False`` when optimization is requested (command line option :option:`-O`). The current +``False`` when optimization is requested (command line option :option:`-O`). The current code generator emits no code for an :keyword:`assert` statement when optimization is -requested at compile time. Note that it is unnecessary to include the source +requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace. -Assignments to :const:`__debug__` are illegal. The value for the built-in variable +Assignments to :const:`__debug__` are illegal. The value for the built-in variable is determined when the interpreter starts. @@ -465,7 +465,7 @@ Deletion of a target list recursively deletes each target, from left to right. Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a :keyword:`global` statement -in the same code block. If the name is unbound, a :exc:`NameError` exception +in the same code block. If the name is unbound, a :exc:`NameError` exception will be raised. .. index:: pair: attribute; deletion @@ -514,7 +514,7 @@ becomes the :attr:`StopIteration.value` attribute. In an asynchronous generator function, an empty :keyword:`return` statement indicates that the asynchronous generator is done and will cause -:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return` +:exc:`StopAsyncIteration` to be raised. A non-empty :keyword:`!return` statement is a syntax error in an asynchronous generator function. .. _yield: @@ -546,7 +546,7 @@ are equivalent to the yield expression statements :: (yield from ) Yield expressions and statements are only used when defining a :term:`generator` -function, and are only used in the body of the generator function. Using :keyword:`yield` +function, and are only used in the body of the generator function. Using :keyword:`yield` in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. @@ -573,7 +573,7 @@ If there isn't currently an active exception, a :exc:`RuntimeError` exception is indicating that this is an error. Otherwise, :keyword:`raise` evaluates the first expression as the exception -object. It must be either a subclass or an instance of :class:`BaseException`. +object. It must be either a subclass or an instance of :class:`BaseException`. If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments. @@ -624,9 +624,9 @@ exceptions will be printed: RuntimeError: Something bad happened A similar mechanism works implicitly if a new exception is raised when -an exception is already being handled. An exception may be handled +an exception is already being handled. An exception may be handled when an :keyword:`except` or :keyword:`finally` clause, or a -:keyword:`with` statement, is used. The previous exception is then +:keyword:`with` statement, is used. The previous exception is then attached as the new exception's :attr:`~BaseException.__context__` attribute: .. code-block:: pycon @@ -729,7 +729,7 @@ The :keyword:`!continue` statement :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or :keyword:`while` loop, but not nested in a function or class definition within -that loop. It continues with the next cycle of the nearest enclosing loop. +that loop. It continues with the next cycle of the nearest enclosing loop. When :keyword:`continue` passes control out of a :keyword:`try` statement with a :keyword:`finally` clause, that :keyword:`!finally` clause is executed before @@ -833,16 +833,16 @@ where the :keyword:`import` statement occurs. The *public names* defined by a module are determined by checking the module's namespace for a variable named ``__all__``; if defined, it must be a sequence -of strings which are names defined or imported by that module. The names -given in ``__all__`` are all considered public and are required to exist. If +of strings which are names defined or imported by that module. The names +given in ``__all__`` are all considered public and are required to exist. If ``__all__`` is not defined, the set of public names includes all names found in the module's namespace which do not begin with an underscore character -(``'_'``). ``__all__`` should contain the entire public API. It is intended +(``'_'``). ``__all__`` should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module). The wild card form of import --- ``from module import *`` --- is only allowed at -the module level. Attempting to use it in class or function definitions will +the module level. Attempting to use it in class or function definitions will raise a :exc:`SyntaxError`. .. index:: @@ -881,7 +881,7 @@ module should be compiled using syntax or semantics that will be available in a specified future release of Python where the feature becomes standard. The future statement is intended to ease migration to future versions of Python -that introduce incompatible changes to the language. It allows use of the new +that introduce incompatible changes to the language. It allows use of the new features on a per-module basis before the release in which the feature becomes standard. @@ -892,7 +892,7 @@ standard. : ("," `feature` ["as" `identifier`])* [","] ")" feature: `identifier` -A future statement must appear near the top of the module. The only lines that +A future statement must appear near the top of the module. The only lines that can appear before a future statement are: * the module docstring (if any), @@ -904,17 +904,17 @@ The only feature that requires using the future statement is ``annotations`` (see :pep:`563`). All historical features enabled by the future statement are still recognized -by Python 3. The list includes ``absolute_import``, ``division``, +by Python 3. The list includes ``absolute_import``, ``division``, ``generators``, ``generator_stop``, ``unicode_literals``, -``print_function``, ``nested_scopes`` and ``with_statement``. They are +``print_function``, ``nested_scopes`` and ``with_statement``. They are all redundant because they are always enabled, and only kept for backwards compatibility. A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating -different code. It may even be the case that a new feature introduces new +different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler -may need to parse the module differently. Such decisions cannot be pushed off +may need to parse the module differently. Such decisions cannot be pushed off until runtime. For any given release, the compiler knows which feature names have been defined, @@ -937,12 +937,12 @@ special semantics or syntax restrictions. Code compiled by calls to the built-in functions :func:`exec` and :func:`compile` that occur in a module :mod:`!M` containing a future statement will, by default, -use the new syntax or semantics associated with the future statement. This can +use the new syntax or semantics associated with the future statement. This can be controlled by optional arguments to :func:`compile` --- see the documentation of that function for details. A future statement typed at an interactive interpreter prompt will take effect -for the rest of the interpreter session. If an interpreter is started with the +for the rest of the interpreter session. If an interpreter is started with the :option:`-i` option, is passed a script name to execute, and the script includes a future statement, it will be in effect in the interactive session started after the script is executed. @@ -980,13 +980,13 @@ assigned to prior to its global declaration in the scope. pair: built-in function; eval pair: built-in function; compile -**Programmer's note:** :keyword:`global` is a directive to the parser. It +**Programmer's note:** :keyword:`global` is a directive to the parser. It applies only to code parsed at the same time as the :keyword:`!global` statement. In particular, a :keyword:`!global` statement contained in a string or code object supplied to the built-in :func:`exec` function does not affect the code block *containing* the function call, and code contained in such a string is unaffected by :keyword:`!global` statements in the code containing the function -call. The same applies to the :func:`eval` and :func:`compile` functions. +call. The same applies to the :func:`eval` and :func:`compile` functions. .. _nonlocal: @@ -1005,7 +1005,7 @@ the definitions of other functions, its nonlocal scopes are the local scopes of the enclosing functions. The :keyword:`nonlocal` statement causes the listed identifiers to refer to names previously bound in nonlocal scopes. It allows encapsulated code to rebind such nonlocal -identifiers. If a name is bound in more than one nonlocal scope, the +identifiers. If a name is bound in more than one nonlocal scope, the nearest binding is used. If a name is not bound in any nonlocal scope, or if there is no nonlocal scope, a :exc:`SyntaxError` is raised. @@ -1019,7 +1019,7 @@ assigned to prior to its nonlocal declaration in the scope. The specification for the :keyword:`nonlocal` statement. **Programmer's note:** :keyword:`nonlocal` is a directive to the parser -and applies only to code parsed along with it. See the note for the +and applies only to code parsed along with it. See the note for the :keyword:`global` statement. diff --git a/Doc/reference/toplevel_components.rst b/Doc/reference/toplevel_components.rst index bd64b1c08bd1ff..3069f194310ebc 100644 --- a/Doc/reference/toplevel_components.rst +++ b/Doc/reference/toplevel_components.rst @@ -9,7 +9,7 @@ Top-level components The Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, -from a module source file, etc. This chapter gives the syntax used in these +from a module source file, etc. This chapter gives the syntax used in these cases. @@ -26,11 +26,11 @@ Complete Python programs pair: module; builtins While a language specification need not prescribe how the language interpreter -is invoked, it is useful to have a notion of a complete Python program. A +is invoked, it is useful to have a notion of a complete Python program. A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for :mod:`sys` (various system services), :mod:`builtins` (built-in -functions, exceptions and ``None``) and :mod:`__main__`. The latter is used to +functions, exceptions and ``None``) and :mod:`__main__`. The latter is used to provide the local and global namespace for execution of the complete program. The syntax for a complete Python program is that for file input, described in @@ -42,7 +42,7 @@ the next section. The interpreter may also be invoked in interactive mode; in this case, it does not read and execute a complete program but reads and executes one statement -(possibly compound) at a time. The initial environment is identical to that of +(possibly compound) at a time. The initial environment is identical to that of a complete program; each statement is executed in the namespace of :mod:`__main__`. @@ -54,7 +54,7 @@ a complete program; each statement is executed in the namespace of A complete program can be passed to the interpreter in three forms: with the :option:`-c` *string* command line option, as a file -passed as the first command line argument, or as standard input. If the file +passed as the first command line argument, or as standard input. If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program. @@ -104,7 +104,7 @@ Expression input .. index:: single: input .. index:: pair: built-in function; eval -:func:`eval` is used for expression input. It ignores leading whitespace. The +:func:`eval` is used for expression input. It ignores leading whitespace. The string argument to :func:`eval` must have the following form: .. grammar-snippet::