views:

99

answers:

4
+3  A: 

Python 2.6 introduced the with statement, which provides for automatic clean up of objects when they leave the with statement. I don't know if the IronPython libraries support it, but it would be a natural fit.

Dup question with authoritative answer: http://stackoverflow.com/questions/1757296/what-is-the-equivalent-of-the-c-using-block-in-ironpython

Ned Batchelder
thanks, that led me to this question: http://stackoverflow.com/questions/1757296/what-is-the-equivalent-of-the-c-using-block-in-ironpython, which somehow I didn't find in my previous searches
Mark Heath
A: 

If I understand correctly, it looks like the equivalent is the with statement. If your classes define context managers, they will be called automatically after the with block.

Daniel Roseman
A: 

Hi,

I think you are looking for the with statement. More info here.

Damian Schenkelman
+1  A: 

Your code with some comments :

def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:                
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)

        try: # These try is useless....
            sw = StreamWriter(isfs)
            try:
                sw.Write(data)
            finally:
                sw.Dispose()
        finally: # Because next finally statement (isfs.Dispose) will be always executed
            isfs.Dispose()
    finally:
        isf.Dispose()

For StreamWrite, you can use a with statment (if your object as __enter__ and _exit__ methods) then your code will looks like :

def Save(self):
    filename = "record.txt"
    data = "{0}:{1}".format(self.Level,self.Name)
    isf = IsolatedStorageFile.GetUserStoreForApplication()
    try:                
        isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf)
        with StreamWriter(isfs) as sw:
            sw.Write(data)
    finally:
        isf.Dispose()

and StreamWriter in his __exit__ method has

sw.Dispose()
ohe
You can also use with statement with IsolatedStorageFile class, if needed.
ohe