观察者:订阅寿命、通知快照与错误策略
让事件内容和派发策略明确,避免订阅变更和失败悄悄漏通知。
本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。
| 检查项 | 实际结果 | 预期结果 |
|---|---|---|
| snapshot publish errors | [] | [] |
| unsubscribe during event applies next dispatch | [["first", "one"], ["second", "one"]] | [["first", "one"], ["second", "one"]] |
| next event removed callback | ["first", "two"] | ["first", "two"] |
| removed subscription count | 1 | 1 |
| unsubscribe idempotent | false | false |
| one observer failure reported | [{"token": 1, "exception": "ValueError", "message": "controlled observer failure"}] | [{"token": 1, "exception": "ValueError", "message": "controlled observer failure"}] |
| other observer still called | ["news"] | ["news"] |
| reentrancy explicitly rejected | ["ValueError", "RuntimeError"] | ["ValueError", "RuntimeError"] |
| unchanged price no duplicate notification | 1 | 1 |
| actual immutable payload | "QuoteEvent(symbol='MBSKY', old=Decimal('100'), new=Decimal('110'))" | "QuoteEvent(symbol='MBSKY', old=Decimal('100'), new=Decimal('110'))" |
| actual percent | "Decimal('10.0')" | "Decimal('10')" |
| symbol filtering | [] | [] |
| history only changes | ["Decimal('100')", "Decimal('110')"] | ["Decimal('100')", "Decimal('110')"] |
| unknown symbol explicit | "KeyError" | "KeyError" |
| zero price rejected avoids zero denominator | "ValueError" | "ValueError" |
| NaN rejected | "ValueError" | "ValueError" |
| live bound observer | "event" | "event" |
| weak bound method releases owner | null | null |
| async independent observers | ["one", "two"] | ["one", "two"] |
| async failure isolated explicitly | [1, "ValueError", 2] | [1, "ValueError", 2] |
本章源码与生成文件
查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *
def observer(c,out):
subject=EventSubject();calls=[];tokens={}
def first(event):
calls.append(("first",event));subject.unsubscribe(tokens["second"])
tokens["first"]=subject.subscribe(first);tokens["second"]=subject.subscribe(lambda event:calls.append(("second",event)))
c.eq("snapshot publish errors",subject.publish("one"),[])
c.eq("unsubscribe during event applies next dispatch",calls,[("first","one"),("second","one")])
subject.publish("two");c.eq("next event removed callback",calls[-1],("first","two"));c.eq("removed subscription count",len(subject.observers),1)
c.eq("unsubscribe idempotent",subject.unsubscribe(tokens["second"]),False)
subject=EventSubject();calls=[]
def broken(event):raise ValueError("controlled observer failure")
subject.subscribe(broken);subject.subscribe(calls.append);errors=subject.publish("news")
c.eq("one observer failure reported",errors,[{"token":1,"exception":"ValueError","message":"controlled observer failure"}])
c.eq("other observer still called",calls,["news"])
subject.subscribe(lambda e:subject.publish("recursive"));errors=subject.publish("again");c.eq("reentrancy explicitly rejected",[e["exception"]for e in errors],["ValueError","RuntimeError"])
market=QuoteMarket();market.add("MBSKY",Decimal("100"));received=[];filtered=[]
market.events.subscribe(received.append);market.events.subscribe(lambda event:filtered.append(event)if event.symbol=="OTHER"else None)
market.update("MBSKY",Decimal("110"));market.update("MBSKY",Decimal("110"))
c.eq("unchanged price no duplicate notification",len(received),1)
c.eq("actual immutable payload",received[0],QuoteEvent("MBSKY",Decimal("100"),Decimal("110")))
c.eq("actual percent",received[0].percent,Decimal("10"));c.eq("symbol filtering",filtered,[])
c.eq("history only changes",market.history["MBSKY"],[Decimal("100"),Decimal("110")])
c.raises("unknown symbol explicit",KeyError,lambda:market.update("MISSING",Decimal("1")))
c.raises("zero price rejected avoids zero denominator",ValueError,lambda:market.update("MBSKY",Decimal("0")))
c.raises("NaN rejected",ValueError,lambda:market.update("MBSKY",Decimal("NaN")))
import weakref,gc,asyncio
class Listener:
def update(self,event):return event
owner=Listener();ref=weakref.WeakMethod(owner.update);c.eq("live bound observer",ref()("event"),"event");del owner;gc.collect();c.eq("weak bound method releases owner",ref(),None)
async def asynchronous():
trace=[]
async def one():await asyncio.sleep(0);trace.append("one");return 1
async def bad():await asyncio.sleep(0);raise ValueError("async controlled")
async def two():await asyncio.sleep(0);trace.append("two");return 2
results=await asyncio.gather(one(),bad(),two(),return_exceptions=True)
return trace,[type(v).__name__ if isinstance(v,Exception)else v for v in results]
trace,result=asyncio.run(asynchronous());c.eq("async independent observers",sorted(trace),["one","two"]);c.eq("async failure isolated explicitly",result,[1,"ValueError",2])
def run_case(out):
c=Checks()
observer(c,out)
return {"chapter":'python-observer',"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))