Created
March 12, 2013 21:27
-
-
Save psobot/5147219 to your computer and use it in GitHub Desktop.
Python Scoping Pitfalls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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