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

运行本章核心实例

PYTHON本地 Python 环境python-decorators.py
python-decorators.py208 行
"""蓝色天空网 mbsky.com — 装饰器时序、返回、描述器与隔离单例。"""
from pathlib import Path
import sys,functools,inspect,asyncio,time,threading
sys.path.insert(0,str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
def main():
    c=Checks();log=[]
    def logged(function):
        @functools.wraps(function)
        def wrapper(*args,**kwargs):
            log.append("before")
            try:return function(*args,**kwargs)
            finally:log.append("after")
        return wrapper
    @logged
    def greeting(name="蓝色天空网"):
        """本站欢迎。"""
        log.append("body");return "欢迎 "+name
    c.eq("function body not at decoration",log,[])
    c.eq("wrapper forwards return",greeting(name="学习者"),"欢迎 学习者")
    c.eq("before body finally sequence",log,["before","body","after"])
    c.eq("wraps name",greeting.__name__,"greeting");c.eq("wraps doc",greeting.__doc__,"本站欢迎。")
    c.eq("wrapped original retained",callable(greeting.__wrapped__),True)
    c.eq("signature follows wrapped",str(inspect.signature(greeting)),"(name='蓝色天空网')")
    c.eq("raw wrapper still variadic",list(inspect.signature(greeting,follow_wrapped=False).parameters),["args","kwargs"])
    c.raises("forwarding does not bypass signature",TypeError,lambda:greeting(unknown=3))
    log.clear()
    @logged
    def broken():raise ValueError("owned error")
    c.raises("wrapped exception propagated",ValueError,broken)
    c.eq("finally after failure",log,["before","after"])
    class Keep:
        def __call__(self,function):return function
    decorator=Keep()
    def plain():return 3
    c.eq("callable decorator not function",inspect.isfunction(decorator),False)
    c.eq("decorator may preserve object",decorator(plain)is plain,True)
    def replace_with_value(function):return 7
    @replace_with_value
    def replaced():return 1
    c.eq("decorator return need not callable",replaced,7)
    c.raises("noncallable replacement call fails",TypeError,lambda:replaced())
    def repeat(times):
        if type(times)is not int:raise TypeError("integer repeat required")
        if times<0:raise ValueError("nonnegative required")
        def decorate(function):
            @functools.wraps(function)
            def wrapper(*args,**kwargs):return [function(*args,**kwargs)for _ in range(times)]
            return wrapper
        return decorate
    calls=[]
    @repeat(3)
    def hello():calls.append("hello");return "蓝色天空网"
    c.eq("repeat3 actual results",hello(),["蓝色天空网"]*3)
    c.eq("repeat3 actual calls",calls,["hello"]*3)
    c.eq("repeat0 actual results",repeat(0)(lambda:1/0)(),[])
    c.raises("repeat negative rejected",ValueError,lambda:repeat(-1))
    c.raises("repeat bool rejected",TypeError,lambda:repeat(True))
    log.clear()
    def factory(label):
        log.append("evaluate:"+label)
        def decorate(function):
            log.append("apply:"+label)
            @functools.wraps(function)
            def wrapper():
                log.append("enter:"+label)
                try:return function()
                finally:log.append("exit:"+label)
            return wrapper
        return decorate
    @factory("outer")
    @factory("inner")
    def stacked():log.append("body");return 9
    c.eq("expression evaluation and application order",log,["evaluate:outer","evaluate:inner","apply:inner","apply:outer"])
    log.clear();c.eq("stacked return",stacked(),9)
    c.eq("stacked enter exit order",log,["enter:outer","enter:inner","body","exit:inner","exit:outer"])
    protected_calls=[]
    def permission(function):
        @functools.wraps(function)
        def wrapper(user):
            if user.get("role")!="editor":raise PermissionError("teaching role only")
            return function(user)
        return wrapper
    @permission
    def protected(user):protected_calls.append("called");return "lesson"
    c.raises("toy permission denied before body",PermissionError,lambda:protected({"role":"reader"}))
    c.eq("denied body absent",protected_calls,[])
    c.eq("toy permission allowed",protected({"role":"editor"}),"lesson")
    c.eq("allowed body once",protected_calls,["called"])
    computed=[]
    @functools.lru_cache(maxsize=2)
    def cached(value):computed.append(value);return value*value
    c.eq("cache miss result",cached(4),16);c.eq("cache hit result",cached(4),16)
    c.eq("cache only one underlying call",computed,[4])
    c.eq("cache statistics",(cached.cache_info().hits,cached.cache_info().misses),(1,1))
    c.raises("cache unhashable key",TypeError,lambda:cached([]))
    failures=[]
    @functools.lru_cache(maxsize=2)
    def fail(value):failures.append(value);raise ValueError("not a successful result")
    c.raises("cache failure first",ValueError,lambda:fail(1))
    c.raises("cache failure second",ValueError,lambda:fail(1))
    c.eq("errors not cached",failures,[1,1])
    timings=[]
    def timed(function):
        def wrapper():
            start=time.perf_counter()
            try:return function()
            finally:timings.append(time.perf_counter()-start)
        return wrapper
    c.eq("timed work result",timed(lambda:sum(range(100)))(),4950)
    c.eq("timer records actual elapsed",len(timings)==1 and timings[0]>=0,True)
    class Raw:
        def __init__(self,title):self.title=title
        def display(self):return "课程:"+self.title
        def __len__(self):return 3
    def proxy_class(cls):
        class Proxy:
            def __init__(self,*args,**kwargs):self._wrapped=cls(*args,**kwargs)
            def __getattr__(self,name):return getattr(self._wrapped,name)
            def display(self):return self._wrapped.display()
        return Proxy
    proxy=proxy_class(Raw)("CSS")
    c.eq("class proxy normal method",proxy.display(),"课程:CSS")
    c.eq("class proxy missing attribute",proxy.title,"CSS")
    c.eq("proxy changes isinstance",isinstance(proxy,Raw),False)
    c.raises("getattr does not proxy len",TypeError,lambda:len(proxy))
    proxy.title="HTML";c.eq("proxy assignment not forwarded",proxy._wrapped.title,"CSS")
    def add_category(cls):cls.category="learning";return cls
    c.eq("inplace class decorator preserves type",add_category(Raw)is Raw,True)
    c.eq("inplace class attribute",Raw.category,"learning")
    class Singleton:
        def __init__(self,cls):self.cls=cls;self.instance=None;self.lock=threading.Lock();self.__wrapped__=cls
        def __call__(self,*args,**kwargs):
            with self.lock:
                if self.instance is None:self.instance=self.cls(*args,**kwargs)
                return self.instance
    initialized=[]
    @Singleton
    class Config:
        def __init__(self,value):initialized.append(value);self.value=value
    one=Config("first");two=Config("later")
    c.eq("singleton same object",one is two,True);c.eq("singleton initializes once",initialized,["first"])
    c.eq("later arguments do not reconfigure",two.value,"first")
    c.eq("decorated class name callable object",isinstance(Config,type),False)
    c.eq("original type available",isinstance(one,Config.__wrapped__),True)
    created=[]
    @Singleton
    class Parallel:
        def __init__(self):time.sleep(0.01);created.append("initialized")
    barrier=threading.Barrier(4);objects=[];errors=[]
    def worker():
        try:barrier.wait(timeout=3);objects.append(Parallel())
        except Exception as exc:errors.append(type(exc).__name__)
    threads=[threading.Thread(target=worker)for _ in range(4)]
    for t in threads:t.start()
    for t in threads:t.join(timeout=5)
    c.eq("singleton threads finished",any(t.is_alive()for t in threads),False)
    c.eq("singleton thread errors",errors,[])
    c.eq("parallel single initialization",created,["initialized"])
    c.eq("parallel all same object",len(objects)==4 and all(x is objects[0]for x in objects),True)
    class Course:
        def __init__(self):self._name="CSS"
        @staticmethod
        def slug(value):return value.lower()
        @classmethod
        def kind(cls):return cls.__name__
        @property
        def name(self):return self._name
        @name.setter
        def name(self,value):
            if not value:raise ValueError("name required")
            self._name=value
    class Child(Course):pass
    item=Course()
    c.eq("static via class",Course.slug("HTML"),"html");c.eq("static via instance",item.slug("CSS"),"css")
    c.eq("classmethod binds subclass",Child.kind(),"Child")
    c.eq("property initial read",item.name,"CSS");item.name="HTML";c.eq("property setter",item.name,"HTML")
    c.raises("property setter validation",ValueError,lambda:setattr(item,"name",""))
    bare=object.__new__(Course);c.raises("property uninitialized backing field",AttributeError,lambda:bare.name)
    trace=[]
    def synchronous(function):
        @functools.wraps(function)
        def wrapper():
            trace.append("sync before");result=function();trace.append("sync after");return result
        return wrapper
    @synchronous
    async def job():trace.append("coroutine body");return 6
    coroutine=job()
    c.eq("sync logs before coroutine runs",trace,["sync before","sync after"])
    c.eq("sync wrapper not coroutine function",inspect.iscoroutinefunction(job),False)
    c.eq("coroutine still can await",asyncio.run(coroutine),6)
    c.eq("sync actual late coroutine trace",trace,["sync before","sync after","coroutine body"])
    trace.clear()
    def asynchronous(function):
        @functools.wraps(function)
        async def wrapper():
            trace.append("async before")
            try:return await function()
            finally:trace.append("async after")
        return wrapper
    @asynchronous
    async def async_job():trace.append("body");return 8
    c.eq("async wrapper recognized",inspect.iscoroutinefunction(async_job),True)
    c.eq("async decorated result",asyncio.run(async_job()),8)
    c.eq("awaited before body after order",trace,["async before","body","async after"])
    c.finish("python-decorators",singletons_are_owned_memory_only=True,permissions_are_teaching_model_not_website_auth=True,async_wrapper_actually_awaited=True)
if __name__=="__main__":main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地 Python 环境

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

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

下载课程关联工程包:Python

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

下载课程关联工程包:Python

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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