Skip to content

Instantly share code, notes, and snippets.

@nooperpudd
Created October 6, 2013 12:24
Show Gist options
  • Save nooperpudd/6853427 to your computer and use it in GitHub Desktop.
Save nooperpudd/6853427 to your computer and use it in GitHub Desktop.
with context api examples
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class WithInContext(object):
"""docstring for WithInContext"""
def __init__(self,context):
print "WithInContext.__init__(%s)" % context
def do_something(self):
print "WithInContext.do_something"
def __del__(self):
print "WithInContext.__del__()"
class Context(object):
"""docstring for Context"""
def __init__(self):
print "__init__"
def __enter__(self):
print "enter"
return WithInContext(self)
def __exit__(self,exc_type,exc_val,exc_tb):
print "__exit__"
print exc_type
print exc_val
print exc_tb
return True
with Context():
print "debug"
with Context() as c:
c.do_something()
with Context():
raise RuntimeError('ERROR MESSAGE!!')
@nooperpudd
Copy link
Author

init
enter
WithInContext.init(<main.Context object at 0x1005e5910>)
WithInContext.del()
debug
exit
None
None
None
init
enter
WithInContext.init(<main.Context object at 0x1005e5910>)
WithInContext.do_something
exit
None
None
None
init
enter
WithInContext.init(<main.Context object at 0x1005e5910>)
WithInContext.del()
exit
<type 'exceptions.RuntimeError'>
ERROR MESSAGE!!
<traceback object at 0x1005e2a28>
WithInContext.del()
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment