gh-56374: Clarify documentation of nonlocal (#116942)

Define 'nonlocal scopes' in a way that excludes class scopes.
Rearrange the rest of the doc.  Add "Programmer's note".
This commit is contained in:
Terry Jan Reedy 2024-03-19 13:55:21 -04:00 • committed by GitHub
parent b85572c47d
commit 025ef7a5f7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1006,25 +1006,29 @@ The :keyword:`!nonlocal` statement
.. productionlist:: python-grammar .. productionlist:: python-grammar
nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)* nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)*
The :keyword:`nonlocal` statement causes the listed identifiers to refer to When the definition of a function or class is nested (enclosed) within
previously bound variables in the nearest enclosing scope excluding globals. the definitions of other functions, its nonlocal scopes are the local
This is important because the default behavior for binding is to search the scopes of the enclosing functions. The :keyword:`nonlocal` statement
local namespace first. The statement allows encapsulated code to rebind causes the listed identifiers to refer to names previously bound in
variables outside of the local scope besides the global (module) scope. nonlocal scopes. It allows encapsulated code to rebind such nonlocal
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.
Names listed in a :keyword:`nonlocal` statement, unlike those listed in a The nonlocal statement applies to the entire scope of a function or
:keyword:`global` statement, must refer to pre-existing bindings in an class body. A :exc:`SyntaxError` is raised if a variable is used or
enclosing scope (the scope in which a new binding should be created cannot assigned to prior to its nonlocal declaration in the scope.
be determined unambiguously).
Names listed in a :keyword:`nonlocal` statement must not collide with
pre-existing bindings in the local scope.
.. seealso:: .. seealso::
:pep:`3104` - Access to Names in Outer Scopes :pep:`3104` - Access to Names in Outer Scopes
The specification for the :keyword:`nonlocal` statement. 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
:keyword:`global` statement.
.. _type: .. _type:
The :keyword:`!type` statement The :keyword:`!type` statement