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

单例:对象身份、初始化及并发范围

相同身份不等于初始化只执行一次,也不等于跨进程唯一。

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

Python 3.12.14 · 21 项实际检查 · 当前入口SHA256 d9abcd95eb3eaab59bf17e3b0215f806aebf28d1d046b12d5c302c94d872e63d

检查项实际结果预期结果
new-only identitytruetrue
init repeats despite same object"second""second"
all actual threads same identity11
initialization serialized once11
first arguments retained"mbsky""mbsky"
per-class registryfalsefalse
subclass actual typetruetrue
failed init propagated"ValueError""ValueError"
failed init retry22
module cache same objecttruetrue
decorator shares config"mbsky.com""mbsky.com"
decorator replaced class with function"TypeError""TypeError"
ttl before boundary77
ttl exact expirationnullnull
ttl valid zero00
delete cachetruetrue
delete missing idempotentfalsefalse
validated config listener[{"site": "蓝色天空网", "debug": true}][{"site": "蓝色天空网", "debug": true}]
listener receives copy"蓝色天空网""蓝色天空网"
invalid config no notify"ValueError""ValueError"
invalid reload no extra listener call11

本章源码与生成文件

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

查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def singleton(c,out):
    class Reinitialized:
        _instance=None
        def __new__(cls,name):
            if cls._instance is None: cls._instance=super().__new__(cls)
            return cls._instance
        def __init__(self,name): self.name=name
    a=Reinitialized("first");b=Reinitialized("second")
    c.eq("new-only identity",a is b,True);c.eq("init repeats despite same object",a.name,"second")
    class Config(metaclass=SingletonMeta):
        initializations=0
        def __init__(self,name): type(self).initializations+=1;self.name=name
    class Child(Config): pass
    gate=Barrier(8)
    def get(_): gate.wait(timeout=10);return Config("mbsky")
    with ThreadPoolExecutor(max_workers=8) as pool: results=list(pool.map(get,range(8)))
    c.eq("all actual threads same identity",len({id(x) for x in results}),1)
    c.eq("initialization serialized once",Config.initializations,1)
    c.eq("first arguments retained",Config("ignored").name,"mbsky")
    child=Child("child");c.eq("per-class registry",child is results[0],False)
    c.eq("subclass actual type",type(child) is Child,True)
    # Failed initialization must not publish a partial instance.
    class Retry(metaclass=SingletonMeta):
        attempts=0
        def __init__(self):
            type(self).attempts+=1
            if type(self).attempts==1: raise ValueError("controlled constructor failure")
    c.raises("failed init propagated",ValueError,Retry);Retry();c.eq("failed init retry",Retry.attempts,2)
    module_file=out/"owned_config_module.py";module_file.write_text("instance = object()\n",encoding="utf8")
    name="mbsky_owned_pattern_config_"+out.name
    spec=importlib.util.spec_from_file_location(name,module_file);module=importlib.util.module_from_spec(spec)
    sys.modules[name]=module
    try:
        spec.loader.exec_module(module)
        c.eq("module cache same object",importlib.import_module(name).instance is module.instance,True)
    finally: sys.modules.pop(name,None)

def extra_singleton(c,out):
    def singleton_decorator(cls):
        instance=[];lock=Lock()
        @wraps(cls)
        def get(*args,**kwargs):
            with lock:
                if not instance:instance.append(cls(*args,**kwargs))
                return instance[0]
        return get
    @singleton_decorator
    class CachedConfig:
        def __init__(self):self.values={}
    first=CachedConfig();first.values["site"]="mbsky.com";c.eq("decorator shares config",CachedConfig().values["site"],"mbsky.com");c.raises("decorator replaced class with function",TypeError,lambda:isinstance(first,CachedConfig))
    now=[0];cache=TtlCache(lambda:now[0]);cache.set("a",7,10);now[0]=9;c.eq("ttl before boundary",cache.get("a"),7);now[0]=10;c.eq("ttl exact expiration",cache.get("a"),None);cache.set("b",0,1);c.eq("ttl valid zero",cache.get("b"),0);c.eq("delete cache",cache.delete("b"),True);c.eq("delete missing idempotent",cache.delete("b"),False)
    cfg=ValidatedConfig();seen=[];cfg.listeners.append(seen.append);path=out/"listened-config.json";path.write_text('{"site":"蓝色天空网","debug":true}',encoding="utf8");cfg.load(path);c.eq("validated config listener",seen,[{"site":"蓝色天空网","debug":True}]);seen[0]["site"]="changed";c.eq("listener receives copy",cfg.values["site"],"蓝色天空网")
    path.write_text('{"site":"bad"}',encoding="utf8");c.raises("invalid config no notify",ValueError,lambda:cfg.load(path));c.eq("invalid reload no extra listener call",len(seen),1)

def run_case(out):
    c=Checks()
    singleton(c,out)
    extra_singleton(c,out)
    return {"chapter":'python-singleton',"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))

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