装饰器:包装顺序、返回值和异常契约
区分GoF对象装饰与Python可调用对象的@转换语法。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| return retained | 5 | 5 |
| metadata | "add" | "add" |
| wrapped original | 3 | 3 |
| elapsed nonnegative | true | true |
| exception propagates | "ValueError" | "ValueError" |
| finally records failed call | "fail" | "fail" |
| nested return | 7 | 7 |
| 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 bound | 3 | 3 |
| zero attempts rejected | "ValueError" | "ValueError" |
| non-retryable propagates | "ValueError" | "ValueError" |
| nonretryable called once | 1 | 1 |
| recursive cache | 55 | 55 |
| cache hit observed | 9 | 9 |
| cache unhashable | "TypeError" | "TypeError" |
| class callable descriptor binds self | 6 | 6 |
| class timer metadata | "double" | "double" |
| timer recorded one call | 1 | 1 |
| repeat returns last result | 3 | 3 |
| repeat0rejected | "ValueError" | "ValueError" |
| retry exhausted propagates | "OSError" | "OSError" |
| exhaustion attempt count | 2 | 2 |
| permission wrapper success | "sky" | "sky" |
| permission wrapper denial | "PermissionError" | "PermissionError" |
| real tracked allocation | true | true |
| allocation computation | 332833500 | 332833500 |
| tracer lifetime respected | false | false |
| static method | 5 | 5 |
| class method receives class | "Radius" | "Radius" |
| property validates construction too | "ValueError" | "ValueError" |
| monitor decorator actual result | 332833500 | 332833500 |
| monitor preserves exception | "ValueError" | "ValueError" |
| monitor reports success and failure | ["calculate", "fails"] | ["calculate", "fails"] |
| monitor metrics actual | true | true |
| owned tracer stopped | false | false |
| borrowed tracer not stopped | true | true |
| borrowed report flagged | false | false |
本章源码与生成文件
查看当前核心代码
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))