当前位置: 首页>>代码示例>>Python>>正文


Python weakref.ref函数代码示例

本文整理汇总了Python中weakref.ref函数的典型用法代码示例。如果您正苦于以下问题:Python ref函数的具体用法?Python ref怎么用?Python ref使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了ref函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

 def __init__(self, c):
     if hasattr(c,'im_func'):
         self._func = weakref.ref(c.im_func)
         self._ob = weakref.ref(c.im_self)
     else:
         self._func = weakref.ref(c)
         self._ob = None
开发者ID:chiluf,项目名称:visvis.dev,代码行数:7,代码来源:events.py

示例2: test_weakref_slots

 def test_weakref_slots(self):
     """Check that classes are using slots and are weak-referenceable"""
     for cls in [self.xs_cls, self.hxs_cls, self.xxs_cls]:
         x = cls()
         weakref.ref(x)
         assert not hasattr(x, '__dict__'), "%s does not use __slots__" % \
             x.__class__.__name__
开发者ID:SeaBear,项目名称:scrapy,代码行数:7,代码来源:test_selector.py

示例3: test_no_refcycle_through_target

    def test_no_refcycle_through_target(self):
        class RunSelfFunction(object):
            def __init__(self, should_raise):
                # The links in this refcycle from Thread back to self
                # should be cleaned up when the thread completes.
                self.should_raise = should_raise
                self.thread = threading.Thread(target=self._run, args=(self,), kwargs={"yet_another": self})
                self.thread.start()

            def _run(self, other_ref, yet_another):
                if self.should_raise:
                    raise SystemExit

        cyclic_object = RunSelfFunction(should_raise=False)
        weak_cyclic_object = weakref.ref(cyclic_object)
        cyclic_object.thread.join()
        del cyclic_object
        self.assertIsNone(
            weak_cyclic_object(), msg=("%d references still around" % sys.getrefcount(weak_cyclic_object()))
        )

        raising_cyclic_object = RunSelfFunction(should_raise=True)
        weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
        raising_cyclic_object.thread.join()
        del raising_cyclic_object
        self.assertIsNone(
            weak_raising_cyclic_object(),
            msg=("%d references still around" % sys.getrefcount(weak_raising_cyclic_object())),
        )
开发者ID:pykomke,项目名称:Kurz_Python_KE,代码行数:29,代码来源:test_threading.py

示例4: test_compatibility_layer

    def test_compatibility_layer(self):
        # Create a new pool
        pool = Pool()
        parent_pool_ref = weakref.ref(pool)
        pool = svn_pool_create(Pool(pool))
        pool_ref = weakref.ref(pool)

        # Make sure proper exceptions are raised with incorrect input
        self.assertRaises(TypeError, lambda: svn_pool_create("abcd"))

        # Test whether pools are destroyed properly
        pool = svn_pool_create(pool)
        self.assertNotNone(pool_ref())
        self.assertNotNone(parent_pool_ref())
        del pool
        self.assertNone(pool_ref())
        self.assertNone(parent_pool_ref())

        # Ensure that AssertionErrors are raised when a pool is deleted twice
        newpool = Pool()
        newpool2 = Pool(newpool)
        svn_pool_clear(newpool)
        self.assertRaises(AssertionError, lambda: libsvn.core.apr_pool_destroy(newpool2))
        self.assertRaises(AssertionError, lambda: svn_pool_destroy(newpool2))
        svn_pool_destroy(newpool)
        self.assertRaises(AssertionError, lambda: svn_pool_destroy(newpool))

        # Try to allocate memory from a destroyed pool
        self.assertRaises(AssertionError, lambda: svn_pool_create(newpool))

        # Create and destroy a pool
        svn_pool_destroy(svn_pool_create())

        # Make sure anonymous pools are destroyed properly
        anonymous_pool_ref = weakref.ref(svn_pool_create())
        self.assertNone(anonymous_pool_ref())

        # Try to cause a segfault using apr_terminate
        apr_terminate()
        apr_initialize()
        apr_terminate()
        apr_terminate()

        # Destroy the application pool
        svn_pool_destroy(libsvn.core.application_pool)

        # Double check that the application pool has been deleted
        self.assertNone(libsvn.core.application_pool)

        # Try to allocate memory from the old application pool
        self.assertRaises(AssertionError, lambda: svn_pool_create(application_pool))

        # Bring the application pool back to life
        svn_pool_create()

        # Double check that the application pool has been created
        self.assertNotNone(libsvn.core.application_pool)

        # We can still destroy and create pools at will
        svn_pool_destroy(svn_pool_create())
开发者ID:vocho,项目名称:openqnx,代码行数:60,代码来源:pool.py

示例5: safeRef

def safeRef(target, onDelete = None):
    """Return a *safe* weak reference to a callable target

    target -- the object to be weakly referenced, if it's a
        bound method reference, will create a BoundMethodWeakref,
        otherwise creates a simple weakref.
    onDelete -- if provided, will have a hard reference stored
        to the callable to be called after the safe reference
        goes out of scope with the reference object, (either a
        weakref or a BoundMethodWeakref) as argument.
    """
    if hasattr(target, '__self__'):
        if target.__self__ is not None:
            # Turn a bound method into a BoundMethodWeakref instance.
            # Keep track of these instances for lookup by disconnect().
            assert hasattr(target, '__func__'), """safeRef target %r has __self__, but no __func__, don't know how to create reference"""%( target,)
            reference = get_bound_method_weakref(
                target=target,
                onDelete=onDelete
            )
            return reference
    if callable(onDelete):
        return weakref.ref(target, onDelete)
    else:
        return weakref.ref( target )
开发者ID:eliasjf,项目名称:cs319-server-dashboard,代码行数:25,代码来源:saferef.py

示例6: load

	def load(self, db):
		data = db("SELECT value FROM last_active_settlement WHERE type = \"PLAYER\"")
		self._last_player_settlement = weakref.ref(WorldObject.get_object_by_id(data[0][0])) if data else None
		data = db("SELECT value FROM last_active_settlement WHERE type = \"ANY\"")
		self._last_settlement = weakref.ref(WorldObject.get_object_by_id(data[0][0])) if data else None
		data = db("SELECT value FROM last_active_settlement WHERE type = \"LAST_NONE_FLAG\"")
		self._last_player_settlement_hovered_was_none = bool(data[0][0])
开发者ID:aviler,项目名称:unknown-horizons,代码行数:7,代码来源:lastactiveplayersettlementmanager.py

示例7: safe_ref

def safe_ref(target, on_delete=None):
    """Return a *safe* weak reference to a callable target.

    - ``target``: The object to be weakly referenced, if it's a bound
      method reference, will create a BoundMethodWeakref, otherwise
      creates a simple weakref.

    - ``on_delete``: If provided, will have a hard reference stored to
      the callable to be called after the safe reference goes out of
      scope with the reference object, (either a weakref or a
      BoundMethodWeakref) as argument.
    """
    try:
        im_self = get_self(target)
    except AttributeError:
        if callable(on_delete):
            return weakref.ref(target, on_delete)
        else:
            return weakref.ref(target)
    else:
        if im_self is not None:
            # Turn a bound method into a BoundMethodWeakref instance.
            # Keep track of these instances for lookup by disconnect().
            assert hasattr(target, 'im_func') or hasattr(target, '__func__'), (
                "safe_ref target %r has im_self, but no im_func, "
                "don't know how to create reference" % target)
            reference = BoundMethodWeakref(target=target, on_delete=on_delete)
            return reference
开发者ID:gpfl7846,项目名称:homepage,代码行数:28,代码来源:_saferef.py

示例8: disableNotifications

    def disableNotifications(self, observable=None, notification=None, observer=None):
        """
        Disable all posts of **notification** from **observable** posted
        to **observer** observing.

        * **observable** The object that the notification belongs to. This is optional.
          If no *observable* is given, *all* *notifications* will be disabled for *observer*.
        * **notification** The name of the notification. This is optional.
          If no *notification* is given, *all* notifications for *observable*
          will be disabled for *observer*.
        * **observer** The specific observer to not send posts to. If no
          *observer* is given, the appropriate notifications will not
          be posted to any observers.

        This object will retain a count of how many times it has been told to
        disable notifications for *notification* and *observable*. It will not
        enable new notifications until the *notification* and *observable*
        have been released the same number of times.
        """
        if observable is not None:
            observable = weakref.ref(observable)
        if observer is not None:
            observer = weakref.ref(observer)
        key = (notification, observable, observer)
        if key not in self._disabled:
            self._disabled[key] = 0
        self._disabled[key] += 1
