Skip to content

Instantly share code, notes, and snippets.

@SkamDart
Created June 17, 2018 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SkamDart/412714e71e167df90b7b37bbe8ea6d35 to your computer and use it in GitHub Desktop.
Save SkamDart/412714e71e167df90b7b37bbe8ea6d35 to your computer and use it in GitHub Desktop.
python nonlocal keyword
# Copyright 2018 Cameron Dart
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#!/usr/bin/env python3
def with_nonlocal():
msg = 'Outside?'
def inside():
msg = 'Inside?'
print(msg)
inside()
print(msg)
def without_nonlocal():
msg = 'Outside?'
def inside():
nonlocal msg
msg = 'Inside?'
print(msg)
inside()
print(msg)
def main():
print("Running example with nonlocal")
with_nonlocal()
print("Running example without nonlocal")
without_nonlocal()
if __name__ == '__main__':
main()
"""
Question: What is the output for the program?
In the first example without Python's nonlocal keyword, the program behaves as expected i.e. Python's normal lexical scoping is used!
However, in the second example, you see that we have used the keyword `nonlocal` to modify the variable `msg`.
Now you're asking yourself, "what does this keyword do?"
TL;DR the `nonlocal` keyword retains the outer scoping if it is changed in some inner scope.
whereas if it is changed in an innerscope, that change propagates to the outerscope in normal lexical scoping.
It might be more intuitive to think of lexical scoping as "function" scopes.
Answer:
Running example with nonlocal
Inside?
Outside?
Running example without nonlocal
Inside?
Inside?
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment