python 上下文管理器

上下文管理器最常用的是確保正確關(guān)閉文件,

with open('/path/to/file', 'r') as f:
    f.read()

with 語句的基本語法,

with expression [as variable]:
    with-block

expression是一個上下文管理器,其實(shí)現(xiàn)了enterexit兩個函數(shù)。當(dāng)我們調(diào)用一個with語句時, 依次執(zhí)行一下步驟,
1.首先生成一個上下文管理器expression, 比如open('xx.txt').
2.執(zhí)行expression.enter()。如果指定了[as variable]說明符,將enter()的返回值賦給variable.
3.執(zhí)行with-block語句塊.
4.執(zhí)行expression.exit(),在exit()函數(shù)中可以進(jìn)行資源清理工作.
with語句不僅可以管理文件,還可以管理鎖、連接等等,如,

#管理鎖
import  threading
lock = threading.lock()
with lock:
    #執(zhí)行一些操作
    pass

#數(shù)據(jù)庫連接管理
def test_write():
    sql = """      #具體的sql語句
    """
    con = DBConnection()
    with con as cursor:   
        cursor.execute(sql)
        cursor.execute(sql)
        cursor.execute(sql)
自定義上下文管理器

上下文管理器就是實(shí)現(xiàn)了上下文協(xié)議的類 ,也就是要實(shí)現(xiàn) __enter__()__exit__()兩個方法。

__enter__():主要執(zhí)行一些環(huán)境準(zhǔn)備工作,同時返回一資源對象。如果上下文管理器open("test.txt")的enter()函數(shù)返回一個文件對象。
__exit__():完整形式為exit(type, value, traceback),這三個參數(shù)和調(diào)用sys.exec_info()函數(shù)返回值是一樣的,分別為異常類型、異常信息和堆棧。如果執(zhí)行體語句沒有引發(fā)異常,則這三個參數(shù)均被設(shè)為None。否則,它們將包含上下文的異常信息。_exit()方法返回True或False,分別指示被引發(fā)的異常有沒有被處理,如果返回False,引發(fā)的異常將會被傳遞出上下文。如果exit()函數(shù)內(nèi)部引發(fā)了異常,則會覆蓋掉執(zhí)行體的中引發(fā)的異常。處理異常時,不需要重新拋出異常,只需要返回False,with語句會檢測exit()返回False來處理異常。

class test_query:
    def __init__(self):
        pass

    def query(self):
        print('query')

    def __enter__(self):
        # 如果是數(shù)據(jù)庫連接就可以返回cursor對象
        # cursor = self.cursor
        # return cursor
        print('begin query,')
        return self #由于這里沒有資源對象就返回對象
        
    def __exit__(self,exc_type,exc_value,traceback):
        if traceback is None:
            print('End')
        else:
            print('Error')

        # 如果是數(shù)據(jù)庫連接提交操作
        # if traceback is None:
        #   self.commit()
        # else:
        #   self.rollback()
        
if __name__ == '__main__':
    with test_query() as q:
        q.query()

contextlib

編寫enterexit仍然很繁瑣,因此Python的標(biāo)準(zhǔn)庫contextlib提供了更簡單的寫法,
基本語法

   @contextmanager
        def some_generator(<arguments>):
            <setup>
            try:
                yield <value>
            finally:
                <cleanup>

生成器函數(shù)some_generator就和我們普通的函數(shù)一樣,它的原理如下:
some_generator函數(shù)在在yield之前的代碼等同于上下文管理器中的enter函數(shù).
yield的返回值等同于enter函數(shù)的返回值,即如果with語句聲明了as <variable>,則yield的值會賦給variable.
然后執(zhí)行<cleanup>代碼塊,等同于上下文管理器的exit函數(shù)。此時發(fā)生的任何異常都會再次通過yield函數(shù)返回。
例,
自動加括號

import contextlib

@contextlib.contextmanager
def tag(name):
    print('<{}>'.format(name))
    yield
    print('</{}>'.format(name))


if __name__ == '__main__':
    with tag('h1') as t:
        print('hello')
        print('context')

管理鎖

@contextmanager
def locked(lock):
    lock.acquire()
    try:
        yield
    finally:
        lock.release()

with locked(myLock):
    #代碼執(zhí)行到這里時,myLock已經(jīng)自動上鎖
    pass
    #執(zhí)行完后會,會自動釋放鎖

管理文件關(guān)閉

@contextmanager
def myopen(filename, mode="r"):
    f = open(filename,mode)
    try:
        yield f
    finally:
        f.close()

with myopen("test.txt") as f:
    for line in f:
        print(line)

管理數(shù)據(jù)庫回滾

@contextmanager
def transaction(db):
    db.begin()
    try:
        yield 
    except:
        db.rollback()
        raise
    else:
        db.commit()

with transaction(mydb):
    mydb.cursor.execute(sql)
    mydb.cursor.execute(sql)
    mydb.cursor.execute(sql)
    mydb.cursor.execute(sql)

這就很方便!
如果一個對象沒有實(shí)現(xiàn)上下文,我們就不能把它用于with語句。這個時候,可以用closing()來把該對象變?yōu)樯舷挛膶ο蟆K?strong>exit函數(shù)僅僅調(diào)用傳入?yún)?shù)的close函數(shù).
例如,用with語句使用urlopen():

import contextlib
from urllib.request import urlopen

if __name__ == '__main__':
    with contextlib.closing(urlopen('https://www.python.org')) as page:
        for line in page:
            print(line)

closing也是一個經(jīng)過@contextmanager裝飾的generator,這個generator編寫起來其實(shí)非常簡單:

@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()

嵌套使用

import contextlib
from urllib.request import urlopen

if __name__ == '__main__':
    with contextlib.closing(urlopen('https://www.python.org')) as page,\
            contextlib.closing(urlopen('https://www.python.org')) as p:
        for line in page:
            print(line)
                print(p)

在2.x中需要使用contextlib.nested()才能使用嵌套,3.x中可以直接使用。
更多函數(shù)可以參考官方文檔https://docs.python.org/3/library/contextlib.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容