单例:对象身份、初始化及并发范围
相同身份不等于初始化只执行一次,也不等于跨进程唯一。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| new-only identity | true | true |
| init repeats despite same object | "second" | "second" |
| all actual threads same identity | 1 | 1 |
| initialization serialized once | 1 | 1 |
| first arguments retained | "mbsky" | "mbsky" |
| per-class registry | false | false |
| subclass actual type | true | true |
| failed init propagated | "ValueError" | "ValueError" |
| failed init retry | 2 | 2 |
| module cache same object | true | true |
| decorator shares config | "mbsky.com" | "mbsky.com" |
| decorator replaced class with function | "TypeError" | "TypeError" |
| ttl before boundary | 7 | 7 |
| ttl exact expiration | null | null |
| ttl valid zero | 0 | 0 |
| delete cache | true | true |
| delete missing idempotent | false | false |
| validated config listener | [{"site": "蓝色天空网", "debug": true}] | [{"site": "蓝色天空网", "debug": true}] |
| listener receives copy | "蓝色天空网" | "蓝色天空网" |
| invalid config no notify | "ValueError" | "ValueError" |
| invalid reload no extra listener call | 1 | 1 |
本章源码与生成文件
查看当前核心代码
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))