Created
February 8, 2019 11:16
-
-
Save egdoc/7e9070e6b06004df1f31270d21e78721 to your computer and use it in GitHub Desktop.
Dynamic vs static/lexical scoping: bash vs python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Bash has "dynamic" scoping: | |
| # Variable lookups occur in the scope where a function is CALLED | |
| animal="dog" | |
| function get_animal() { | |
| echo "I have a ${animal}" | |
| } | |
| function mypet() { | |
| local animal="cat" | |
| get_animal # <-- The get_animal function is invoked here, therefore 'animal' will be "cat" | |
| } | |
| mypet | |
| # Output: | |
| # I have a cat |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python3 | |
| # Python, as most modern languages has static/lexical scoping: | |
| # Variable lookups occur in the scope where a function is DEFINED | |
| animal = "dog" | |
| def get_animal(): | |
| print(f"I have a {animal}") | |
| def mypet(): | |
| animal = "cat" | |
| get_animal() | |
| mypet() | |
| # Output: | |
| # I have a dog |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment