What is the python “with” statement designed for?

后端 未结 10 1841
心在旅途
心在旅途 2020-11-21 07:52

I came across the Python with statement for the first time today. I\'ve been using Python lightly for several months and didn\'t even know of its existence! G

10条回答
  •  滥情空心
    2020-11-21 08:03

    The with statement works with so-called context managers:

    http://docs.python.org/release/2.5.2/lib/typecontextmanager.html

    The idea is to simplify exception handling by doing the necessary cleanup after leaving the 'with' block. Some of the python built-ins already work as context managers.

提交回复
热议问题