Example of new with statement
@ 2008-10-09 23:20:16
Filed under: Code Python Tech
And the result ...
digg it
seed it
del.icio.us
ma.gnolia
Filed under: Code Python Tech
#!/usr/bin/env python
# Only needed in 2.5
from __future__ import with_statement
class Alsome(object):
"""
An alsome object to use with a with statement.
"""
def __enter__(self):
"""
Executed at the point of with'ing. We return outselves so that we can
use this object like "with Alsome() as a:"
"""
print "Entering ..."
return self
def __exit__(self, ttype, value, traceback):
"""
Executed at the end of the with statement which is either when all
code within the with statement has been executed successfully or
if an exception is raised.
ttype is the type of the traceback.
value is the value of the traceback (like a message).
traceback is the traceback itself.
"""
if traceback != None:
print "Rolling back due to %s: %s" % (ttype.__name__, value)
print "Exiting ..."
def __init__(self):
"""
Simple constructor.
"""
print "Created the object ..."
self.hello = None
if __name__ == '__main__':
# Work
with Alsome() as a:
a.hello = "Hi!"
print a.hello
# Raise an error
with Alsome() as a:
a.hello = "Ho!"
sda
print a.hello
And the result ...
[steve@tachikoman ~]$ python t.py
Created the object ...
Entering ...
Hi!
Exiting ...
Created the object ...
Entering ...
Rolling back due to NameError: name 'sda' is not defined
Exiting ...
Traceback (most recent call last):
File "t.py", line 51, in <module>
sda
NameError: name 'sda' is not defined
[steve@tachikoman ~]$
digg it
seed it
del.icio.us
ma.gnolia


