What does the Python nonlocal statement do (in Python 3.0 and later)?
What does the Python nonlocal statement do (in Python 3.0 and later)?
The Python nonlocal
statement, introduced in Python 3.0, is used to work with variables inside nested functions, where the variable should not belong to the inner function itself but rather to an enclosing scope that is not the global scope. This statement allows the modification of a variable outside of the immediate local scope but within the nearest enclosing scope that is not global.
nonlocal
StatementScope Modification: The nonlocal
statement is used when you need to modify a variable that exists in an outer, but not global, scope. It effectively tells Python to use the variable from the nearest enclosing scope (excluding the global scope) if it exists[1][3][4][5].
Usage Constraints: It cannot be used to declare global variables or to affect variables in the global scope. It only works within nested functions[1][4][5].
Error Handling: If the variable specified after nonlocal
is not found in the nearest enclosing scope, Python will raise a SyntaxError
. This ensures that the variable must already exist in the outer function before it can be declared nonlocal in the inner function[2][4][5].
Memory Efficiency: By using nonlocal
, the memory address of the variable is reused. This can lead to more memory-efficient code because it avoids creating a new local variable ...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào