

class ObjContextManager():
  def __init__(self,msg):
    self.msg=msg;

  def __enter__(self):
    print "enter ", self.msg
    return self.msg

  def __exit__(self, type, value, traceback):
    print "exit ", self.msg

with ObjContextManager("test"):
  print "1"
  print "2"
  print "3"

import contextlib

@contextlib.contextmanager
def funcContextManager(msg):
    print "enter ", msg
    yield msg
    print "exit ", msg

with funcContextManager("test2") as msg:
  print "1"
  print "2"
  print "3"
  print msg

@contextlib.contextmanager
def funcCatchExcept(val):
  print "ready to do something with", val;
  try:
    yield val;
  except(AttributeError):
    print "exception detected"
  finally:
    print "feni"

with funcCatchExcept(1) as val:
  val.val=val;

with open("file","w") as f:
  f.write("hello")

with open("file","r") as f:
  print f.read();