开发者ID:LettError,项目名称:defcon,代码行数:27,代码来源:notifications.py

示例9: addObserver

    def addObserver(self, observer, methodName, notification=None, observable=None):
        """
        Add an observer to this notification dispatcher.

        * **observer** An object that can be referenced with weakref.
        * **methodName** A string epresenting the method to be called
          when the notification is posted.
        * **notification** The notification that the observer should
          be notified of. If this is None, all notifications for
          the *observable* will be posted to *observer*.
        * **observable** The object to observe. If this is None,
          all notifications with the name provided as *notification*
          will be posted to the *observer*.

        If None is given for both *notification* and *observable*
        **all** notifications posted will be sent to the method
        given method of the observer.

        The method that will be called as a result of the action
        must accept a single *notification* argument. This will
        be a :class:`Notification` object.
        """
        if observable is not None:
            observable = weakref.ref(observable)
        observer = weakref.ref(observer)
        key = (notification, observable)
        if key not in self._registry:
            self._registry[key] = ObserverDict()
        assert observer not in self._registry[key], "An observer is only allowed to have one callback for a given notification + observable combination."
        self._registry[key][observer] = methodName
开发者ID:LettError,项目名称:defcon,代码行数:30,代码来源:notifications.py

示例10: test_keep_alive_noleak2

def test_keep_alive_noleak2():
    # Even if the above would not work ...
    
    class Foo:
        pass
    
    # Create a session and an object that has a reference to it (like Model)
    session = app.Session('test')
    foo = Foo()
    foo.session = session
    
    # Let the session keep the object alive, so it keeps its reference
    session.keep_alive(foo)
    
    session_ref = weakref.ref(session)
    foo_ref = weakref.ref(foo)
    
    # Removing session wont delete it
    del session
    gc.collect()
    assert session_ref() is not None
    
    # But removing both will; gc is able to clear circular ref
    del foo
    gc.collect()
    assert session_ref() is None
    assert foo_ref() is None
开发者ID:Konubinix,项目名称:flexx,代码行数:27,代码来源:test_model.py

示例11: holdNotifications

    def holdNotifications(self, observable=None, notification=None, observer=None):
        """
        Hold all notifications posted to all objects observing
        **notification** in **observable**.

        * **observable** The object that the notification belongs to. This is optional.
          If no *observable* is given, *all* *notifications* will be held.
        * **notification** The name of the notification. This is optional.
          If no *notification* is given, *all* notifications for *observable*
          will be held.
         * **observer** The specific observer to not hold notifications for.
           If no *observer* is given, the appropriate notifications will be
           held for all observers.

        Held notifications will be posted after the matching *notification*
        and *observable* have been passed to :meth:`Notification.releaseHeldNotifications`.
        This object will retain a count of how many times it has been told to
        hold notifications for *notification* and *observable*. It will not
        post the notifications until the *notification* and *observable*
        have been released the same number of times.
        """
        if observable is not None:
            observable = weakref.ref(observable)
        if observer is not None:
            observer = weakref.ref(observer)
        key = (notification, observable, observer)
        if key not in self._holds:
            self._holds[key] = dict(count=0, notifications=[])
        self._holds[key]["count"] += 1
开发者ID:LettError,项目名称:defcon,代码行数:29,代码来源:notifications.py

示例12: test_keep_alive_noleak1

def test_keep_alive_noleak1():
    
    class Foo:
        pass
    
    # Create a session and an object that has a reference to it (like Model)
    session = app.Session('test')
    foo = Foo()
    foo.session = session
    
    # Let the session keep the object alive, so it keeps its reference
    session.keep_alive(foo)
    
    session_ref = weakref.ref(session)
    foo_ref = weakref.ref(foo)
    
    # Removing object wont delete it
    del foo
    gc.collect()
    assert foo_ref() is not None
    
    # But closing the session will; session clears up after itself
    session.close()
    gc.collect()
    assert foo_ref() is None
开发者ID:Konubinix,项目名称:flexx,代码行数:25,代码来源:test_model.py

示例13: testMemoryIsFreed

  def testMemoryIsFreed(self):
    # Note: we use `set` values for components and metadata because we need
    # to construct weakrefs to them.  Other builtin types, such as `list` and
    # `tuple`, do not support weakrefs.
    ct1 = CT(set([1, 2]), set(['no', 'leaks']))
    ct2 = CT(set([3, 4]), set(['no', 'leaks']))
    ct3 = CT(set([5, 6]), set(['other', 'metadata']))

    # Note: map_structure exercises flatten, pack_sequence_as, and
    # assert_same_structure.
    func = lambda x, y: x | y
    ct4 = nest.map_structure(func, ct1, ct2, expand_composites=True)

    # Check that the exception-raising path in assert_same_structure
    # doesn't leak any objects.
    with self.assertRaisesRegexp(ValueError,
                                 ".*don't have the same nested structure.*"):
      nest.map_structure(func, ct2, ct3, expand_composites=True)
    if hasattr(sys, 'exc_clear'):
      sys.exc_clear()  # Remove any references in exception stack traces.

    refs = []
    for ct in [ct1, ct2, ct3, ct4]:
      refs.append(weakref.ref(ct))
      refs.append(weakref.ref(ct.components))
      refs.append(weakref.ref(ct.metadata))
    del ct  # pylint: disable=undefined-loop-variable

    for ref in refs:
      self.assertIsNotNone(ref())

    del ct1, ct2, ct3, ct4
    gc.collect()
    for ref in refs:
      self.assertIsNone(ref())
开发者ID:aritratony,项目名称:tensorflow,代码行数:35,代码来源:composite_tensor_test.py

示例14: test_model_garbage_collection

    def test_model_garbage_collection(self):
        """
        Make sure tenant models are correctly garbage collected upon deletion.
        """
        tenant = Tenant.objects.create(name='tenant')

        # Keep weak-references to tenant and associated models to make sure
        # they have been colllected.
        tenant_wref = weakref.ref(tenant)
        models_wrefs = []
        for model in TenantModelBase.references:
            # Make sure all models have their relation tree populated.
            getattr(model._meta, '_relation_tree')
            models_wrefs.append(weakref.ref(model.for_tenant(tenant)))

        # Delete the tenant and all it's associated models.
        tenant.delete()
        del tenant

        # Force a garbage collection for the benefit of non-reference counting
        # implementations.
        gc.collect()

        # Make sure all references have been removed.
        self.assertIsNone(tenant_wref())
        for model_wref in models_wrefs:
            self.assertIsNone(model_wref())
开发者ID:charettes,项目名称:django-tenancy,代码行数:27,代码来源:test_models.py

示例15: ViewCell

def ViewCell(base, get_transform, set_transform, **kwargs):
    """
    A Cell whose value is always a transformation of another.
    
    TODO: Stop implementing this as LooseCell.
    """
    
    def forward(view_value):
        base_value = set_transform(view_value)
        base.set(base_value)
        actual_base_value = base.get()
        if base_value != actual_base_value:
            reverse(actual_base_value)
    
    def reverse(base_value):
        self.set(get_transform(base_value))
    
    self = LooseCell(
        value=get_transform(base.get()),
        post_hook=forward,
        **kwargs)
    
    sub = base._subscribe_immediate(reverse)
    weakref.ref(self, lambda: sub.unsubscribe())

    # Allows the cell to be put back in sync if the transform changes.
    # Not intended to be called except by the creator of the cell, but mostly harmless.
    def changed_transform():
        reverse(base.get())
    
    self.changed_transform = changed_transform  # pylint: disable=attribute-defined-outside-init
    
    return self
开发者ID:thefinn93,项目名称:shinysdr,代码行数:33,代码来源:values.py


注:本文中的weakref.ref函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。