Is it good practice to depend on python's with…as statement

后端 未结 2 1958
悲&欢浪女
悲&欢浪女 2021-02-04 09:24

I\'m curious if it is considered safe or good practice to depend on python\'s with...as statement. For example when opening a file:

with open(\"myfile\",\"w\") a         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-04 09:55

    Yes, the with statement is better way. Since Python 2.5, the file object has been equipped with __enter__() and __exit__() methods. The __exit__() method closes the file object.

    Python guarantees that it will call the __exit__() method, but there is not guarantee that the __exit__() method will close the resource, especially with 3rd party code. You need to manually verify that.

提交回复
热议问题