def testWeakRef(self): for obj in self.objects: wr = weakref.ref(obj) self.assertTrue(wr() is obj) self.assertTrue(wr in weakref.getweakrefs(obj)) wr = weakref.proxy(obj) self.assertTrue(wr in weakref.getweakrefs(obj))
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 test_support.gc_collect() self.assert_(weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 test_support.gc_collect() self.assert_(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 test_support.gc_collect() self.assert_(weakref.getweakrefs(o) == [], "list of refs not cleared") # assumes ints do not support weakrefs self.assert_(weakref.getweakrefs(1) == [], "list of refs does not match for int")
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 gc.collect() self.assert_( weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 gc.collect() gc.collect() gc.collect() self.assert_( weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 gc.collect() self.assert_(weakref.getweakrefs(o) == [], "list of refs not cleared") # assumes ints do not support weakrefs self.assert_( weakref.getweakrefs(1) == [], "list of refs does not match for int")
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 self.assert_(weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 self.assert_(weakref.getweakrefs(o) == [ref1], "list of refs does not match")
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 self.assert_( weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 self.assert_( weakref.getweakrefs(o) == [ref1], "list of refs does not match")
def del_Profile(self, profile, del_users=False, no_archive=False, batch=False): """ Delete a user profile (LMC.groups is an instance of GroupsController and is needed to delete the profile group). """ assert ltrace(TRACE_PROFILES, '> del_Profile(%s)' % (profile.name)) # we need to hold the users lock, in case we need to delete users. assert ltrace(TRACE_LOCKS, ' del_Profile locks: %s, %s, %s' % (self.lock, LMC.groups.lock, LMC.users.lock)) with nested(self.lock, LMC.groups.lock, LMC.users.lock): # delete the reference in the controller. del self[profile.gid] # flush the controler data to disk. self.serialize() if profile.group.is_system_restricted: logging.info(_(u'Kept restricted system group %s.') % profile.groupName) else: try: LMC.groups.del_Group(profile.group, del_users=del_users, no_archive=no_archive, batch=batch, # this one is needed to avoid looping... check_profiles=False) except exceptions.DoesntExistException: logging.info('Group %s does not already exist, skipped.' % profile.groupName) name = profile.name assert ltrace(TRACE_GC, ' profile ref count before del: %d %s' % ( sys.getrefcount(profile), gc.get_referrers(profile))) # delete the hopefully last reference to the object. This will # delete it from the reverse mapping caches too. import weakref print weakref.getweakrefs(profile) del profile # checkpoint, needed for multi-delete (users-groups-profile) operation, # to avoid collecting the deleted users at the end of the run, making # throw false-negative operation about non-existing groups. gc.collect() logging.notice(_(u'Deleted profile %s.') % stylize(ST_NAME, name)) assert ltrace(TRACE_LOCKS, ' del_Profile locks: %s, %s, %s' % (self.lock, LMC.groups.lock, LMC.users.lock))
def _disconnect(self, cat, slots, **options): #{{{ numdel = int(options.get('count', 1)) if numdel < 0: numdel = 0 if isinstance(slots, dict): slots = slots.iteritems() sigcat = self._categories order, sigslot = sigcat[cat] if not slots: for name, (funchandler, funclist) in sigslot.iteritems(): del funclist[:] else: for name, funclist in slots: slist = sigslot[name][1] slist_rem = slist.remove if not funclist: del slist[:] continue for f in funclist: count = 0 proxies = [pf for pf in getweakrefs(f) if isinstance(pf, CallableProxyType)] for flist in (proxies, repeat(f)): for p in flist: if numdel and count >= numdel: break try: slist_rem(p) except ValueError: if p == f: break else: count = count + 1 if cat in ('around', 'replace'): self.reload()
def test_subclass_refs_dont_replace_standard_refs(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) self.assertTrue(r1 is not r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) self.assertTrue(r2 is refs[0]) self.assertIn(r1, refs[1:]) self.assertIn(r3, refs[1:])
def simple_demo(): class obj(object): def __init__(self, a): self.a = a def __repr__(self): return "obj:{0}".format(self.a) o = obj(3) r = weakref.ref(o) if r(): print "weakref's referent is alive" print "weakref's reference's references/proxies is ", weakref.getweakrefs(o) del o if r(): print "weakref's referent is not alive" print "weakref's reference's references/proxies is ", weakref.getweakrefs(o)
def test_subclass_refs_dont_replace_standard_refs(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) self.assert_(r1 is not r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) self.assert_(r2 is refs[0]) self.assert_(r1 in refs[1:]) self.assert_(r3 in refs[1:])
def pop(cls, limiter): if not limiter.pop(): key = weakref.getweakrefs(limiter)[0].key logging.debug('%s.pop %r with empty limiter', cls, key, stack_info=True)
def pop(cls, key): limiter = cls._get_limiter(key) if limiter is None or not limiter.pop(): key = weakref.getweakrefs(limiter)[0].key logging.debug('%s.pop %r with empty limiter', cls, key, stack_info=True)
def test_subclass_refs_dont_replace_standard_refs(self): if test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"): return class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) self.assertTrue(r1 is not r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) self.assertTrue(r2 is refs[0]) self.assertIn(r1, refs[1:]) self.assertIn(r3, refs[1:])
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 self.assertEqual(weakref.getweakrefs(o), [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 self.assertEqual(weakref.getweakrefs(o), [ref1], "list of refs does not match") del ref1 self.assertEqual(weakref.getweakrefs(o), [], "list of refs not cleared") # assumes ints do not support weakrefs self.assertEqual(weakref.getweakrefs(1), [], "list of refs does not match for int")
def test_subclass_refs_dont_replace_standard_refs(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o) r2 = weakref.ref(o) self.assertTrue(r1 is not r2) self.assertEqual(weakref.getweakrefs(o), [r2, r1]) self.assertEqual(weakref.getweakrefcount(o), 2) r3 = MyRef(o) self.assertEqual(weakref.getweakrefcount(o), 3) refs = weakref.getweakrefs(o) self.assertEqual(len(refs), 3) assert set(refs) == set((r1, r2, r3)) if test_support.check_impl_detail(): self.assertTrue(r2 is refs[0]) self.assertIn(r1, refs[1:]) self.assertIn(r3, refs[1:])
def stop_matlab(screen_session, matlab_engine, matlab_session, matlab_process, keep_engine=False): # pragma: matlab r"""Stop a Matlab shared engine session running inside a detached screen session. Args: screen_session (str): Name of the screen session that the shared Matlab session was started in. matlab_engine (MatlabEngine): Matlab engine that should be stopped. matlab_session (str): Name of Matlab session that the Matlab engine is connected to. matlab_process (psutil.Process): Process running the Matlab shared engine. keep_engine (bool, optional): If True, the references to the engine will be removed so it is not deleted. Defaults to False. Raises: RuntimeError: If Matlab is not installed. """ if not _matlab_installed: # pragma: no matlab raise RuntimeError("Matlab is not installed.") if keep_engine and (matlab_engine is not None): if '_matlab' in matlab_engine.__dict__: matlab_engine.quit() return # Remove weakrefs to engine to prevent stopping engine more than once if matlab_engine is not None: # Remove weak references so engine not deleted on exit eng_ref = weakref.getweakrefs(matlab_engine) for x in eng_ref: if x in matlab.engine._engines: matlab.engine._engines.remove(x) # Either exit the engine or remove its reference if matlab_session in matlab.engine.find_matlab(): try: matlab_engine.eval('exit', nargout=0) except BaseException: pass else: # pragma: no cover matlab_engine.__dict__.pop('_matlab', None) # Stop the screen session containing the Matlab shared session if screen_session is not None: if matlab_session in matlab.engine.find_matlab(): os.system(('screen -X -S %s quit') % screen_session) T = TimeOut(5) while ((matlab_session in matlab.engine.find_matlab()) and not T.is_out): debug("Waiting for matlab engine to exit") sleep(1) if (matlab_session in matlab.engine.find_matlab()): # pragma: debug if matlab_process is not None: matlab_process.terminate() error("stop_matlab timed out at %f s. " % T.elapsed + "Killed Matlab sharedEngine process.")
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 self.assertEqual(weakref.getweakrefs(o), [ref2], 'list of refs does not match') o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 self.assertEqual(weakref.getweakrefs(o), [ref1], 'list of refs does not match') del ref1 self.assertEqual(weakref.getweakrefs(o), [], 'list of refs not cleared') self.assertEqual(weakref.getweakrefs(1), [], 'list of refs does not match for int')
def __eq__(self, other): # We want slots to compare equal if they reference the same function/method if isinstance(other, Slot): if self.method and not other.method or not self.method and other.method: return False elif self.method and other.method: return self.obj == other.obj and self.name == other.name else: return self.call == other.call # We also want slots to compare equal _to_ the function or method they reference else: if self.method: if hasattr(other, 'im_self'): return self.obj in weakref.getweakrefs(other.im_self) and self.name == other.__name__ else: # `other` is not a method return False else: return self.call in weakref.getweakrefs(other)
def test_subclass_refs_dont_conflate_callbacks(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o, id) r2 = MyRef(o, str) self.assertTrue(r1 is not r2) refs = list(weakref.getweakrefs(o)) self.assertIn(r1, refs) self.assertIn(r2, refs)
def test_subclass_refs_dont_conflate_callbacks(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o, id) r2 = MyRef(o, str) self.assert_(r1 is not r2) refs = weakref.getweakrefs(o) self.assert_(r1 in refs) self.assert_(r2 in refs)
def test_subclass_refs_dont_conflate_callbacks(self): class MyRef(weakref.ref): pass o = Object(42) r1 = MyRef(o, id) r2 = MyRef(o, str) self.assertTrue(r1 is not r2) refs = weakref.getweakrefs(o) self.assertIn(r1, refs) self.assertIn(r2, refs)
def show(s = ''): print(s) print('global dict', dict(d)) for ref in d.keyrefs(): k = ref() if k is None: continue count = weakref.getweakrefcount(k) print('weakref count', k, count, ref) print('weakref list', weakref.getweakrefs(k)) print('ref count', k, sys.getrefcount(k)) # == 4?????????? print('\n'*2)
def tearDown(self): handler = self.loghandler # All this is necessary to properly shut down the logging system and # avoid a regrtest complaint. Thanks to Vinay Sajip for the help. handler.close() logger.removeHandler(handler) for ref in weakref.getweakrefs(handler): logging._removeHandlerRef(ref) del self.loghandler logger.setLevel(self._old_level) super(LoggingCatcher, self).tearDown()
def test_getweakrefs(self): def runTest(): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 return o, ref2 o, ref2 = runTest() test_support.force_gc_collect() self.assertTrue( weakref.getweakrefs(o) == [ref2], "list of refs does not match") def runTest(): def runInnerTest(): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 return o, ref1 o, ref1 = runInnerTest() test_support.force_gc_collect() self.assertTrue( weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 return o o = runTest() test_support.force_gc_collect() self.assertTrue( weakref.getweakrefs(o) == [], "list of refs not cleared") # assumes ints do not support weakrefs self.assertTrue( weakref.getweakrefs(1) == [], "list of refs does not match for int")
def test_getweakrefs(self): def runTest(): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 return o, ref2 o, ref2 = runTest() test_support.force_gc_collect() self.assertTrue(weakref.getweakrefs(o) == [ref2], "list of refs does not match") def runTest(): def runInnerTest(): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 return o, ref1 o, ref1 = runInnerTest() test_support.force_gc_collect() self.assertTrue(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 return o o = runTest() test_support.force_gc_collect() self.assertTrue(weakref.getweakrefs(o) == [], "list of refs not cleared") # assumes ints do not support weakrefs self.assertTrue(weakref.getweakrefs(1) == [], "list of refs does not match for int")
def test_getweakrefs(self): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref1 extra_collect() self.assert_(weakref.getweakrefs(o) == [ref2], "list of refs does not match") o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 extra_collect() if test_support.is_jython: # XXX: Likely a Jython bug: the following inline declared # [ref1] list isn't garbage collected no matter how many # times we force gc.collect(), which prevents ref1 from # being garbage collected after it's del'd below. So we # explicitly delete our list ref1_list = [ref1] self.assert_(weakref.getweakrefs(o) == ref1_list, #self.assert_(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1_list else: self.assert_(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 extra_collect() self.assert_(weakref.getweakrefs(o) == [], "list of refs not cleared") # assumes ints do not support weakrefs self.assert_(weakref.getweakrefs(1) == [], "list of refs does not match for int")
def runTest(): def runInnerTest(): o = C() ref1 = weakref.ref(o, self.callback) ref2 = weakref.ref(o, self.callback) del ref2 return o, ref1 o, ref1 = runInnerTest() test_support.force_gc_collect() self.assertTrue(weakref.getweakrefs(o) == [ref1], "list of refs does not match") del ref1 return o
def IsSame(o1: Any, o2: Any) -> bool: """ This checks for the identity even if one of the parameters is a weak reference :param o1: first object to compare :param o2: second object to compare @raise RuntimeError if both of the passed parameters are weak references """ # get rid of weak refs (we only need special treatment for proxys) if IsWeakRef(o1): o1 = o1() if IsWeakRef(o2): o2 = o2() # simple case (no weak objects) if not IsWeakObj(o1) and not IsWeakObj(o2): return o1 is o2 # all weak proxys if IsWeakProxy(o1) and IsWeakProxy(o2): if not o1 == o2: # if they are not equal, we know they're not the same return False # but we cannot say anything if they are the same if they are equal raise ReferenceError( "Cannot check if object is same if both arguments passed are weak objects" ) # one is weak and the other is not if IsWeakObj(o1): weak = o1 original = o2 else: weak = o2 original = o1 weaks = weakref.getweakrefs(original) for w in weaks: if w is weak: # check the weak object identity return True return False
def IsSame(o1, o2): ''' This checks for the identity even if one of the parameters is a weak reference :param o1: first object to compare :param o2: second object to compare @raise RuntimeError if both of the passed parameters are weak references ''' # get rid of weak refs (we only need special treatment for proxys) if IsWeakRef(o1): o1 = o1() if IsWeakRef(o2): o2 = o2() # simple case (no weak objects) if not IsWeakObj(o1) and not IsWeakObj(o2): return o1 is o2 # all weak proxys if IsWeakProxy(o1) and IsWeakProxy(o2): if not o1 == o2: # if they are not equal, we know they're not the same return False # but we cannot say anything if they are the same if they are equal raise ReferenceError('Cannot check if object is same if both arguments passed are weak objects') # one is weak and the other is not if IsWeakObj(o1): weak = o1 original = o2 else: weak = o2 original = o1 weaks = weakref.getweakrefs(original) for w in weaks: if w is weak: # check the weak object identity return True return False
def main3(): a = OBJ() b = weakref.proxy(a) print(a, b, type(a), type(b)) print(sys.getrefcount(a)) print(sys.getrefcount(b)) print(weakref.getweakrefs(a), weakref.getweakrefcount(a)) print(b is a) # False del a # print(b) # ReferenceError: weakly-referenced object no longer exists a = OBJ() c = weakref.ref(a) _c = c() print(c) print(_c is a) del a, _c print(c)
def stop_matlab(screen_session, matlab_engine, matlab_session): # pragma: matlab r"""Stop a Matlab shared engine session running inside a detached screen session. Args: screen_session (str): Name of the screen session that the shared Matlab session was started in. matlab_engine (MatlabEngine): Matlab engine that should be stopped. matlab_session (str): Name of Matlab session that the Matlab engine is connected to. Raises: RuntimeError: If Matlab is not installed. """ if not _matlab_installed: # pragma: no matlab raise RuntimeError("Matlab is not installed.") # Remove weakrefs to engine to prevent stopping engine more than once if matlab_engine is not None: # Remove weak references so engine not deleted on exit eng_ref = weakref.getweakrefs(matlab_engine) for x in eng_ref: if x in matlab.engine._engines: matlab.engine._engines.remove(x) # Either exit the engine or remove its reference if matlab_session in matlab.engine.find_matlab(): matlab_engine.exit() else: # pragma: no cover matlab_engine.__dict__.pop('_matlab') # Stop the screen session containing the Matlab shared session if screen_session is not None: if matlab_session in matlab.engine.find_matlab(): os.system(('screen -X -S %s quit') % screen_session) T = TimeOut(5) while ((matlab_session in matlab.engine.find_matlab()) and not T.is_out): debug("Waiting for matlab engine to exit") sleep(1) if (matlab_session in matlab.engine.find_matlab()): # pragma: debug raise Exception("stp[_matlab timed out at %f s" % T.elapsed)
def disconnect(self, receiver: callable, event: int): """ AUTHORS: -------- :author: Alix Leroy DESCRIPTION: ------------ Disconnect a receiver from a particular event PARAMETERS: ----------- :param receiver(callable): The method to call on the event is fired :param event(int): The type of event RETURN: ------- :return: """ disconnected = False # For all the connections at the specific event for i, connection in enumerate(self.connections[event]): weak_ref_receiver = connection.get_receiver() # If the weak connection if found, we remove the connection if weak_ref_receiver in weakref.getweakrefs(receiver): self.connections[event][i].pop() disconnected = True break if disconnected is False: Notification( DEEP_NOTIF_ERROR, "The following receiver %s could not be disconnected from %i." % (str(receiver), event))
def test_lock_session_used_by(self): session = mock.Mock() self.connection.lock(session) self.assertIn(self.connection.used_by, weakref.getweakrefs(session))
def _swap_refs(old, new, ignores): """Swap references from one object to another""" __internal_swaprefs_ignore__ = "swap_refs" # Swap weak references refs = weakref.getweakrefs(old) if refs: try: newRef = weakref.ref(new) except ValueError: pass else: for oldRef in refs: _swap_refs(oldRef, newRef, ignores + (id(refs),)) del refs deque, defaultdict = _bonus_containers() # Swap through garbage collector referrers = gc.get_referrers(old) for container in referrers: if id(container) in ignores: continue containerType = type(container) if containerType is list or containerType is deque: for index in _find_sequence_indices(container, old): container[index] = new elif containerType is tuple: # protect from recursive tuples orig = container if id(orig) in _recursive_tuple_swap: continue _recursive_tuple_swap.add(id(orig)) try: container = list(container) for index in _find_sequence_indices(container, old): container[index] = new container = tuple(container) _swap_refs(orig, container, ignores + (id(referrers),)) finally: _recursive_tuple_swap.remove(id(orig)) elif containerType is dict or containerType is defaultdict: if "__internal_swaprefs_ignore__" not in container: try: if old in container: container[new] = container.pop(old) except TypeError: # Unhashable old value pass for k,v in container.iteritems(): if v is old: container[k] = new elif containerType is set: container.remove(old) container.add(new) elif containerType is type: if old in container.__bases__: bases = list(container.__bases__) bases[bases.index(old)] = new container.__bases__ = tuple(bases) elif type(container) is old: container.__class__ = new elif containerType is _InstanceType: if container.__class__ is old: container.__class__ = new
def __dealloc(self, o): for r in weakref.getweakrefs(o): self._item_refs.pop(r, None)
child.parent = self def callback(ref): print('__del__', ref) n1 = Node(0) n2 = Node(2) print(n1, n2) # <__main__.Node object at 0x7fb0c2750c10> <__main__.Node object at 0x7fb0c2750d10> n1.add_child(n2) print(weakref.getweakrefcount(n1)) print(weakref.getweakrefcount(n2)) print(weakref.getweakrefs(n1)) del n1 # __del__ <weakref at 0x7fb0c26e75d0; dead> class DemoClass: def __init__(self, name): self.name = name print("----------------class weakref.WeakKeyDictionary([dict])") n = DemoClass("name") a = DemoClass("age") keyd = weakref.WeakKeyDictionary({n: "xxx", a: 2}) print(keyd[n])
def _swap_refs(old, new, ignores): """Swap references from one object to another""" __internal_swaprefs_ignore__ = "swap_refs" # Swap weak references refs = weakref.getweakrefs(old) if refs: try: newRef = weakref.ref(new) except ValueError: pass else: for oldRef in refs: _swap_refs(oldRef, newRef, ignores + (id(refs),)) del refs deque, defaultdict = _bonus_containers() # Swap through garbage collector referrers = gc.get_referrers(old) for container in referrers: if id(container) in ignores: continue containerType = type(container) if containerType is list or containerType is deque: for index in _find_sequence_indices(container, old): container[index] = new elif containerType is tuple: # protect from recursive tuples orig = container if id(orig) in _recursive_tuple_swap: continue _recursive_tuple_swap.add(id(orig)) try: container = list(container) for index in _find_sequence_indices(container, old): container[index] = new container = tuple(container) _swap_refs(orig, container, ignores + (id(referrers),)) finally: _recursive_tuple_swap.remove(id(orig)) elif containerType is dict or containerType is defaultdict: if "__internal_swaprefs_ignore__" not in container: try: if old in container: container[new] = container.pop(old) except TypeError: # Unhashable old value pass for k, v in container.iteritems(): if v is old: container[k] = new elif containerType is set: container.remove(old) container.add(new) elif containerType is type: if old in container.__bases__: bases = list(container.__bases__) bases[bases.index(old)] = new container.__bases__ = tuple(bases) elif type(container) is old: try: container.__class__ = new except TypeError: # Type error happens on slotted classes pass elif containerType is _InstanceType: if container.__class__ is old: container.__class__ = new
the same as the __dict__ attribute of a class as experimented in cls_attr2.py. """ import weakref class God(object): def __init__(self, name): self.name = name lilith = God('lilith') adam = God('adam') eva0 = weakref.proxy(adam) eva1 = weakref.proxy(lilith) print God.__weakref__.__get__(lilith, God) print weakref.getweakrefs(lilith) print God.__weakref__.__get__(lilith, God).name print lilith.__weakref__.name print God.__weakref__.__get__(adam, God) print weakref.getweakrefs(adam) print weakref.getweakrefcount(adam) print God.__weakref__.__get__(adam, God).name eva2 = weakref.proxy(adam) print God.__weakref__.__get__(adam, God) print weakref.getweakrefs(adam) print weakref.getweakrefcount(adam) print God.__weakref__.__get__(adam, God).name del eva0
if __name__ == '__main__': obj = Man('Tom') print sys.getrefcount(obj) # get the reference count of obj r = weakref.ref(obj) # 创建一个弱引用 print sys.getrefcount(obj) # 应用计数并没有发生变化 print 'weakref:', r # 弱引用所指向的对象信息 <weakref at 02C6BED0; to 'instance' at 02C744E0> obj2 = r() # 获取弱引用所指向的对象 print 'obj:', obj print 'obj2:', obj2 assert obj is obj2 # True print sys.getrefcount(obj) # +1 print weakref.getweakrefcount(obj) # 返回弱引用数 1 print weakref.getweakrefs( obj) # 返回引用列表 [<weakref at 02C3BED0; to 'instance' at 02C444E0>] obj = None obj2 = None print 'r:', r # 当对象引用计数为零时,弱引用失效。 <weakref at 02C6BED0; dead> man_obj = Man('Jerry') proxy_obj = weakref.proxy(man_obj, callback) # 创建代理对象 proxy_obj.test() man_obj = None proxy_obj.test() # ReferenceError # demo(WeakRequest)
def __weakref__(self): print "Inside weakref" a = Example() b = weakref.proxy(a) # b = a #b = weakref.ref(a) print a,b ''' c = Example() Example.get_count() ''' #print "EE =>", sys.getrefcount(Example()) #print "EAA=>", sys.getrefcount(Example) b._dp("LL") #b._dp("LL") print a.__hash__ #del a gc.collect() print b.__hash__ print weakref.getweakrefcount(a) print weakref.getweakrefs(a) print "ID :a() =>", id(a) print "ID :b() =>", id(b) print "HASH :a() =>", hash(a) #Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary keys. print "HASH :b() =>", hash(b)
# coding:utf-8 from socket import * import weakref # 创建弱引用 # 你可以通过调用weakref模块的ref(obj[,callback])来创建一个弱引用,obj是你想弱引用的对象,callback是一个可选的函数, # 当因没有引用导致Python要销毁这个对象时调用。回调函数callback要求单个参数(弱引用的对象) s = socket(AF_INET, SOCK_STREAM) ref = weakref.ref(s) print s print ref print ref() # 调用它来访问被引用的对象, 这里就是s对象 print weakref.getweakrefcount(s) # 返回弱引用数 print weakref.getweakrefs(s) # 所给对象的引用列表 # 创建代理对象 # 代理对象是弱引用对象,它们的行为就像它们所引用的对象,这就便于你不必首先调用弱引用来访问背后的对象。 # 通过weakref模块的proxy(obj[,callback])函数来创建代理对象。使用代理对象就如同使用对象本身一样 ref2 = weakref.proxy(s) print ref2 ref2.close() # ******************************************************************************************* # 弱引用使用的机会不是很多,一般用来进行 cache 编程。我们可以使用 weakref.ref() 来创建一个弱引用。 import sys class Class1(object): def test(self): print "test..."
def collect_and_show_garbage(): print "Collecting..." print "unreachable objects:", gc.collect() # 收集垃圾 print "garbage:", gc.garbage # gc.garbage 获取垃圾列表 if __name__ == '__main__': req_args = {'action_id': 222, 'data': 'test'} response = Response() request = Request(req_args) pre_process(request, response) print 'request引用计数器的值:', sys.getrefcount(request) print 'request弱引用数量:', weakref.getweakrefcount( request), 'request弱引用列表:', weakref.getweakrefs(request) # 原始: # request引用计数器的值: 3 # request弱引用数量: 0 request弱引用列表: [] # weakref.proxy(): # request引用计数器的值: 2 # request弱引用数量: 1 request弱引用列表: [<weakproxy at 02C0BB40 to Request at 02C1B090>] # request.ctx.request = None collect_and_show_garbage() # # print 'request:', request # print 'refcount:', sys.getrefcount(request) # print 'weakrefcount:', weakref.getweakrefcount(request), 'refs:', weakref.getweakrefs(request) #
a.color = 'red' print(a.color) proxy_a = weakref.proxy(a) print(a.color) print(proxy_a.color) print(a is proxy_a) print(a) print(proxy_a) del a a = Apple() r = weakref.ref(a) proxy_a = weakref.proxy(a) proxy_a weakref.getweakrefcount(a) weakref.getweakrefs(a)
import sys
import weakref print(dir(weakref)) class A: pass a = A() b = weakref.ref(a) c = weakref.ref(a) print(f"{id(a) =}") print(f"{id(b) =}") print(f"{id(c) =}") assert b is c assert b is a.__weakref__ print(weakref.getweakrefs(a))