In this post, we go through the default scope of variable, and the scopes of variables with the global and nonlocal statement in front of a variable.
Let's go through an example from Python documentation website below, and see the output of this piece of code.
Output:
- After local assignment: test spam
- After nonlocal assignment: nonlocal spam
- After global assignment: nonlocal spam
- In global scope: global spam
Explanation:
- The spam assigned inside do_local() is a local variable (default). As mentioned in the website: "The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local namespace.". Therefore, the spam in the green square scope is unchanged (i.e., as initialized - "test spam")
- The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. That is, the spam in the green square scope is updated to "nonlocal spam" after calling do_nonlocal().
- The global assignment changed the module-level binding in the global scope (blue square scope), so the spam called "After global assignment" is still the one in the green square scope - nonlocal spam.
- Finally, if we print("In global scope", spam) where we are printing spam in the global scope, the one in the blue square scope will be printed, which is "global spam".
No comments:
Post a Comment