python context sample
Last active
August 4, 2017 02:20
-
-
Save allenyang79/82f8611fe1e7df5aa4dd932e393e0f66 to your computer and use it in GitHub Desktop.
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
import contextlib | |
import copy | |
class Context(object): | |
def __init__(self, init_state={}): | |
self._states = [init_state] | |
@property | |
def state(self): | |
return self._states[-1] | |
@contextlib.contextmanager | |
def push(self, new_state): | |
state = copy.copy(self.state) | |
state.update(new_state) | |
self._states.append(state) | |
yield self | |
self._states.pop() | |
c = Context({'a':'AA', 'c': ['ccc']}) | |
s1 = c.state | |
with c.push({'b': 'BB', 'a': 'AAA'}) as cc: | |
#assert id(cc.state['c'], s1['c']) | |
s2 = cc.state | |
print s1['c'], id(s1['c']) | |
print s2['c'], id(s2['c']) | |
assert id(s1['c']) == id(s2['c']) | |
print s2 | |
print cc.state |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment