Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent to C#'s using statement [duplicate]

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 is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I suppose there should be checks for None in each of them too - or will the variable not even exist if the constructor fails?)

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()
like image 748
Mark Heath Avatar asked Oct 28 '10 12:10

Mark Heath


2 Answers

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?

like image 82
Ned Batchelder Avatar answered Nov 09 '22 01:11

Ned Batchelder


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

like image 42
Damian Schenkelman Avatar answered Nov 09 '22 01:11

Damian Schenkelman