" , " " , " (, , " , -" ), . Python , with.
from __future__ import with_statement
import sys
class Spam(object):
def __init__(self, name):
self.name = name
def __enter__(self):
sys.stdout.write("Entering Spam:%s\n" % self.name)
sys.stdout.flush()
def __exit__(self, type, value, traceback):
sys.stdout.write("Lets clean up Spam:%s\n" % self.name)
if type is None:
sys.stdout.write("Leaving Spam:%s in peace\n" % self.name)
return
else:
sys.stdout.write("Leaving Spam:%s with Exception:%r\n" % (self.name, value))
with Spam("first") as spam:
pass
with Spam("2nd") as spam:
raise Exception("Oh No!")
:
Entering Spam:first
Lets clean up Spam:first
Leaving Spam:first in peace
Entering Spam:2nd
Lets clean up Spam:2nd
Leaving Spam:2nd with Exception:Exception('Oh No!',)
Traceback (most recent call last):
File "asd.py", line 24, in <module>
raise Exception("Oh No!")
Exception: Oh No!