Skip to content Skip to sidebar Skip to footer

Python Equivalent To C#'s Using Statement

Possible Duplicate: What is the equivalent of the C# “using” block in IronPython? I'm writing some IronPython using some disposable .NET objects, and wondering whether there

Solution 1:

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: What is the equivalent of the C# "using" block in IronPython?

Solution 2:

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

Solution 3:

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.

Solution 4:

Your code with some comments :

defSave(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 :

defSave(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()

Post a Comment for "Python Equivalent To C#'s Using Statement"