当前位置:Gxlcms > Python > Python中的with语句与上下文管理器

Python中的with语句与上下文管理器

时间:2021-07-01 10:21:17 帮助过:65人阅读

在Python中作为上下文管理器的对象可以使用with语句,提供上下文管理器的contextlib模块的使用则是Python编程中的高级技巧,下面我们就来详细整理一下Python中的with语句与上下文管理器学习总结:

0、关于上下文管理器
上下文管理器是可以在with语句中使用,拥有__enter__和__exit__方法的对象。

  1. with manager as var:
  2. do_something(var)

相当于以下情况的简化:

  1. var = manager.__enter__()
  2. try:
  3. do_something(var)
  4. finally:
  5. manager.__exit__()

换言之,PEP 343中定义的上下文管理器协议允许将无聊的try...except...finally结构抽象到一个单独的类中,仅仅留下关注的do_something部分。

__enter__方法首先被调用。它可以返回赋给var的值。as部分是可选的:如果它不出现,enter的返回值简单地被忽略。
with语句下的代码被执行。就像try子句,它们或者成功执行到底,或者break,continue或return,或者可以抛出异常。无论哪种情况,该块结束后,__exit__方法被调用。如果抛出异常,异常信息被传递给__exit__,这将在下一章节讨论。通常情况下,异常可被忽略,就像在finally子句中一样,并且将在__exit__结束后重新抛出。
比如说我们想确认一个文件在完成写操作之后被立即关闭:

  1. >>> class closing(object):
  2. ... def __init__(self, obj):
  3. ... self.obj = obj
  4. ... def __enter__(self):
  5. ... return self.obj
  6. ... def __exit__(self, *args):
  7. ... self.obj.close()
  8. >>> with closing(open('/tmp/file', 'w')) as f:
  9. ... f.write('the contents\n')

这里我们确保了当with块退出时调用了f.close()。因为关闭文件是非常常见的操作,该支持已经出现在file类之中。它有一个__exit__方法调用close,并且本身可作为上下文管理器。

  1. >>> with open('/tmp/file', 'a') as f:
  2. ... f.write('more contents\n')

try...finally常见的用法是释放资源。各种不同的情况实现相似:在__enter__阶段资源被获得,在__exit__阶段释放,如果抛出异常也被传递。正如文件操作,往往这是对象使用后的自然操作,内置支持使之很方便。每一个版本,Python都在更多的地方提供支持。

1、如何使用上下文管理器:

如何打开一个文件,并写入"hello world"

  1. filename="my.txt"
  2. mode="w"
  3. writer=open(filename,mode)
  4. writer.write("hello world")
  5. writer.close()

当发生异常时(如磁盘写满),就没有机会执行第5行。当然,我们可以采用try-finally语句块进行包装:

  1. writer=open(filename,mode)
  2. try:
  3. writer.write("hello world")
  4. finally:
  5. writer.close()

当我们进行复杂的操作时,try-finally语句就会变得丑陋,采用with语句重写:

  1. with open(filename,mode) as writer:
  2. writer.write("hello world")

as指代了从open()函数返回的内容,并把它赋给了新值。with完成了try-finally的任务。

2、自定义上下文管理器

with语句的作用类似于try-finally,提供一种上下文机制。要应用with语句的类,其内部必须提供两个内置函数__enter__和__exit__。前者在主体代码执行前执行,后者在主体代码执行后执行。as后面的变量,是在__enter__函数中返回的。

  1. class echo():
  2. def output(self):
  3. print "hello world"
  4. def __enter__(self):
  5. print "enter"
  6. return self #可以返回任何希望返回的东西
  7. def __exit__(self,exception_type,value,trackback):
  8. print "exit"
  9. if exception_type==ValueError:
  10. return True
  11. else:
  12. return Flase
  13. >>>with echo as e:
  14. e.output()


输出:

  1. enter
  2. hello world
  3. exit

完备的__exit__函数如下:

  1. def __exit__(self,exc_type,exc_value,exc_tb)

其中,exc_type:异常类型;exc_value:异常值;exc_tb:异常追踪信息

当__exit__返回True时,异常不传播

3、contextlib模块

contextlib模块的作用是提供更易用的上下文管理器,它是通过Generator实现的。contextlib中的contextmanager作为装饰器来提供一种针对函数级别的上下文管理机制,常用框架如下:

  1. from contextlib import contextmanager
  2. @contextmanager
  3. def make_context():
  4. print 'enter'
  5. try:
  6. yield "ok"
  7. except RuntimeError,err:
  8. print 'error',err
  9. finally:
  10. print 'exit'
  11. >>>with make_context() as value:
  12. print value


输出为:

  1. enter
  2. ok
  3. exit

其中,yield写入try-finally中是为了保证异常安全(能处理异常)as后的变量的值是由yield返回。yield前面的语句可看作代码块执行前操作,yield之后的操作可以看作在__exit__函数中的操作。

以线程锁为例:

  1. @contextlib.contextmanager
  2. def loudLock():
  3. print 'Locking'
  4. lock.acquire()
  5. yield
  6. print 'Releasing'
  7. lock.release()
  8. with loudLock():
  9. print 'Lock is locked: %s' % lock.locked()
  10. print 'Doing something that needs locking'
  11. #Output:
  12. #Locking
  13. #Lock is locked: True
  14. #Doing something that needs locking
  15. #Releasing

4、contextlib.nested:减少嵌套

对于:

  1. with open(filename,mode) as reader:
  2. with open(filename1,mode1) as writer:
  3. writer.write(reader.read())

可以通过contextlib.nested进行简化:

  1. with contextlib.nested(open(filename,mode),open(filename1,mode1)) as (reader,writer):
  2. writer.write(reader.read())

在python 2.7及以后,被一种新的语法取代:

  1. with open(filename,mode) as reader,open(filename1,mode1) as writer:
  2. writer.write(reader.read())

5、contextlib.closing()

file类直接支持上下文管理器API,但有些表示打开句柄的对象并不支持,如urllib.urlopen()返回的对象。还有些遗留类,使用close()方法而不支持上下文管理器API。为了确保关闭句柄,需要使用closing()为它创建一个上下文管理器(调用类的close方法)。

  1. import contextlib
  2. class myclass():
  3. def __init__(self):
  4. print '__init__'
  5. def close(self):
  6. print 'close()'
  7. with contextlib.closing(myclass()):
  8. print 'ok'


输出:

  1. __init__
  2. ok
  3. close()


更多Python中的with语句与上下文管理器相关文章请关注PHP中文网!

人气教程排行