This repository has been archived by the owner on Feb 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import time | ||
import weakref | ||
from bisect import bisect | ||
|
||
class Escapable(object): | ||
def __init__(self, callback, *args): | ||
self.callback = callback | ||
self.args = map(weakref.ref, args) | ||
|
||
def cancel(self): | ||
args = [a() for a in self.args] | ||
self.callback(*args) | ||
|
||
def is_active(self): | ||
args = [a() for a in self.args] | ||
return not any(a is None for a in args) | ||
|
||
|
||
class Manager(object): | ||
def __init__(self): | ||
self.escape_stack = [] | ||
|
||
def push(self, obj, priority=None): | ||
if priority is None: | ||
priority = 0 | ||
|
||
item = (-priority, time.time(), obj) | ||
self.escape_stack.insert(bisect(self.escape_stack, item), item) | ||
return obj | ||
|
||
def process(self): | ||
while self.escape_stack: | ||
_, _, obj = self.escape_stack.pop() | ||
if obj.is_active(): | ||
obj.cancel() | ||
return False | ||
|
||
return True |