python with用法

@python with用法

python中with可以明显改进代码友好度,比如:

  1. with open('a.txt') as f:  
  2.     print f.readlines()  


为了我们自己的类也可以使用with, 只要给这个类增加两个函数__enter__, __exit__即可:

  1. >>> class A:  
  2.     def __enter__(self):  
  3.         print 'in enter'  
  4.     def __exit__(self, e_t, e_v, t_b):  
  5.         print 'in exit'  
  6.   
  7. >>> with A() as a:  
  8.     print 'in with'  
  9.   
  10. in enter  
  11. in with  
  12. in exit  


另外python库中还有一个模块contextlib,使你不用构造含有__enter__, __exit__的类就可以使用with:

[python]
 1 #-*- coding:utf-8 -*-
 2 from __future__ import with_statement
 3 from contextlib import contextmanager
 4 
 5 @contextmanager
 6 def context():
 7     print 'entering the zone'
 8     try:
 9         yield
10     except Exception,e:
11         print 'with an error %s ..' % e
12         raise e
13     else:
14         print 'with no error'
15 
16 #实用
17 with context():
18     print '----------in context call-------'

结果:

entering the zone
----------in context call-------
with no error


使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大

[python]
 
      1. from contextlib import closing  
      2. import urllib  
      3.   
      4. with closing(urllib.urlopen('http://www.python.org')) as page:  
      5.     for line in page:  
      6.         print line 
*******************************************************************************
@with从Python 2.5就有,需要from __future__ import with_statement。
python 
2.6开始,成为默认关键字。
在What's new in python2.6/3.0中,明确提到:
The 'with' statement is a control-flow structure whose basic structure is:
with expression [as variable]: with-block
也就是说with是一个控制流语句,跟if/for/while/try之类的是一类的,with可以用来简化try finally代码,看起来可以比try finally更清晰。
这里新引入了一个"上下文管理协议"context management protocol,实现方法是为一个类定义__enter__和__exit__两个函数。
with expresion as variable的执行过程是,首先执行__enter__函数,它的返回值会赋给as后面的variable,想让它返回什么就返回什么,只要你知道怎么处理就可以了,如果不写as variable,返回值会被忽略。
然后,开始执行with-block中的语句,不论成功失败(比如发生异常、错误,设置sys.exit()),在with-block执行完成后,会执行__exit__函数。
这样的过程其实等价于:
try:
执行 __enter__的内容
执行 with_block.
finally:
执行 __exit__内容
只不过,现在把一部分代码封装成了__enter__函数,清理代码封装成__exit__函数。
我们可以自己实现一个例子:
import sys
class test:
def __enter__(self):
       print("enter")
       return 1
def __exit__(self,*args):
       print("exit")
       return True
with test() as t:
print("t is not the result of test(), it is __enter__ returned")
print("t is 1, yes, it is {0}".format(t))
raise NameError("Hi there")
sys.exit()
print("Never here")
注意:
1,t不是test()的值,test()返回的是"context manager object",是给with用的。t获得的是__enter__函数的返回值,这是with拿到test()的对象执行之后的结果。t的值是1.
2,__exit__函数的返回值用来指示with-block部分发生的异常是否要re-raise,如果返回False,则会re-raise with-block的异常,如果返回True,则就像什么都没发生。
符合这种特征的实现就是符合“上下文管理协议”了,就可以跟with联合使用了。
as关键字的另一个用法是except XXX as e,而不是以前的except XXX,e的方式了。
此外,还可以使用contextlib模块中的contextmanager,方法是:
@contextmanager
...
yield something
...
的方式,具体需要看看文档和手册了。
yield的用法还是很神奇的,一句两句搞不清楚,如果您已经弄懂,看看文档就明白了,如果不懂yield,根据自己的需要去弄懂或者干脆不理他也可以,反正用到的时候,您一定回去搞懂的:-
其实with很像一个wrapper或者盒子,把with-block部分的代码包装起来,加一个头,加一个尾,头是__enter__,尾是__exit__,无论如何,头尾都是始终要执行的。


有一篇详细的介绍在:http://effbot.org/zone/python-with-statement.htm

 

我简单翻译一下其中的要点:

如果有一个类包含  __enter__ 方法和 __exit__ 方法,像这样:
class  controlled_execution:
       def__enter__(self):
              set things up
              return thing
        def__exit__(self, type, value, traceback):
              tear things down
那么它就可以和with一起使用,像这样:

with controlled_execution() as thing:
some code
    当with语句被执行的时候,python对表达式进行求值,对求值的结果(叫做“内容守护者”)调用__enter__方法,并把__enter__
方法的返回值赋给as后面的变量。然后python会执行接下来的代码段,并且无论这段代码干了什么,都会执行“内容守护者”的__exit__
方法。

       作为额外的红利,__exit__方法还能够在有exception的时候看到exception,并且压制它或者对它做出必要的反应。要压制 exception,只需要返回一个true。比如,下面的__exit__方法吞掉了任何的TypeError,但是让所有其他的exceptions 通过:

def__exit__(self, type, value, traceback):
return isinstance(value, TypeError)

在Python2.5中,file object拥有__enter__和__exit__方法,前者仅仅是返回object自己,而后者则关闭这个文件:
>>> f = open("x.txt")
>>> f
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.__enter__()
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>> f.read(1)
'X'
>>> f.__exit__(None, None, None)
>>> f.read(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
这样要打开一个文件,处理它的内容,并且保证关闭它,你就可以简简单单地这样做:
with open("x.txt") as f:
data = f.read()
do something with data
原文地址:https://www.cnblogs.com/liunnis/p/4627739.html