Skip to content

Instantly share code, notes, and snippets.

@muddana
Created March 15, 2010 22:18
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 muddana/333402 to your computer and use it in GitHub Desktop.
Save muddana/333402 to your computer and use it in GitHub Desktop.
test with python global keyword
WORD_FEATURES = []
def overwrite_word_features():
WORD_FEATURES = [1, 3, 5 ]
overwrite_word_features()
print WORD_FEATURES # prints []
#This took me a while to guess what could have been happening and was confirmed upon googling. the correct way to do is
WORD_FEATURES = []
def overwrite_word_features():
global WORD_FEATURES #tell python that in the following code WORD_FEATURES is global
WORD_FEATURES = [1, 3, 5 ]
overwrite_word_features()
print WORD_FEATURES # prints [1, 3, 5 ]
#How about if we assign the variable first and then declare as global it gives syntax warning "SyntaxWarning: name 'WORD_FEATURES' is assigned to #before global declaration" but still the global variable is assigned.
WORD_FEATURES = []
def overwrite_word_features():
WORD_FEATURES = [10, 9, 8 ]
global WORD_FEATURES #tell python that in the following code WORD_FEATURES is global
WORD_FEATURES += [1, 3, 5]
overwrite_word_features()
print WORD_FEATURES # prints [10, 9, 8, 1, 3, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment