Skip to content

Commit a1eb1ab

Browse files
author
Ram Rachum
committed
-
1 parent 34885bc commit a1eb1ab

File tree

2 files changed

+35
-15
lines changed

2 files changed

+35
-15
lines changed

garlicsim/garlicsim/general_misc/sleek_refs.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@
66

77
__all__ = ['CuteSleekValueDictionary', 'SleekRef']
88

9+
class Ref(weakref.ref):
10+
pass
11+
912
class SleekRef(object):
1013
def __init__(self, thing, callback=None):
1114
self.callback = callback
1215
if callback and not callable(callback):
1316
raise Exception('%s is not a callable object.' % callback)
1417
try:
15-
self.ref = weakref.ref(thing, callback)
18+
self.ref = Ref(thing, callback)
1619
except TypeError:
1720
self.ref = None
1821
self.thing = thing
@@ -200,15 +203,14 @@ class KeyedSleekRef(SleekRef):
200203
201204
"""
202205

203-
__slots__ = "key",
204-
205206
def __new__(type, ob, callback, key):
206-
self = SleekRef.__new__(type, ob, callback)
207-
self.key = key
207+
self = SleekRef.__new__(type)
208208
return self
209209

210210
def __init__(self, ob, callback, key):
211211
super(KeyedSleekRef, self).__init__(ob, callback)
212+
if self.ref:
213+
self.ref.key = key
212214

213215

214216

garlicsim/tests/general_misc/sleek_refs.py

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ def s():
1919

2020

2121
def counter(_=None):
22-
if not hasattr(counter, 'count'):
23-
counter.count = 0
24-
result = counter.count
25-
counter.count += 1
26-
return result
22+
if not hasattr(counter, 'count'):
23+
counter.count = 0
24+
result = counter.count
25+
counter.count += 1
26+
return result
2727

2828

2929
def test_sleek_ref():
@@ -69,13 +69,31 @@ def test_cute_sleek_value_dictionary():
6969
unvolatile_things = [A.s, __builtins__, list, type, list.append, str.join,
7070
sum]
7171

72+
# Using len(csvd) as our key; Just to guarantee we're not running over an
73+
# existing key.
74+
7275
while volatile_things:
7376
volatile_thing = volatile_things.pop()
7477
csvd = CuteSleekValueDictionary(counter)
75-
# Using len(csvd) as our key; Just to guarantee we're not running over
76-
# an existing key.
77-
csvd[len(csvd)] = volatile_thing
78+
if _is_weakreffable(volatile_thing):
79+
csvd[len(csvd)] = volatile_thing
80+
count = counter()
81+
del volatile_thing
82+
gc.collect()
83+
assert counter() == count + 2
84+
else:
85+
csvd[len(csvd)] = volatile_thing
86+
count = counter()
87+
del volatile_thing
88+
gc.collect()
89+
assert counter() == count + 1
90+
91+
while unvolatile_things:
92+
unvolatile_thing = unvolatile_things.pop()
93+
csvd = CuteSleekValueDictionary(counter)
94+
95+
csvd[len(csvd)] = unvolatile_thing
7896
count = counter()
79-
del volatile_thing
97+
del unvolatile_thing
8098
gc.collect()
81-
assert counter() == count + 2
99+
assert counter() == count + 1

0 commit comments

Comments
 (0)