问题
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()
回答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?
回答2:
I think you are looking for the with statement. More info here.
回答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.
回答4:
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()
来源:https://stackoverflow.com/questions/4042995/python-equivalent-to-cs-using-statement