蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

with:进入、退出、事务与资源寿命

清理效果由具体上下文管理器决定,必须观察真实状态。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

为什么需要上下文管理

with expression as target建立进入/退出范围,减少手写try/finally的重复;它不会猜任意对象该做何种清理,应查具体协议并核对退出结果。

文件退出通常close,数据库管理器可能只处理事务,锁负责获取/释放。不能把共同语法概括为所有对象自动关闭,也不能把一种API行为套给其它API。

进入值、退出参数与失败

__enter__的返回值绑定给as目标,不一定是管理器自身。__exit__(exc_type,exc_value,traceback)在正常退出时接到三个None,有异常时接到异常信息;图中返回箭头对应这一绑定。

__enter__失败时不调用本管理器__exit__;成功进入后as赋值失败仍调用退出。多个管理器依次进入、逆序退出,第二个进入失败也要退出此前成功进入的第一个。

有异常时__exit__返回值的真假决定是否抑制,不限于字面True;False或None通常让异常传播。无异常时返回值不改变普通流程;退出处理也可抛错,须保留原异常链。

流程图的继续后续代码只适合正常返回或异常被抑制的路径。异常传播时with后的普通语句不会照常运行;进程强制终止也不能承诺清理必然完成。

真实文件与SQLite事务

同时管理输入/输出文件,采用明确UTF-8和独立临时目录,实际检查原文本、大写后字节、两个文件关闭与异常退出closed。路径和编码错误另行处理。

sqlite3.Connection上下文管理器通常提交或回滚已打开事务,不负责关闭连接。本站固定legacy事务模式,观察提交、回滚和退出后还能查询,再显式close后观察ProgrammingError。完整寿命用外层contextlib.closing,内层采用明确事务策略,不用连接自动关闭的注释代替观察。查询前还须确保目标表存在;缺表会OperationalError,不能把一个未建表示例的失败误认为连接已关闭。

锁与临时数值上下文

with lock获取后离开时释放,异常退出也检查释放。线程安全依赖所有相关访问使用同一把锁及正确协议,不是一次print加锁就证明全程序安全。本站让多线程真实竞争自有计数器。

decimal.localcontext块内精度可设42,退出恢复原设置,不是永久修改整个系统所有线程。源码核对块内精度、计算及退出后的精度。

自定义管理器与contextlib

计时管理器使用perf_counter记录经过时间,返回self便于读取起止;只证明结束不早于开始,不作为性能基准。异常时执行退出但不默认吞错。

contextmanager装饰的生成器须恰好yield一次;必要清理放try/finally。若只在yield后直接打印结束标记,块内异常可能使它执行不到;仅记录异常时应再抛出,不能意外吞掉。

使用边界

使用资源正式支持的协议,保持块范围明确。只有__exit__而无__enter__不是完整同步管理器;未返回值等于None,是否抑制须按需求决定,并非忘写False就一定错误。

协议、三个异常参数及五个总结条目分别整理。异步with、网络服务和其它数据库驱动各自有边界,本地文件、SQLite和锁的观察不能泛化为这些环境已通过验收。

五个总结条目的准确边界

条目准确含义条件/反例
自动资源管理执行具体管理器的退出动作非任意对象自动close;SQLite管事务
上下文协议同步__enter__/__exit__as接enter返回值;进入失败不调exit
异常安全成功进入后异常路径也执行退出处理exit可抑制/抛错,强制终止另论
常见应用文件、事务、锁、局部精度分别检查closed/事务/锁/精度
自定义实现类协议或contextmanager恰好yield一次,清理放finally

退出方法和异常参数

入口/参数取值作用与条件
__enter__任意返回值不一定self;失败不运行块
__exit__(exc_type,exc_value,traceback)真值或假值异常时真值抑制,不限字面True
exc_type异常类型或None正常为None
exc_value异常实例或None不以字符串代实例
traceback追踪或None供记录,避免无谓长期持有
contextmanager一个生成器函数yield一次,finally清理
closing(resource)有close方法的资源退出时明确close
sqlite3.Connection本章legacy事务模式退出提交/回滚,不关闭连接

本章自编源码与运行范围

