Python is equivalent to C # using operator

Possible duplicate:
What is the C # equivalent using a block in IronPython?

I am writing IronPython using some one-time .NET objects and wondering if there is a good “pythonic” way to do this. I currently have a bunch of final statements (and I believe that each of them should also have a None check) or does the variable not exist even if the constructor doesn't work?)

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:
            sw = StreamWriter(isfs)
            try:
                sw.Write(data)
            finally:
                sw.Dispose()
        finally:
            isfs.Dispose()
    finally:
        isf.Dispose()
+5
source share
4 answers

Python 2.6 with, , with. , IronPython, .

: # "using" IronPython?

+4

, . .

+1

, with. , .

0

:

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

StreamWrite a ( __ __ _exit __), :

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 __ output method __ has

sw.Dispose()
0
source

All Articles