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()
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?
I think you are looking for the with statement. More info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With