Skip to content

Instantly share code, notes, and snippets.

@ieure
Created October 2, 2009 20:29
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 ieure/200091 to your computer and use it in GitHub Desktop.
Save ieure/200091 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# foo()'s a_value is unmodified.
def foo():
a_value = "Hello"
def bar():
a_value = "Goodbye"
bar()
print a_value # -> "Hello"
foo() # -> "Hello"
# But can be read.
def foo():
a_value = "Hello"
def bar():
print a_value
bar()
print a_value # -> "Hello"
foo() # -> "Hello"
# If it's set in bar(), it becomes a different var, even before the
# assignment.
def foo():
a_value = "Hello"
def bar():
print a_value
a_value = "Goodbye"
bar()
print a_value
try:
foo()
except Exception, e:
print e # -> UnboundLocalError: local variable 'a_value' referenced
# before assignment
# Attributes of vars can be changed.
def foo():
some_values = {'a_value': "Hello"}
def bar():
print some_values
some_values['a_value'] = "Goodbye"
bar()
print some_values # -> {'a_value': 'Hello'}
foo() # -> {'a_value': 'Goodbye'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment