Created
November 20, 2014 17:45
-
-
Save fabiosantoscode/fa8a6884e45ae65e829b to your computer and use it in GitHub Desktop.
Non-threadsafe Dynamic Scoping in python
This file contains 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
#encoding=utf-8 | |
def env(name): | |
return stacks_of_names[name][-1] | |
stacks_of_names = {} | |
# comment the below line? | |
__builtins__.env = env | |
class assign(object): | |
def __init__(self, name, value): | |
self.name = name | |
self.value = value | |
def __enter__(self): | |
stack = stacks_of_names.setdefault(self.name, []) | |
stack.append(self.value) | |
def __exit__(self, *args): | |
stacks_of_names[self.name].pop() | |
if __name__ == '__main__': | |
# do a demo | |
def outp(msg): | |
if env('lang') == 'pt_PT': | |
print('olá' if msg == 'hi' else 'adeus lel') | |
else: # default | |
print(msg) | |
def eng_section(): | |
with assign('lang', 'en'): | |
program() | |
def program(): | |
outp('hi') | |
outp('bye') | |
with assign('lang', 'pt_PT'): | |
program() | |
eng_section() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment