Skip to content

Instantly share code, notes, and snippets.

@psobot
Created March 12, 2013 21:27
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 psobot/5147219 to your computer and use it in GitHub Desktop.
Save psobot/5147219 to your computer and use it in GitHub Desktop.
Python Scoping Pitfalls
class MyClass(object):
def __init__(self):
self.foo = "I'm the correct variable!"
def do_something(self):
# Whoops, I forgot to write this as "self.foo".
print foo
if __name__ == "__main__":
foo = "Herp derp, I'm the wrong variable."
MyClass().do_something()
# This will print:
# Herp derp, I'm the wrong variable.
class MyClass(object):
def __init__(self):
self.foo = "I'm the correct variable!"
def do_something(self):
# Whoops, I forgot to write this as "self.foo".
print foo
def main():
foo = "Herp derp, I'm the wrong variable."
MyClass().do_something()
if __name__ == "__main__":
main()
# This will throw a NameError, as "foo" is not valid
# in the scope of do_something on line 7.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment