Python上下文管理器全實例詳解
Python上下文管理器
簡介
最近用到這個,仔細(xì)了解了一下,感覺是十分有用的,記錄一下
使用場景
當(dāng)我們需要獲取一個臨時打開的資源,并在使用完畢后進行資源釋放和異常處理,利用try-catch語句可以完成,舉個例子。
打開文件:
f = None try: print("try") f = open("__init__.py", "r") print(f.read()) except Exception as e: print("exception") finally: if f: print("finally") f.close()
利用上下文管理器:
class OpenHandle: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.f = open(self.filename, self.mode) return self.f def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: print("exception") else: print("normal") self.f.close() with OpenHandle("book.txt", "r") as f: print(f.read())
這樣可以利用with-as語句改寫代碼,讓程序員關(guān)注業(yè)務(wù)主流程,去掉對于資源的獲取和關(guān)閉這些重復(fù)操作。提升代碼的可讀性。好處很大。
執(zhí)行順序
執(zhí)行順序是理解這種寫法的關(guān)鍵:
- 初始化,執(zhí)行handle的__init__()
- __enter__()方法,獲取資源對象,返回給as后的變量
- 業(yè)務(wù)代碼邏輯
- __exit__方法,傳入3個參數(shù),異常類型,異常對象,調(diào)用棧對象,無異常都為None
- 拋出異?;蛘哒=Y(jié)束
函數(shù)式上下文管理器
利用from contextlib import contextmanager這個裝飾器可以將函數(shù)裝飾為上下文管理器,其實這個裝飾背后也是返回一個實現(xiàn)了__enter__和__exit__方法的類
from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): # Code to acquire resource, e.g.: resource = acquire_resource(*args, **kwds) try: yield resource finally: # Code to release resource, e.g.: release_resource(resource) >>> with managed_resource(timeout=3600) as resource: ... # Resource is released at the end of this block, ... # even if code in the block raises an exception
模板代碼
sqlalchemy會話上下文管理器
利用這個管理sqlalchemy會話對象的獲取和釋放,控制事務(wù)是再合適不過了
class DbTransaction: def __init__(self, session_maker): self.session_maker = session_maker def __enter__(self): self.session = self.session_maker() return self.session def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: self.session.rollback() else: self.session.commit() self.session.close() return False if exc_type else True
以上就是全部相關(guān)知識點,感謝大家的學(xué)習(xí)和對腳本之家的支持。
相關(guān)文章
Python本地搭建靜態(tài)Web服務(wù)器的實現(xiàn)
本文主要介紹了Python本地搭建靜態(tài)Web服務(wù)器的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02python中subprocess批量執(zhí)行l(wèi)inux命令
本篇文章給大家詳細(xì)講述了python中使用subprocess批量執(zhí)行l(wèi)inux命令的方法,有興趣的朋友參考學(xué)習(xí)下。2018-04-04