-
Notifications
You must be signed in to change notification settings - Fork 38
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement hooks with register functions/decorators
Addresses #953.
- Loading branch information
Showing
4 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
from collections import defaultdict | ||
|
||
|
||
class Context(object): | ||
context_stack = [None] | ||
|
||
def __init__(self, page): | ||
self.page = page | ||
|
||
def __enter__(self): | ||
self.context_stack.append(self.page) | ||
for hook in (on_step, on_start, on_pause, on_continue, on_close): | ||
# NOTE entering context clears hooks, this might be surprising and | ||
# there might be a better solution to prevent accumulation of hooks | ||
# from multiple code executions. | ||
if self.page in hook.callbacks: | ||
del hook.callbacks[self.page] | ||
return self | ||
|
||
def __exit__(self, exc_type, exc_value, tb): | ||
assert self.context_stack.pop() is self.page | ||
|
||
|
||
class Hook(object): | ||
def __init__(self): | ||
self.callbacks = defaultdict(list) # FIXME page references should be weak | ||
|
||
def __call__(self, fn): | ||
self.callbacks[Context.context_stack[-1]].append(fn) | ||
|
||
def execute(self, page): | ||
for cb in self.callbacks[page] + self.callbacks[None]: | ||
cb(page.sim) | ||
|
||
|
||
on_step = Hook() | ||
on_start = Hook() | ||
on_pause = Hook() | ||
on_continue = Hook() | ||
on_close = Hook() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters