Skip to content

Instantly share code, notes, and snippets.

@egdoc
Created February 8, 2019 11:16
Show Gist options
  • Select an option

  • Save egdoc/7e9070e6b06004df1f31270d21e78721 to your computer and use it in GitHub Desktop.

Select an option

Save egdoc/7e9070e6b06004df1f31270d21e78721 to your computer and use it in GitHub Desktop.
Dynamic vs static/lexical scoping: bash vs python
#!/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
#!/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