• contextlib


    contextlib   

    with 语句   上下文

    任何对象,只要正确实现了上下文管理,就可以用于with语句。

    实现上下文管理是通过__enter__和__exit__这两个方法实现的。

    例如,下面的class实现了这两个方法:


    class Query(object):

    def __init__(self, name):
    self.name = name

    def __enter__(self):
    print('Begin')
    return self

    def __exit__(self, exc_type, exc_value, traceback):
    if exc_type:
    print('Error')
    else:
    print('End')

    def query(self):
    print('Query info about %s...' % self.name)

    就可以把自己写的资源对象用于with语句:

    with Query('Bob') as q:
    q.query()

    编写__enter__和__exit__仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下:


    from contextlib import contextmanager

    class Query(object):

    def __init__(self, name):
    self.name = name

    def query(self):
    print('Query info about %s...' % self.name)

    @contextmanager
    def create_query(name):
    print('Begin')
    q = Query(name)
    yield q
    print('End')

    @contextmanager这个decorator接受一个generator

    在某段代码执行前后自动执行特定代码,也可以用@contextmanager实现。例如:

    @contextmanager
    def tag(name):
    print("<%s>" % name)
    yield
    print("</%s>" % name)

    with tag("h1"):
    print("hello")
    print("world")

    上述代码执行结果为:

    <h1>
    hello
    world
    </h1>

    with语句首先执行yield之前的语句,因此打印出<h1>;
    yield调用会执行with语句内部的所有语句,因此打印出hello和world;
    最后执行yield之后的语句,打印出</h1>。

    可以用closing()来把该对象变为上下文对象。例如,用with语句使用urlopen():

    from contextlib import closing
    from urllib.request import urlopen

    with closing(urlopen('https://www.python.org')) as page:
    for line in page:
    print(line)

    closing也是一个经过@contextmanager装饰的generator

    它的作用就是把任意对象变为上下文对象,并支持with语句。

    朝闻道
  • 相关阅读:
    UVA 10480 Sabotage (最大流最小割)
    bzoj2002 [Hnoi2010]Bounce 弹飞绵羊 (分块)
    poj3580 SuperMemo (Splay+区间内向一个方向移动)
    bzoj1500: [NOI2005]维修数列 (Splay+变态题)
    hdu3436 Queue-jumpers(Splay)
    hdu4710 Balls Rearrangement(数学公式+取模)
    hdu1890 Robotic Sort (splay+区间翻转单点更新)
    zoj2112 Dynamic Rankings (主席树 || 树套树)
    poj3581 Sequence (后缀数组)
    notepa++ Emmet的安装方法
  • 原文地址:https://www.cnblogs.com/wander-clouds/p/8503729.html
Copyright © 2020-2023  润新知