温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python如何使用ContextLib

发布时间:2022-03-22 10:54:24 来源:亿速云 阅读:303 作者:小新 栏目:开发技术

小编给大家分享一下python如何使用ContextLib,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

上下文管理库(ContextLib)

contextlib模块包含了与上下文管理器和with声明相关的工具。通常如果你想写一个上下文管理器,则你需要定义一个类包含enter方法以及exit方法,例如:

import timeclass demo:

  def __init__(self, label):    self.label = label  def __enter__(self):    self.start = time.time()  def __exit__(self, exc_ty, exc_val, exc_tb):    end = time.time()

    print('{}: {}'.format(self.label, end - self.start))

完整的例子在此:

import timeclass demo:

  def __init__(self, label):    self.label = label  def __enter__(self):    self.start = time.time()  def __exit__(self, exc_ty, exc_val, exc_tb):    end = time.time()

    print('{}: {}'.format(self.label, end - self.start))

with demo('counting'):

  n = 10000000

  while n > 0:

    n -= 1# counting: 1.36000013351

上下文管理器被with声明所激活,这个API涉及到两个方法。 enter方法,当执行流进入with代码块时,enter方法将执行。并且它将返回一个可供上下文使用的对象。
当执行流离开with代码块时,exit方法被调用,它将清理被使用的资源。

利用@contextmanager装饰器改写上面那个例子:

from contextlib import contextmanagerimport time@contextmanagerdef demo(label):

  start = time.time()  try:    yield

  finally:

    end = time.time()

    print('{}: {}'.format(label, end - start))with demo('counting'):

  n = 10000000

  while n > 0:

    n -= 1# counting: 1.32399988174

看上面这个例子,函数中yield之前的所有代码都类似于上下文管理器中enter方法的内容。而yield之后的所有代码都如exit方法的内容。如果执行过程中发生了异常,则会在yield语句触发。

以上是“python如何使用ContextLib”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI