Created
November 26, 2017 15:23
-
-
Save pgroudas/5aab4c2fb59804a8df4ad8a592ec7803 to your computer and use it in GitHub Desktop.
Global reassignment Python example
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
def foo(x): | |
return x | |
def reassign(y): | |
# Must have this line to tell the interpreter that you mean the outer 'foo' reference, not a new, locally scoped one. | |
global foo | |
if y: | |
foo = lambda x: x + 1 | |
else: | |
foo = lambda x: x - 1 | |
if __name__ == "__main__": | |
print(foo(1)) | |
reassign(True) | |
print(foo(1)) | |
reassign(False) | |
print(foo(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment