-
Notifications
You must be signed in to change notification settings - Fork 1
/
weakreflist.pyx
65 lines (45 loc) · 2.01 KB
/
weakreflist.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
cdef inline object _get_object(object x):
x = PyWeakref_GetObject(x)
Py_XINCREF(x)
return x
cdef inline object _get_ref(object x, object self):
return PyWeakref_NewRef(x, self._remove)
cdef class WeakList(list):
def __init__(self, items=None):
items = items or []
super(WeakList, self).__init__((_get_ref(x, self) for x in items))
def __contains__(self, item):
return super(WeakList, self).__contains__(_get_ref(item, self))
def __getitem__(self, item):
return _get_object(super(WeakList, self).__getitem__(item))
def __getslice__(self, i, j):
return [_get_object(x) for x in super(WeakList, self).__getslice__(i, j)] #slow?
def __iter__(self):
for x in super(WeakList, self).__iter__():
yield _get_object(x)
def __repr__(self):
return "WeakList({!r})".format(list(self))
def __reversed__(self, *args, **kwargs):
for x in super(WeakList, self).__reversed__(*args, **kwargs):
yield _get_object(x)
def __setitem__(self, i, item):
super(WeakList, self).__setitem__(i, _get_ref(item, self))
def __setslice__(self, i, j, items):
super(WeakList, self).__setslice__(i, j, (_get_ref(x, self) for x in items))
cpdef _remove(self, object item):
while super(WeakList, self).__contains__(item):
super(WeakList, self).remove(item)
def append(self, item):
super(WeakList, self).append(_get_ref(item, self))
def count(self, item):
return super(WeakList, self).count(_get_ref(item, self))
def extend(self, items):
super(WeakList, self).extend((_get_ref(x, self) for x in items))
def index(self, item):
return super(WeakList, self).index(_get_ref(item, self))
def insert(self, i, item):
super(WeakList, self).insert(i, _get_ref(item, self))
def pop(self, i=-1):
return _get_object(super(WeakList, self).pop(i))
def remove(self, item):
super(WeakList, self).remove(_get_ref(item, self))