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

北慕城南 提交于 2020-01-01 10:03:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!