3 def __init__(self
, mth
, sort
, args
):
8 def __repr__(self
): return str(self
.mth
)
16 def attach(self
, obs_meth
, sort
=10, rename
='', args
=None):
18 onm
= rename
or obs_meth
.__name
__
19 if onm
not in self
.observers
: self
.observers
[onm
] = []
20 self
.observers
[onm
] += [ObsInfo(obs_meth
, sort
, args
)]
21 sorted_obs
= sorted(self
.observers
[onm
], key
=lambda obs
: obs
.sort
)
22 self
.observers
[onm
] = sorted_obs
24 def detach(self
, obs_meth
, lambda_call
=None):
25 if isinstance(obs_meth
, str):
27 observers
= [obs
for obs
in self
.observers
[onm
]
28 if obs
.mth
== lambda_call
]
30 onm
= obs_meth
.__name
__
31 observers
= [obs
for obs
in self
.observers
[onm
]
32 if obs
.mth
== obs_meth
]
33 if not observers
: raise Exception
34 list(map(self
.observers
[onm
].remove
, observers
))
36 def notify(self
, meth
, *args
, **kwargs
):
37 if meth
not in self
.observers
: return # no obs for this notification
38 for obs
in self
.observers
[meth
][:]:
39 if obs
in self
.observers
[meth
]: # if an obs removes another one
41 act_args
= obs
.args
+ list(args
)
42 obs
.mth(*act_args
, **kwargs
)
45 import sys
; sys
.exit()
47 def observing(self
, obs_meth
):
48 if callable(obs_meth
): obs_meth
= obs_meth
.__name
__
49 return obs_meth
in self
.observers
and self
.observers
[obs_meth
]
51 def destroy(self
): self
.observers
= None