Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active August 4, 2017 02:20
Show Gist options
  • Save allenyang79/82f8611fe1e7df5aa4dd932e393e0f66 to your computer and use it in GitHub Desktop.
Save allenyang79/82f8611fe1e7df5aa4dd932e393e0f66 to your computer and use it in GitHub Desktop.

python context sample

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