How to know the scope of variables in Python?

 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:

  1. After local assignment: test spam
  2. After nonlocal assignment: nonlocal spam
  3. After global assignment: nonlocal spam
  4. In global scope: global spam

Explanation:
  1. 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")
  2. 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().
  3. 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.
  4. 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