示例#1
0
 def __init__(self, method, notifyDead=None):
     """The method must be bound. notifyDead will be called when 
     object that method is bound to dies. """
     assert ismethod(method)
     if method.im_self is None:
         raise ValueError, "We need a bound method!"
     if notifyDead is None:
         self.objRef = WeakRef(method.im_self)
     else:
         self.objRef = WeakRef(method.im_self, notifyDead)
     self.fun = method.im_func
     self.cls = method.im_class
示例#2
0
def apply(widget: tkImgWidgetsT, img: Handle | None) -> tkImgWidgetsT:
    """Set the image in a widget.

    This tracks the widget, so later reloads will affect the widget.
    If the image is None, it is instead unset.
    """
    ref = WeakRef(widget, _label_destroyed)
    if img is None:
        widget['image'] = None
        try:
            old = _wid_tk.pop(ref)
        except KeyError:
            pass
        else:
            old._decref(ref)
        return widget
    try:
        old = _wid_tk[ref]
    except KeyError:
        pass
    else:
        if old is img:
            # Unchanged.
            return widget
        old._decref(ref)
    img._incref(ref)
    _wid_tk[ref] = img
    cached_img = img._cached_tk
    if cached_img is not None:
        widget['image'] = cached_img
    else:  # Need to load.
        widget['image'] = img._request_load()
    return widget
示例#3
0
    def __init__(self, method, notifyDead=None):
        """The method must be bound. notifyDead will be called when
        object that method is bound to dies. """
        assert ismethod(method)
        if method.__self__ is None:
            raise ValueError('Unbound methods cannot be weak-referenced.')

        self.notifyDead = None
        if notifyDead is None:
            self.objRef = WeakRef(method.__self__)
        else:
            self.notifyDead = notifyDead
            self.objRef = WeakRef(method.__self__, self.__onNotifyDeadObj)

        self.fun = method.__func__
        self.cls = method.__self__.__class__
示例#4
0
文件: loop.py 项目: yssource/gevent
 def _register_watcher(self, python_watcher, ffi_watcher):
     self._active_watchers[ffi_watcher] = WeakRef(
         python_watcher,
         self.__make_watcher_ref_callback(type(python_watcher),
                                          self._active_watchers,
                                          ffi_watcher,
                                          repr(python_watcher)))
    def test_full_sweep_clears_weakrefs(self, sweep_method='incrgc'):
        # like test_full_sweep_clears_weakrefs_in_interface,
        # but directly using a weakref. This is the simplest version of the test.
        from weakref import ref as WeakRef
        gc.disable()
        self.addCleanup(gc.enable)

        jar = ClosedConnection(self)
        cache = self._makeOne(jar, 0)

        # Make a persistent object, put it in the cache as saved
        class P(self._getRealPersistentClass()):
            """A real persistent object that can be weak referenced."""

        p = P()
        p._p_jar = jar
        p._p_oid = b'\x01' * 8
        cache[p._p_oid] = p
        p._p_changed = False

        # Now, take a weak reference to it
        ref = WeakRef(p)

        # Remove the original object
        del p

        # Sweep the cache.
        getattr(cache, sweep_method)()

        # Now, try to use that weak reference; it should be gone.
        p = ref()
        self.assertIsNone(p)
示例#6
0
    def testTreeNode():
        class WS:
            def __init__(self, s):
                self.s = s

            def __call__(self, msg):
                print 'WS#', self.s, ' received msg ', msg

            def __str__(self):
                return self.s

        def testPreNotifyRoot(dead):
            print 'testPreNotifyROOT heard notification of', ` dead `

        node = _TopicTreeNode((ALL_TOPICS, ), WeakRef(testPreNotifyRoot))
        boo, baz, bid = WS('boo'), WS('baz'), WS('bid')
        node.addCallable(boo)
        node.addCallable(baz)
        node.addCallable(boo)
        assert node.getCallables() == [boo, baz]
        assert node.hasCallable(boo)

        node.removeCallable(bid)  # no-op
        assert node.hasCallable(baz)
        assert node.getCallables() == [boo, baz]

        node.removeCallable(boo)
        assert node.getCallables() == [baz]
        assert node.hasCallable(baz)
        assert not node.hasCallable(boo)

        node.removeCallable(baz)
        assert node.getCallables() == []
        assert not node.hasCallable(baz)

        node2 = node.createSubtopic('st1', ('st1', ))
        node3 = node.createSubtopic('st2', ('st2', ))
        cb1, cb2, cb = WS('st1_cb1'), WS('st1_cb2'), WS('st2_cb')
        node2.addCallable(cb1)
        node2.addCallable(cb2)
        node3.addCallable(cb)
        node2.createSubtopic('st3', ('st1', 'st3'))
        node2.createSubtopic('st4', ('st1', 'st4'))

        print str(node)
        assert str(
            node) == ' (st1: st1_cb1 st1_cb2  (st4: ) (st3: )) (st2: st2_cb )'

        # verify send message, and that a dead listener does not get sent one
        delivered = node2.sendMessage('hello')
        assert delivered == 2
        del cb1
        delivered = node2.sendMessage('hello')
        assert delivered == 1
        assert _NodeCallback.notified == 1

        done('testTreeNode')
示例#7
0
    def addTopic(self, topic, listener):
        """Add topic to tree if doesnt exist, and add listener to topic node"""
        assert isinstance(topic, tuple)
        topicNode = self.__getTreeNode(topic, make=True)
        weakCB = topicNode.addCallable(listener)
        assert topicNode.hasCallable(listener)

        theList = self.__callbackDict.setdefault(weakCB, [])
        assert self.__callbackDict.has_key(weakCB)
        # add it only if we don't already have it
        try:
            weakTopicNode = WeakRef(topicNode)
            theList.index(weakTopicNode)
        except ValueError:
            theList.append(weakTopicNode)
        assert self.__callbackDict[weakCB].index(weakTopicNode) >= 0
示例#8
0
 def unsubAll(self, topicList, onNoSuchTopic):
     """Unsubscribe all listeners registered for any topic in 
     topicList. If a topic in the list does not exist, and 
     onNoSuchTopic is not None, a call
     to onNoSuchTopic(topic) is done for that topic."""
     for topic in topicList:
         node = self.__getTreeNode(topic)
         if node is not None:
             weakCallables = node.clearCallables()
             for callable in weakCallables:
                 weakNodes = self.__callbackDict[callable]
                 success = _removeItem(WeakRef(node), weakNodes)
                 assert success == True
                 if weakNodes == []:
                     del self.__callbackDict[callable]
         elif onNoSuchTopic is not None:
             onNoSuchTopic(topic)
示例#9
0
 def __new__(klass, publisher, target, method):
     self = Handle.__new__(klass, publisher)
     self.__target = WeakRef(target)
     self.__method = method
     return self
示例#10
0
 def __new__(klass, publisher, function):
     self = Handle.__new__(klass, publisher)
     self.__function = WeakRef(function)
     return self
示例#11
0
 def __init__(self, obj: Component) -> None:
     self._uid = UniqueIdentifier[obj]
     self._ref = WeakRef(obj)