Python · 阅读源码
"""蓝色天空网 mbsky.com:文件/事务/锁的独立真实状态观察。"""
from pathlib import Path
import sys,contextlib,tempfile,sqlite3,threading,decimal,time
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
class Managed:
    def __init__(self,log,name="one",suppress=False,enter_error=False):
        self.log=log;self.name=name;self.suppress=suppress;self.enter_error=enter_error
    def __enter__(self):
        self.log.append(("enter",self.name))
        if self.enter_error:raise ValueError("enter failed")
        return "bound:"+self.name
    def __exit__(self,kind,value,tb):
        self.log.append(("exit",self.name,kind.__name__ if kind else None,type(value).__name__ if value else None,tb is not None))
        return self.suppress
def main():
    c=Checks();log=[];manager=Managed(log)
    with manager as bound:c.eq("as receives enter value",bound,"bound:one")
    c.eq("normal exit triple None",log,[("enter","one"),("exit","one",None,None,False)])
    log=[]
    def propagate():
        with Managed(log):raise ValueError("body failed")
    c.raises("body exception propagates",ValueError,propagate)
    c.eq("exception exit arguments",log,[("enter","one"),("exit","one","ValueError","ValueError",True)])
    log=[]
    with Managed(log,suppress="truthy"):raise LookupError("suppressed")
    c.eq("truthy nonbool suppresses",log[-1][2],"LookupError")
    log=[]
    def fail_enter():
        with Managed(log,enter_error=True):log.append("body")
    c.raises("enter error propagates",ValueError,fail_enter)
    c.eq("failed enter has no exit",log,[("enter","one")])
    log=[]
    def fail_binding():
        with Managed(log) as (first,second):pass
    c.raises("as assignment fails",ValueError,fail_binding)
    c.eq("as assignment still exits",log[-1][0],"exit")
    log=[]
    with Managed(log,"A"),Managed(log,"B"):log.append("body")
    c.eq("multiple inverse exit order",[(x[0],x[1])for x in log if type(x)is tuple],[("enter","A"),("enter","B"),("exit","B"),("exit","A")])
    log=[]
    def second_enter_fail():
        with Managed(log,"A"),Managed(log,"B",enter_error=True):pass
    c.raises("second enter failure",ValueError,second_enter_fail)
    c.eq("first still exits",[(x[0],x[1])for x in log],[("enter","A"),("enter","B"),("exit","A")])
    class ExitOnly:
        def __exit__(self,*args):pass
    def incomplete():
        with ExitOnly():pass
    c.raises("exit only incomplete protocol",TypeError,incomplete)
    class NoReturn:
        def __enter__(self):return self
        def __exit__(self,*args):pass
    def none_propagates():
        with NoReturn():raise KeyError("owned")
    c.raises("implicit None exit propagates",KeyError,none_propagates)
    log=[]
    class Mask(Managed):
        def __exit__(self,*args):raise RuntimeError("exit failed")
    try:
        with Mask(log):raise ValueError("body")
    except RuntimeError as exc:c.eq("exit error preserves context",type(exc.__context__).__name__,"ValueError")
    else:raise AssertionError("exit error missing")
    base=Path(__file__).resolve().parent/"_runtime-work";base.mkdir(exist_ok=True)
    with tempfile.TemporaryDirectory(prefix="contexts-",dir=base) as folder:
        root=Path(folder);source=root/"input.txt";target=root/"output.txt";source.write_text("蓝色天空网 mbsky.com\n",encoding="utf8")
        with source.open("r",encoding="utf8") as infile,target.open("w",encoding="utf8",newline="\n") as outfile:
            text=infile.read();outfile.write(text.upper());c.eq("files open inside",infile.closed or outfile.closed,False)
        c.eq("both files actually closed",(infile.closed,outfile.closed),(True,True))
        c.eq("actual uppercase bytes",target.read_bytes(),"蓝色天空网 MBSKY.COM\n".encode())
        def failing_file():
            nonlocal handle
            with source.open(encoding="utf8") as handle:raise ValueError("body")
        handle=None;c.raises("file body error",ValueError,failing_file)
        c.eq("file closed after exception",handle.closed,True)
        dbpath=root/"learning.sqlite"
        db=sqlite3.connect(dbpath,isolation_level="DEFERRED",autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)
        try:
            c.raises("sqlite missing table explicit",sqlite3.OperationalError,lambda:db.execute("SELECT * FROM missing_lessons"))
            db.execute("CREATE TABLE lessons(name TEXT UNIQUE)")
            with db as returned:
                c.eq("sqlite enter returns same connection",returned is db,True)
                db.execute("INSERT INTO lessons VALUES(?)",("HTML",))
            c.eq("sqlite committed result",db.execute("SELECT name FROM lessons").fetchall(),[("HTML",)])
            c.eq("sqlite connection remains usable",db.execute("SELECT 7").fetchone(),(7,))
            def rollback_body():
                with db:
                    db.execute("INSERT INTO lessons VALUES(?)",("CSS",))
                    raise ValueError("rollback now")
            c.raises("sqlite body propagates",ValueError,rollback_body)
            c.eq("sqlite rollback actual rows",db.execute("SELECT name FROM lessons").fetchall(),[("HTML",)])
            with contextlib.closing(sqlite3.connect(dbpath)) as reopened:
                c.eq("commit persisted actual file",reopened.execute("SELECT name FROM lessons").fetchall(),[("HTML",)])
            c.raises("closing really closes",sqlite3.ProgrammingError,lambda:reopened.execute("SELECT 1"))
        finally:db.close()
        c.raises("explicit close rejects query",sqlite3.ProgrammingError,lambda:db.execute("SELECT 1"))
    c.eq("temporary resources cleaned",Path(folder).exists(),False)
    lock=threading.Lock()
    def lock_failure():
        with lock:raise ValueError("lock body")
    c.raises("lock body exception",ValueError,lock_failure)
    acquired=lock.acquire(blocking=False)
    try:c.eq("lock released after exception",acquired,True)
    finally:
        if acquired:lock.release()
    state={"counter":0,"inside":0,"max":0};barrier=threading.Barrier(4);errors=[]
    def worker():
        try:
            barrier.wait(timeout=3)
            for _ in range(100):
                with lock:
                    state["inside"]+=1;state["max"]=max(state["max"],state["inside"])
                    state["counter"]+=1;state["inside"]-=1
        except Exception as exc:errors.append(type(exc).__name__)
    threads=[threading.Thread(target=worker)for _ in range(4)]
    for thread in threads:thread.start()
    for thread in threads:thread.join(timeout=5)
    c.eq("all worker threads joined",any(t.is_alive()for t in threads),False)
    c.eq("thread errors",errors,[])
    c.eq("protected actual total",state["counter"],400);c.eq("protected maximum concurrency",state["max"],1)
    original=decimal.getcontext().prec
    with decimal.localcontext() as ctx:
        ctx.prec=42;c.eq("temporary precision42",decimal.getcontext().prec,42)
        result=decimal.Decimal(1)/decimal.Decimal(7)
        c.eq("42 digit decimal",str(result),"0.142857142857142857142857142857142857142857")
    c.eq("decimal precision restored",decimal.getcontext().prec,original)
    class Timer:
        def __enter__(self):self.start=time.perf_counter();return self
        def __exit__(self,*args):self.end=time.perf_counter();return False
    with Timer() as timing:total=sum(range(1000))
    c.eq("timer work real result",total,499500);c.eq("monotonic timer order",timing.end>=timing.start,True)
    log=[]
    @contextlib.contextmanager
    def tag(name):
        log.append("<"+name+">")
        try:yield name
        finally:log.append("</"+name+">")
    with tag("h1") as value:c.eq("contextmanager yield binding",value,"h1");log.append("蓝色天空网")
    c.eq("normal tag sequence",log,["<h1>","蓝色天空网","</h1>"])
    log=[]
    def tag_error():
        with tag("h1"):raise ValueError("body")
    c.raises("tag body error propagates",ValueError,tag_error)
    c.eq("finally closing tag on exception",log,["<h1>","</h1>"])
    log=[]
    @contextlib.contextmanager
    def unsafe_tag():
        log.append("open");yield;log.append("close")
    def unsafe_error():
        with unsafe_tag():raise ValueError("body")
    c.raises("yield without finally propagates",ValueError,unsafe_error)
    c.eq("post yield cleanup skipped without finally",log,["open"])
    @contextlib.contextmanager
    def twice():yield 1;yield 2
    def two_yields():
        with twice():pass
    c.raises("contextmanager must yield once",RuntimeError,two_yields)
    @contextlib.contextmanager
    def never():
        if False:yield
    def no_yield():
        with never():pass
    c.raises("contextmanager cannot yield zero",RuntimeError,no_yield)
    c.finish("python3-with-keyword",sqlite_version=sqlite3.sqlite_version,transaction_mode="LEGACY_TRANSACTION_CONTROL/DEFERRED",thread_total=state["counter"],decimal_context_restored=True,network_or_async_contexts_tested=False)
if __name__=="__main__":main()
运行本章核心实例

所需环境:本地 Python 环境

当前源码 SHA256:9e08f05563ad813424e11a30287f8d08299234e8d018cdb0a226f3998527286c

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据