蓝色天空网 · mbsky.com 全部实例

装饰器:包装顺序、返回值和异常契约

区分GoF对象装饰与Python可调用对象的@转换语法。

本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。

Python 3.12.14 · 38 项实际检查 · 当前入口SHA256 6370242d435285bc2a8a979c0793c10d7482937c5a889b92fb15467b0a3dcdc2

检查项实际结果预期结果
return retained55
metadata"add""add"
wrapped original33
elapsed nonnegativetruetrue
exception propagates"ValueError""ValueError"
finally records failed call"fail""fail"
nested return77
application vs call order["outer before", "inner before", "core", "inner after", "outer after"]["outer before", "inner before", "core", "inner after", "outer after"]
deterministic third attempt"ready""ready"
attempt bound33
zero attempts rejected"ValueError""ValueError"
non-retryable propagates"ValueError""ValueError"
nonretryable called once11
recursive cache5555
cache hit observed99
cache unhashable"TypeError""TypeError"
class callable descriptor binds self66
class timer metadata"double""double"
timer recorded one call11
repeat returns last result33
repeat0rejected"ValueError""ValueError"
retry exhausted propagates"OSError""OSError"
exhaustion attempt count22
permission wrapper success"sky""sky"
permission wrapper denial"PermissionError""PermissionError"
real tracked allocationtruetrue
allocation computation332833500332833500
tracer lifetime respectedfalsefalse
static method55
class method receives class"Radius""Radius"
property validates construction too"ValueError""ValueError"
monitor decorator actual result332833500332833500
monitor preserves exception"ValueError""ValueError"
monitor reports success and failure["calculate", "fails"]["calculate", "fails"]
monitor metrics actualtruetrue
owned tracer stoppedfalsefalse
borrowed tracer not stoppedtruetrue
borrowed report flaggedfalsefalse

本章源码与生成文件

下载独立入口 共享实现 补充实例实现 本章结果JSON

查看当前核心代码
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))

上图是本站运行生成文件,不能当作来源原图已采集。