@@ -1006,25 +1006,29 @@ The :keyword:`!nonlocal` statement
1006
1006
.. productionlist :: python-grammar
1007
1007
nonlocal_stmt: "nonlocal" `identifier ` ("," `identifier `)*
1008
1008
1009
- The :keyword: `nonlocal ` statement causes the listed identifiers to refer to
1010
- previously bound variables in the nearest enclosing scope excluding globals.
1011
- This is important because the default behavior for binding is to search the
1012
- local namespace first. The statement allows encapsulated code to rebind
1013
- variables outside of the local scope besides the global (module) scope.
1014
-
1015
- Names listed in a :keyword: `nonlocal ` statement, unlike those listed in a
1016
- :keyword: `global ` statement, must refer to pre-existing bindings in an
1017
- enclosing scope (the scope in which a new binding should be created cannot
1018
- be determined unambiguously).
1019
-
1020
- Names listed in a :keyword: `nonlocal ` statement must not collide with
1021
- pre-existing bindings in the local scope.
1009
+ When the definition of a function or class is nested (enclosed) within
1010
+ the definitions of other functions, its nonlocal scopes are the local
1011
+ scopes of the enclosing functions. The :keyword: `nonlocal ` statement
1012
+ causes the listed identifiers to refer to names previously bound in
1013
+ nonlocal scopes. It allows encapsulated code to rebind such nonlocal
1014
+ identifiers. If a name is bound in more than one nonlocal scope, the
1015
+ nearest binding is used. If a name is not bound in any nonlocal scope,
1016
+ or if there is no nonlocal scope, a :exc: `SyntaxError ` is raised.
1017
+
1018
+ The nonlocal statement applies to the entire scope of a function or
1019
+ class body. A :exc: `SyntaxError ` is raised if a variable is used or
1020
+ assigned to prior to its nonlocal declaration in the scope.
1022
1021
1023
1022
.. seealso ::
1024
1023
1025
1024
:pep: `3104 ` - Access to Names in Outer Scopes
1026
1025
The specification for the :keyword: `nonlocal ` statement.
1027
1026
1027
+ **Programmer's note: ** :keyword: `nonlocal ` is a directive to the parser
1028
+ and applies only to code parsed along with it. See the note for the
1029
+ :keyword: `global ` statement.
1030
+
1031
+
1028
1032
.. _type :
1029
1033
1030
1034
The :keyword: `!type ` statement
0 commit comments