Skip to content

Instantly share code, notes, and snippets.

@TheLonelyGhost
Last active June 12, 2019 00:17
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 TheLonelyGhost/9dbe810c42d8f2edcf3388a8b19519e1 to your computer and use it in GitHub Desktop.
Save TheLonelyGhost/9dbe810c42d8f2edcf3388a8b19519e1 to your computer and use it in GitHub Desktop.
Global state versus variable shadowing (python)

Example of Shadowing versus Global Shared State in Python

$ python ./main.py
PRE-CHANGE
First (direct): I am first
First (attribute): I am first
Second (direct): I am second
Second (attribute): I am second
CHANGE 1
First (direct): I am first
First (attribute): I am first
Second (direct): I am second
Second (attribute): I am second
CHANGE 2
First (direct): I am first
First (attribute): I am first
Second (direct): I am second
Second (attribute): changed
FOLLOW-UP HYPOTHESIS
First (direct): I am first
First (attribute): changed
Second (direct): I am second
Second (attribute): changed
first = 'I am first'
second = 'I am second'
from __future__ import print_function
import global_state
from global_state import first, second
from mutator import change_first, change_second, change_first_alt
print('PRE-CHANGE')
print('First (direct): {}'.format(first))
print('First (attribute): {}'.format(global_state.first))
print('Second (direct): {}'.format(second))
print('Second (attribute): {}'.format(global_state.second))
change_first()
print('CHANGE 1')
print('First (direct): {}'.format(first))
print('First (attribute): {}'.format(global_state.first))
print('Second (direct): {}'.format(second))
print('Second (attribute): {}'.format(global_state.second))
change_second()
print('CHANGE 2')
print('First (direct): {}'.format(first))
print('First (attribute): {}'.format(global_state.first))
print('Second (direct): {}'.format(second))
print('Second (attribute): {}'.format(global_state.second))
change_first_alt()
print('FOLLOW-UP HYPOTHESIS')
print('First (direct): {}'.format(first))
print('First (attribute): {}'.format(global_state.first))
print('Second (direct): {}'.format(second))
print('Second (attribute): {}'.format(global_state.second))
import global_state
from global_state import first
def change_first():
first = 'changed'
def change_second():
global_state.second = 'changed'
def change_first_alt():
global_state.first = 'changed'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment