Python weakref.WeakMethod() Examples

The following are 30 code examples of weakref.WeakMethod(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module weakref , or try the search function .
Example #1
Source File: gst_media.py    From linux-show-player with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        super().__init__()

        self._state = MediaState.Null
        self._elements = []
        self._old_pipe = ''
        self._loop_count = 0

        self._gst_pipe = Gst.Pipeline()
        self._gst_state = Gst.State.NULL
        self._time_query = Gst.Query.new_position(Gst.Format.TIME)

        bus = self._gst_pipe.get_bus()
        bus.add_signal_watch()

        # Use a weakref instead of the method or the object will not be
        # garbage-collected
        on_message = weakref.WeakMethod(self.__on_message)
        handler = bus.connect('message', lambda *args: on_message()(*args))
        weakref.finalize(self, self.__finalizer, self._gst_pipe, handler,
                         self._elements)

        self.changed('loop').connect(self.__prepare_loops)
        self.changed('pipe').connect(self.__prepare_pipe) 
Example #2
Source File: Signal.py    From insteon-mqtt with GNU General Public License v3.0 6 votes vote down vote up
def connect(self, slot):
        """Connect a slot to the signal.

        If the input slot is already connected, nothing is done.

        Args:
           slot:  Instance method or function to connect.
        """
        # Create a weak reference to the method or function.
        if inspect.ismethod(slot):
            wr_slot = weakref.WeakMethod(slot)
        else:
            wr_slot = weakref.ref(slot)

        # Only insert the slot if it doesn't already exist.  If the index
        # method throws, the slot doesn't exist yet. Insert it at the
        # beginning so that when we call the slots in reverse order, they
        # will be called in the order inserted.
        if wr_slot not in self.slots:
            self.slots.insert(0, wr_slot)

    #----------------------------------------------------------------------- 
Example #3
Source File: Signal.py    From insteon-mqtt with GNU General Public License v3.0 6 votes vote down vote up
def disconnect(self, slot):
        """Disconnect a slot from the signal.

        If the input slot is not connected, nothing is done.

        Args:
           slot:  Instance method or function to disconnect.
        """
        # Create a weak reference to the method or function so that we can
        # use the comparison operator on the weakref to find the slot.
        if inspect.ismethod(slot):
            wr_slot = weakref.WeakMethod(slot)
        else:
            wr_slot = weakref.ref(slot)

        try:
            self.slots.remove(wr_slot)
        except ValueError:
            pass

    #----------------------------------------------------------------------- 
Example #4
Source File: event.py    From pyglet with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _remove_handler(self, name, handler):
        """Used internally to remove all handler instances for the given event name.

        This is normally called from a dead ``WeakMethod`` to remove itself from the
        event stack.
        """

        # Iterate over a copy as we might mutate the list
        for frame in list(self._event_stack):

            if name in frame:
                try:
                    if frame[name] == handler:
                        del frame[name]
                        if not frame:
                            self._event_stack.remove(frame)
                except TypeError:
                    # weakref is already dead
                    pass 
Example #5
Source File: __init__.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def connect(self, s, func):
        """Register *func* to be called when signal *s* is generated.
        """
        self._func_cid_map.setdefault(s, {})
        try:
            proxy = WeakMethod(func, self._remove_proxy)
        except TypeError:
            proxy = _StrongRef(func)
        if proxy in self._func_cid_map[s]:
            return self._func_cid_map[s][proxy]

        cid = next(self._cid_gen)
        self._func_cid_map[s][proxy] = cid
        self.callbacks.setdefault(s, {})
        self.callbacks[s][cid] = proxy
        return cid 
Example #6
Source File: test_weakref.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_hashing(self):
        # Alive WeakMethods are hashable if the underlying object is
        # hashable.
        x = Object(1)
        y = Object(1)
        a = weakref.WeakMethod(x.some_method)
        b = weakref.WeakMethod(y.some_method)
        c = weakref.WeakMethod(y.other_method)
        # Since WeakMethod objects are equal, the hashes should be equal.
        self.assertEqual(hash(a), hash(b))
        ha = hash(a)
        # Dead WeakMethods retain their old hash value
        del x, y
        gc.collect()
        self.assertEqual(hash(a), ha)
        self.assertEqual(hash(b), ha)
        # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
        self.assertRaises(TypeError, hash, c) 
Example #7
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_hashing(self):
        # Alive WeakMethods are hashable if the underlying object is
        # hashable.
        x = Object(1)
        y = Object(1)
        a = weakref.WeakMethod(x.some_method)
        b = weakref.WeakMethod(y.some_method)
        c = weakref.WeakMethod(y.other_method)
        # Since WeakMethod objects are equal, the hashes should be equal.
        self.assertEqual(hash(a), hash(b))
        ha = hash(a)
        # Dead WeakMethods retain their old hash value
        del x, y
        gc.collect()
        self.assertEqual(hash(a), ha)
        self.assertEqual(hash(b), ha)
        # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
        self.assertRaises(TypeError, hash, c) 
Example #8
Source File: signal.py    From linux-show-player with GNU General Public License v3.0 6 votes vote down vote up
def connect(self, slot_callable, mode=Connection.Direct):
        """Connect the given slot, if not already connected.

        :param slot_callable: The slot (a python callable) to be connected
        :param mode: Connection mode
        :type mode: Connection
        :raise ValueError: if mode not in Connection enum
        """
        if mode not in Connection:
            raise ValueError('invalid mode value: {0}'.format(mode))

        with self.__lock:
            # Create a new Slot object, use a weakref for the callback
            # to avoid cyclic references.
            callback = weak_call_proxy(weakref.WeakMethod(self.__remove_slot))
            self.__slots[slot_id(slot_callable)] = mode.new_slot(slot_callable,
                                                                 callback) 
Example #9
Source File: test_weakref.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_hashing(self):
        # Alive WeakMethods are hashable if the underlying object is
        # hashable.
        x = Object(1)
        y = Object(1)
        a = weakref.WeakMethod(x.some_method)
        b = weakref.WeakMethod(y.some_method)
        c = weakref.WeakMethod(y.other_method)
        # Since WeakMethod objects are equal, the hashes should be equal.
        self.assertEqual(hash(a), hash(b))
        ha = hash(a)
        # Dead WeakMethods retain their old hash value
        del x, y
        gc.collect()
        self.assertEqual(hash(a), ha)
        self.assertEqual(hash(b), ha)
        # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
        self.assertRaises(TypeError, hash, c) 
Example #10
Source File: signals.py    From easypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, func, asynchronous=False, priority=PRIORITIES.NONE, times=None, identifier=None, **kw):
        self.func = kwargs_resilient(func)
        self._func = get_original_func(func)  # save the original funtion so we can unregister based on the function

        # identifier only applicable to methods
        if inspect.ismethod(self._func) or isinstance(self._func, weakref.WeakMethod):
            self.identifier = identifier
        else:
            self.identifier = None

        # Backwards compatibility
        self.asynchronous = kw.pop("async", asynchronous)
        assert not kw, "SignalHandler's kwargs should contain only 'async' argument for backwards compatibility"

        self.priority = priority
        self.times = times
        self.idx = next(self._idx_gen)

        if isinstance(func, weakref.WeakMethod):
            func = func()  # to allow accessing it's __code__ and __name__
        self.filename = func.__code__.co_filename
        self.lineno = func.__code__.co_firstlineno
        self.name = self.__name__ = func.__name__ 
Example #11
Source File: __init__.py    From CogAlg with MIT License 6 votes vote down vote up
def connect(self, s, func):
        """Register *func* to be called when signal *s* is generated.
        """
        self._func_cid_map.setdefault(s, {})
        try:
            proxy = WeakMethod(func, self._remove_proxy)
        except TypeError:
            proxy = _StrongRef(func)
        if proxy in self._func_cid_map[s]:
            return self._func_cid_map[s][proxy]

        cid = next(self._cid_gen)
        self._func_cid_map[s][proxy] = cid
        self.callbacks.setdefault(s, {})
        self.callbacks[s][cid] = proxy
        return cid 
Example #12
Source File: __init__.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def connect(self, s, func):
        """Register *func* to be called when signal *s* is generated.
        """
        self._func_cid_map.setdefault(s, {})
        try:
            proxy = WeakMethod(func, self._remove_proxy)
        except TypeError:
            proxy = _StrongRef(func)
        if proxy in self._func_cid_map[s]:
            return self._func_cid_map[s][proxy]

        cid = next(self._cid_gen)
        self._func_cid_map[s][proxy] = cid
        self.callbacks.setdefault(s, {})
        self.callbacks[s][cid] = proxy
        return cid 
Example #13
Source File: __init__.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def connect(self, s, func):
        """Register *func* to be called when signal *s* is generated.
        """
        self._func_cid_map.setdefault(s, {})
        try:
            proxy = WeakMethod(func, self._remove_proxy)
        except TypeError:
            proxy = _StrongRef(func)
        if proxy in self._func_cid_map[s]:
            return self._func_cid_map[s][proxy]

        cid = next(self._cid_gen)
        self._func_cid_map[s][proxy] = cid
        self.callbacks.setdefault(s, {})
        self.callbacks[s][cid] = proxy
        return cid 
Example #14
Source File: __init__.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def connect(self, s, func):
        """Register *func* to be called when signal *s* is generated.
        """
        self._func_cid_map.setdefault(s, {})
        try:
            proxy = WeakMethod(func, self._remove_proxy)
        except TypeError:
            proxy = _StrongRef(func)
        if proxy in self._func_cid_map[s]:
            return self._func_cid_map[s][proxy]

        cid = next(self._cid_gen)
        self._func_cid_map[s][proxy] = cid
        self.callbacks.setdefault(s, {})
        self.callbacks[s][cid] = proxy
        return cid 
Example #15
Source File: central_dispatch.py    From scqubits with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _dispatch(self, event, sender, **kwargs):
        """Issue a dispatch for `event` coming from `sender.

        Parameters
        ----------
        event: str
            event name from EVENTS
        sender: DispatchClient
            object requesting the dispatch
        **kwargs
        """
        for client, callback_ref in self.get_clients_dict(event).items():
            logging.debug("Central dispatch calling {} about {}.".format(type(client).__name__, event))
            callback_ref(event, sender=sender, **kwargs)
            # When using WeakMethod references, this should rather be:
            # callback_ref()(event, sender=sender, **kwargs) 
Example #16
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_callback_when_method_dead(self):
        # Test callback behaviour when method dies first.
        C = self._subclass()
        calls = []
        def cb(arg):
            calls.append(arg)
        o = C(1)
        r = weakref.WeakMethod(o.some_method, cb)
        del C.some_method
        gc.collect()
        self.assertEqual(calls, [r])
        # Callback is only called once.
        del o
        gc.collect()
        self.assertEqual(calls, [r]) 
Example #17
Source File: mp.py    From mpwn with MIT License 5 votes vote down vote up
def weak_callable(cb: Callable) -> 'weakref.ReferenceType[Callable]':
    if inspect.ismethod(cb):
        ref = weakref.WeakMethod(cb)
    else:
        ref = weakref.ref(cb)
    return ref 
Example #18
Source File: context.py    From rclpy with Apache License 2.0 5 votes vote down vote up
def on_shutdown(self, callback: Callable[[], None]):
        """Add a callback to be called on shutdown."""
        if not callable(callback):
            raise TypeError('callback should be a callable, got {}', type(callback))
        with self._callbacks_lock:
            if not self.ok():
                callback()
            else:
                self._callbacks.append(weakref.WeakMethod(callback, self._remove_callback)) 
Example #19
Source File: test_utils.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def test_get_weakref_bound(self):
        mock_val = Mock()
        getter = TestGetWeakref.Getter(mock_val)
        ref = utils.get_weakref(getter.get)
        self.assertIsInstance(ref, WeakMethod)
        self.assertEqual(ref(), getter.get)
        self.assertIs(ref()(), mock_val)

        del getter
        gc.collect()
        self.assertIsNotNone(ref)
        self.assertIsNone(ref()) 
Example #20
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_alive(self):
        o = Object(1)
        r = weakref.WeakMethod(o.some_method)
        self.assertIsInstance(r, weakref.ReferenceType)
        self.assertIsInstance(r(), type(o.some_method))
        self.assertIs(r().__self__, o)
        self.assertIs(r().__func__, o.some_method.__func__)
        self.assertEqual(r()(), 4) 
Example #21
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_object_dead(self):
        o = Object(1)
        r = weakref.WeakMethod(o.some_method)
        del o
        gc.collect()
        self.assertIs(r(), None) 
Example #22
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_method_dead(self):
        C = self._subclass()
        o = C(1)
        r = weakref.WeakMethod(o.some_method)
        del C.some_method
        gc.collect()
        self.assertIs(r(), None) 
Example #23
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_callback_when_object_dead(self):
        # Test callback behaviour when object dies first.
        C = self._subclass()
        calls = []
        def cb(arg):
            calls.append(arg)
        o = C(1)
        r = weakref.WeakMethod(o.some_method, cb)
        del o
        gc.collect()
        self.assertEqual(calls, [r])
        # Callback is only called once.
        C.some_method = Object.some_method
        gc.collect()
        self.assertEqual(calls, [r]) 
Example #24
Source File: signals.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_object(obj, **kwargs):
    for method_name in get_signals_for_type(type(obj)):
        method = getattr(obj, method_name)
        assert callable(method), "'%s' (%r) is not callable" % (method, obj)

        # Don't use static/class methods for automatic event registration - they
        # could be registered multiple times if the are multiple objects of that
        # type in the system, or not at all if there are no objects of that type
        # in the system.
        assert method is not getattr(type(obj), method_name, None), "'%s' is a static/class method" % method

        params = getattr(method, '_signal_handler_params', {})
        intersection = set(params).intersection(kwargs)
        assert not intersection, "parameter conflict in signal object registration (%s)" % (intersection)
        params.update(kwargs)

        method_name, *_ = method_name.partition("__")  # allows multiple methods for the same signal

        if not inspect.ismethod(method):
            # Fake method attributes for WeakMethod
            method.__self__ = obj
            method.__func__ = getattr(type(obj), method_name)
            if not hasattr(method, '__code__'):
                method.__code__ = __FakeCode('', '')
            fake_meth_type = functools.partial(
                __fake_meth_type,
                # Best effort: fake name and code for SignalHandler. We don't know the line number.
                name=method_name,
                code=__FakeCode(type(obj).__module__, '?'))

        method = weakref.WeakMethod(method)
        try:
            method._meth_type = fake_meth_type
        except UnboundLocalError:
            pass

        register_signal(method_name, method, **params) 
Example #25
Source File: test_weakref.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_equality(self):
        def _eq(a, b):
            self.assertTrue(a == b)
            self.assertFalse(a != b)
        def _ne(a, b):
            self.assertTrue(a != b)
            self.assertFalse(a == b)
        x = Object(1)
        y = Object(1)
        a = weakref.WeakMethod(x.some_method)
        b = weakref.WeakMethod(y.some_method)
        c = weakref.WeakMethod(x.other_method)
        d = weakref.WeakMethod(y.other_method)
        # Objects equal, same method
        _eq(a, b)
        _eq(c, d)
        # Objects equal, different method
        _ne(a, c)
        _ne(a, d)
        _ne(b, c)
        _ne(b, d)
        # Objects unequal, same or different method
        z = Object(2)
        e = weakref.WeakMethod(z.some_method)
        f = weakref.WeakMethod(z.other_method)
        _ne(a, e)
        _ne(a, f)
        _ne(b, e)
        _ne(b, f)
        del x, y, z
        gc.collect()
        # Dead WeakMethods compare by identity
        refs = a, b, c, d, e, f
        for q in refs:
            for r in refs:
                self.assertEqual(q == r, q is r)
                self.assertEqual(q != r, q is not r) 
Example #26
Source File: dispatcher.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def register(self, receiver, weak=True, dispatch_uid=None):
		"""
		Connect receiver to sender for signal.

		:param receiver: A function or an instance method which is to receive signals. Receivers must be hashable objects.
			If weak is True, then receiver must be weak referenceable.Receivers must be able to accept keyword arguments.
			If a receiver is connected with a dispatch_uid argument, it
			will not be added if another receiver was already connected with that dispatch_uid.

		:param weak: Whether to use weak references to the receiver. By default, the
			module will attempt to use weak references to the receiver
			objects. If this parameter is false, then strong references will
			be used.

		:param dispatch_uid: An identifier used to uniquely identify a particular instance of
			a receiver. This will usually be a string, though it may be anything hashable.
		"""
		if dispatch_uid:
			lookup_key = dispatch_uid
		else:
			lookup_key = _make_id(receiver)

		if weak:
			ref = weakref.ref
			receiver_object = receiver

			# Check for bound methods.
			if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'):
				ref = weakref.WeakMethod
				receiver_object = receiver.__self__
			receiver = ref(receiver)
			weakref.finalize(receiver_object, self._remove_receiver)

		with self.lock:
			self._clear_dead_receivers()
			for rec_key in self.receivers:
				if rec_key == lookup_key:
					break
			else:
				self.receivers.append((lookup_key, receiver))
			self.sender_receivers_cache.clear() 
Example #27
Source File: event.py    From pyglet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_handlers(self, args, kwargs):
        """Implement handler matching on arguments for set_handlers and
        remove_handlers.
        """
        for obj in args:
            if inspect.isroutine(obj):
                # Single magically named function
                name = obj.__name__
                if name not in self.event_types:
                    raise EventException('Unknown event "%s"' % name)
                if inspect.ismethod(obj):
                    yield name, WeakMethod(obj, partial(self._remove_handler, name))
                else:
                    yield name, obj
            else:
                # Single instance with magically named methods
                for name in dir(obj):
                    if name in self.event_types:
                        meth = getattr(obj, name)
                        yield name, WeakMethod(meth, partial(self._remove_handler, name))

        for name, handler in kwargs.items():
            # Function for handling given event (no magic)
            if name not in self.event_types:
                raise EventException('Unknown event "%s"' % name)
            if inspect.ismethod(handler):
                yield name, WeakMethod(handler, partial(self._remove_handler, name))
            else:
                yield name, handler 
Example #28
Source File: __init__.py    From opencensus-python with Apache License 2.0 5 votes vote down vote up
def get_weakref(func):
    """Get a weak reference to bound or unbound `func`.

    If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref,
    otherwise get a wrapper that simulates weakref.ref.
    """
    if func is None:
        raise ValueError
    if not hasattr(func, '__self__'):
        return weakref.ref(func)
    return WeakMethod(func) 
Example #29
Source File: misc.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, weak_method):
        if isinstance(weak_method, MethodType):
            weak_method = weakref.WeakMethod(weak_method)
        self.weak_method = weak_method
        update_wrapper(self, weak_method(), updated=())
        self.__wrapped__ = weak_method 
Example #30
Source File: signals.py    From easypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bound_object(self):
        if isinstance(self._func, weakref.WeakMethod):
            return weakref.ref.__call__(self._func)
        else:
            return None