當前位置: 首頁>>代碼示例>>Python>>正文


Python weakref.ReferenceType方法代碼示例

本文整理匯總了Python中weakref.ReferenceType方法的典型用法代碼示例。如果您正苦於以下問題:Python weakref.ReferenceType方法的具體用法?Python weakref.ReferenceType怎麽用?Python weakref.ReferenceType使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在weakref的用法示例。


在下文中一共展示了weakref.ReferenceType方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: base_equal

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def base_equal(self, ob1, ob2):
        if type(ob1) != type(ob2):
            return False

        def cmp(obj1, obj2):
            if isinstance(obj1, np.ndarray):
                return np.array_equal(obj1, obj2)
            elif isinstance(obj1, Iterable) and \
                    not isinstance(obj1, str) and \
                    isinstance(obj2, Iterable) and \
                    not isinstance(obj2, str):
                return all(cmp(it1, it2) for it1, it2 in itertools.zip_longest(obj1, obj2))
            elif hasattr(obj1, 'key') and hasattr(obj2, 'key'):
                return obj1.key == obj2.key
            elif isinstance(obj1, ReferenceType) and isinstance(obj2, ReferenceType):
                return cmp(obj1(), obj2())
            else:
                return obj1 == obj2

        for slot in ob1.__slots__:
            if not cmp(getattr(ob1, slot, None), getattr(ob2, slot, None)):
                return False

        return True 
開發者ID:mars-project,項目名稱:mars,代碼行數:26,代碼來源:core.py

示例2: test_gc

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def test_gc(self):
        # Github issue 1769: Runner objects can get GCed unexpectedly
        # while their future is alive.
        weakref_scope = [None]  # type: List[Optional[weakref.ReferenceType]]

        def callback():
            gc.collect(2)
            weakref_scope[0]().set_result(123)  # type: ignore

        @gen.coroutine
        def tester():
            fut = Future()  # type: Future[int]
            weakref_scope[0] = weakref.ref(fut)
            self.io_loop.add_callback(callback)
            yield fut

        yield gen.with_timeout(datetime.timedelta(seconds=0.2), tester()) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:19,代碼來源:gen_test.py

示例3: __init__

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def __init__(
        self,
        *,
        path_id: Optional[pathid.PathId]=None,
        fenced: bool=False,
        unique_id: Optional[int]=None,
    ) -> None:
        self.unique_id = unique_id
        self.path_id = path_id
        self.fenced = fenced
        self.protect_parent = False
        self.unnest_fence = False
        self.factoring_fence = False
        self.factoring_whitelist = set()
        self.optional = False
        self.children = set()
        self.namespaces = set()
        self._parent: Optional[weakref.ReferenceType[ScopeTreeNode]] = None 
開發者ID:edgedb,項目名稱:edgedb,代碼行數:20,代碼來源:scopetree.py

示例4: __init__

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def __init__(
        self,
        tb: Union[TracebackType, Iterable[TracebackEntry]],
        excinfo: Optional["ReferenceType[ExceptionInfo]"] = None,
    ) -> None:
        """ initialize from given python traceback object and ExceptionInfo """
        self._excinfo = excinfo
        if isinstance(tb, TracebackType):

            def f(cur: TracebackType) -> Iterable[TracebackEntry]:
                cur_ = cur  # type: Optional[TracebackType]
                while cur_ is not None:
                    yield TracebackEntry(cur_, excinfo=excinfo)
                    cur_ = cur_.tb_next

            super().__init__(f(tb))
        else:
            super().__init__(tb) 
開發者ID:pytest-dev,項目名稱:pytest,代碼行數:20,代碼來源:code.py

示例5: list_pubs

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def list_pubs():
#    import pdb; pdb.set_trace()
    import weakref
    msg = []
    for receiver in signals.post_save.receivers:
        (receiver_class_name,_), receiver = receiver
        # django.contrib.contenttypes.generic.GenericForeignKey.instance_pre_init is not weakref
        if isinstance(receiver, weakref.ReferenceType):
            receiver = receiver()
        receiver = getattr(receiver, '__wraps__', receiver)
        receiver_name = getattr(receiver, '__name__', str(receiver))
        text = "%s.%s" % (receiver_class_name, receiver_name)
        if receiver_name == 'publish_rdf' :
            msg.append(text)

    return str(msg) 
開發者ID:rob-metalinkage,項目名稱:django-rdf-io,代碼行數:18,代碼來源:utils.py

示例6: emit

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def emit(self, *args):
        # allow remove receiver during emitting
        for receiver in self.receivers.copy():
            try:
                if self._is_alive(receiver):
                    if isinstance(receiver, weakref.ReferenceType):
                        func = receiver()
                    else:
                        func = receiver
                    if Signal.has_aio_support:
                        uid = gen_id(func)
                        aioqueue = uid in self.aioqueued_receiver_ids
                        if aioqueue:
                            Signal.aioqueue.sync_q.put_nowait((func, args))
                        else:
                            func(*args)
                    else:
                        func(*args)
                else:
                    logger.debug('receiver:{} is dead'.format(receiver))
            except Exception:
                logger.exception('receiver %s raise error' % receiver) 
開發者ID:feeluown,項目名稱:FeelUOwn,代碼行數:24,代碼來源:dispatch.py

示例7: __init__

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def __init__(self, imagecrawler: BaseImageCrawler, *,
                 weight: _CrawlerWeight = 1.0,
                 restart_at_front_when_exhausted: bool = False,
                 is_image_addable: Optional[_IsImageAddable] = None,
                 on_image_added: Optional[_OnImageAdded] = None
                 ) -> None:  # pragma: no cover
        if weight <= 0:
            raise ValueError('weight <= 0')
        self.imagecrawler = imagecrawler
        self.weight = weight
        self.restart_at_front_when_exhausted = restart_at_front_when_exhausted
        self.images = ImageCollection()
        self._is_image_addable_wr: Optional[ReferenceType[_IsImageAddable]] = None
        self._image_added_wr: Optional[ReferenceType[_OnImageAdded]] = None
        self.set_is_image_addable(is_image_addable)
        self.set_image_added(on_image_added) 
開發者ID:k4cg,項目名稱:nichtparasoup,代碼行數:18,代碼來源:__init__.py

示例8: __init__

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def __init__(
        self,
        key_processor_ref: "weakref.ReferenceType[KeyProcessor]",
        arg: Optional[str],
        key_sequence: List[KeyPress],
        previous_key_sequence: List[KeyPress],
        is_repeat: bool,
    ) -> None:

        self._key_processor_ref = key_processor_ref
        self.key_sequence = key_sequence
        self.previous_key_sequence = previous_key_sequence

        #: True when the previous key sequence was handled by the same handler.
        self.is_repeat = is_repeat

        self._arg = arg
        self._app = get_app() 
開發者ID:prompt-toolkit,項目名稱:python-prompt-toolkit,代碼行數:20,代碼來源:key_processor.py

示例9: __init__

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def __init__(self, name: str, name_full: str,
                 sessionplayer: ba.SessionPlayer, stats: ba.Stats):
        self.name = name
        self.name_full = name_full
        self.score = 0
        self.accumscore = 0
        self.kill_count = 0
        self.accum_kill_count = 0
        self.killed_count = 0
        self.accum_killed_count = 0
        self._multi_kill_timer: Optional[ba.Timer] = None
        self._multi_kill_count = 0
        self._stats = weakref.ref(stats)
        self._last_sessionplayer: Optional[ba.SessionPlayer] = None
        self._sessionplayer: Optional[ba.SessionPlayer] = None
        self._sessionteam: Optional[ReferenceType[ba.SessionTeam]] = None
        self.streak = 0
        self.associate_with_sessionplayer(sessionplayer) 
開發者ID:efroemling,項目名稱:ballistica,代碼行數:20,代碼來源:_stats.py

示例10: _verify_object_death

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def _verify_object_death(wref: ReferenceType) -> None:
    obj = wref()
    if obj is None:
        return

    try:
        name = type(obj).__name__
    except Exception:
        print(f'Note: unable to get type name for {obj}')
        name = 'object'

    print(f'{Clr.RED}Error: {name} not dying'
          f' when expected to: {Clr.BLD}{obj}{Clr.RST}')
    refs = list(gc.get_referrers(obj))
    print(f'{Clr.YLW}Active References:{Clr.RST}')
    i = 1
    for ref in refs:
        print(f'{Clr.YLW}  reference {i}:{Clr.BLU} {ref}{Clr.RST}')
        i += 1 
開發者ID:efroemling,項目名稱:ballistica,代碼行數:21,代碼來源:_general.py

示例11: __init__

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def __init__(self) -> None:
        size = config.val.tabs.focus_stack_size
        if size < 0:
            size = None
        self._stack = collections.deque(
            maxlen=size
        )  # type: typing.Deque[weakref.ReferenceType[QWidget]]
        # Items that have been removed from the primary stack.
        self._stack_deleted = [
        ]  # type: typing.List[weakref.ReferenceType[QWidget]]
        self._ignore_next = False
        self._keep_deleted_next = False 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:14,代碼來源:tabbedbrowser.py

示例12: _clear_dead_receivers

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def _clear_dead_receivers(self):
        # Note: caller is assumed to hold self.lock.
        if self._dead_receivers:
            self._dead_receivers = False
            new_receivers = []
            for r in self.receivers:
                if isinstance(r[1], weakref.ReferenceType) and r[1]() is None:
                    continue
                new_receivers.append(r)
            self.receivers = new_receivers 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:12,代碼來源:dispatcher.py

示例13: _live_receivers

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def _live_receivers(self, sender):
        """
        Filter sequence of receivers to get resolved, live receivers.

        This checks for weak references and resolves them, then returning only
        live receivers.
        """
        receivers = None
        if self.use_caching and not self._dead_receivers:
            receivers = self.sender_receivers_cache.get(sender)
            # We could end up here with NO_RECEIVERS even if we do check this case in
            # .send() prior to calling _live_receivers() due to concurrent .send() call.
            if receivers is NO_RECEIVERS:
                return []
        if receivers is None:
            with self.lock:
                self._clear_dead_receivers()
                senderkey = _make_id(sender)
                receivers = []
                for (receiverkey, r_senderkey), receiver in self.receivers:
                    if r_senderkey == NONE_ID or r_senderkey == senderkey:
                        receivers.append(receiver)
                if self.use_caching:
                    if not receivers:
                        self.sender_receivers_cache[sender] = NO_RECEIVERS
                    else:
                        # Note, we must cache the weakref versions.
                        self.sender_receivers_cache[sender] = receivers
        non_weak_receivers = []
        for receiver in receivers:
            if isinstance(receiver, weakref.ReferenceType):
                # Dereference the weak reference.
                receiver = receiver()
                if receiver is not None:
                    non_weak_receivers.append(receiver)
            else:
                non_weak_receivers.append(receiver)
        return non_weak_receivers 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:40,代碼來源:dispatcher.py

示例14: to_fmt

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
def to_fmt(self) -> fmt.indentable:
        res = None
        showlist = {
            'attr': {
                "res": fmt.sep('', ['.']),
                "inblock": fmt.sep('=', [self.value])
            },
            'indice': {
                "res": fmt.block('[', ']', []),
                "inblock": fmt.sep(': ', [repr(self.value)])
            },
            'key': {
                "res": fmt.block('{', '}', []),
                "inblock": fmt.sep(': ', [repr(self.value)])
            }
            }
        for k in sorted(showlist.keys()):
            v = showlist[k]
            if self.kind == CaptureContext.kind_of_node[k]:
                res = v["res"]
                inblock = v["inblock"]
                if self.node is not None:
                    if hasattr(self.node, 'to_fmt'):
                        inblock.lsdata.append(self.node.to_fmt())
                    elif type(self.node) is weakref.ReferenceType:
                        inblock.lsdata.append(repr(self.get()))
                res.lsdata.append(inblock)
        ######
        if self.kind == CaptureContext.kind_of_node['node']:
            res = fmt.sep('', [self.value])
            elmts = fmt.sep(',\n', [])
            for sk in sorted(CaptureContext.map_intern.values()):
                subelmt = None
                if hasattr(self, sk):
                    subelmt = getattr(self, sk)
                if subelmt is not None:
                    for sube in subelmt:
                        elmts.lsdata.append(sube.to_fmt())
            se = fmt.tab(fmt.block('(\n', '\n)', elmts))
            res.lsdata.append(se)
        return res 
開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:43,代碼來源:state.py

示例15: test_alive

# 需要導入模塊: import weakref [as 別名]
# 或者: from weakref import ReferenceType [as 別名]
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) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:10,代碼來源:test_weakref.py


注:本文中的weakref.ReferenceType方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。