蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHON本地 Python 环境python3-with-keyword.py
python3-with-keyword.py166 行
"""蓝色天空网 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 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

入口文件:projects/python-lab/python3-with-keyword.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python3-with-keyword.py,或下载右侧课程工程包。
  2. 确认本地已准备 本地 Python 环境。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习