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

装饰器:包装顺序、返回值和异常契约:独立运行与结果核对

PYTHONWindows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Pythonpython-decorator.py
python-decorator.py59 行
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def decorator(c,out):
    trace=[]
    @timed(trace)
    def add(x,y):
        """返回两数之和。"""
        return x+y
    c.eq("return retained",add(2,y=3),5);c.eq("metadata",add.__name__,"add");c.eq("wrapped original",add.__wrapped__(1,2),3)
    c.eq("elapsed nonnegative",trace[0][1]>=0,True)
    @timed(trace)
    def fail(): raise ValueError("planned")
    c.raises("exception propagates",ValueError,fail);c.eq("finally records failed call",trace[-1][0],"fail")
    sequence=[]
    def wrap(label):
        def dec(fn):
            @wraps(fn)
            def run():
                sequence.append(label+" before");value=fn();sequence.append(label+" after");return value
            return run
        return dec
    @wrap("outer")
    @wrap("inner")
    def core(): sequence.append("core");return 7
    c.eq("nested return",core(),7);c.eq("application vs call order",sequence,["outer before","inner before","core","inner after","outer after"])
    calls=[]
    @retry(3,(OSError,))
    def unstable():
        calls.append(1)
        if len(calls)<3: raise OSError("controlled transient")
        return "ready"
    c.eq("deterministic third attempt",unstable(),"ready");c.eq("attempt bound",len(calls),3)
    c.raises("zero attempts rejected",ValueError,lambda:retry(0,(OSError,)))
    badcalls=[]
    @retry(3,(OSError,))
    def invalid(): badcalls.append(1);raise ValueError("not transient")
    c.raises("non-retryable propagates",ValueError,invalid);c.eq("nonretryable called once",len(badcalls),1)
    @lru_cache(maxsize=32)
    def fib(n):
        if type(n) is not int or n<0: raise ValueError("nonnegative integer")
        return n if n<2 else fib(n-1)+fib(n-2)
    c.eq("recursive cache",fib(10),55);hits=fib.cache_info().hits;fib(10);c.eq("cache hit observed",fib.cache_info().hits,hits+1)
    c.raises("cache unhashable",TypeError,lambda:fib([]))

def extra_decorator_complete(c,out):extra_decorator(c,out);extra_monitor(c,out)

def run_case(out):
    c=Checks()
    decorator(c,out)
    extra_decorator_complete(c,out)
    return {"chapter":'python-decorator',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}

if __name__ == "__main__":
    output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
    print(json.dumps(run_case(output),ensure_ascii=False,default=repr))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python

入口文件:projects/patterns-lab/python-decorator.py

预期结果与验证条件观察提示
  • 当前固定输入命名检查符合明确实际结果及失败策略
  • 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:Python 设计模式

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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