The With Statement

The with statement is actually a quite general construct, allowing you to use so-called context managers. A context manager is an object that supports two methods: __enter__ and __exit__. Like:

class controlled_execution:
      def __enter__(self):
          set things up
          return thing
      def __exit__(self, type, value, traceback):
          tear thing down

with controlled_execution() as thing:
     some code

The __enter__ method takes no arguments. It is called when entering the with statement, and the return value is bound to the variable after the as keyword.
The __exit__ method takes three arguments: an exception type, an exception object, and an exception traceback. It is called when leaving the method (with any exception raised supplied through the parameters). If __exit__ returns false, any exceptions are suppressed.

Files may be used as context managers. Their __enter__ methods return the file objects themselves, while their __exit__ methods close the files.

with open("somefile.txt") as somefile: #somefile is a file-like object returned by open()
     do_something(somefile)
For more information about this powerful, yet rather advanced, feature, check out the description of context managers in the Python Reference Manual.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值