Python weakref.ReferenceType() Examples

The following are 30 code examples of weakref.ReferenceType(). 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: utils.py    From django-rdf-io with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
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) 
Example #2
Source File: __init__.py    From nichtparasoup with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: dispatch.py    From FeelUOwn with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: key_processor.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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() 
Example #5
Source File: code.py    From pytest with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: _stats.py    From ballistica with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: scopetree.py    From edgedb with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: _general.py    From ballistica with MIT License 6 votes vote down vote up
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 
Example #9
Source File: gen_test.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
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()) 
Example #10
Source File: gen_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
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()) 
Example #11
Source File: core.py    From mars with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: signals.py    From anyMesh-Python with MIT License 5 votes vote down vote up
def _call_callback(self, callback, user_arg, user_args, emit_args):
        if user_args:
            args_to_pass = []
            for arg in user_args:
                if isinstance(arg, weakref.ReferenceType):
                    arg = arg()
                    if arg is None:
                        # If the weakref is None, the referenced object
                        # was cleaned up. We just skip the entire
                        # callback in this case. The weakref cleanup
                        # handler will have removed the callback when
                        # this happens, so no need to actually remove
                        # the callback here.
                        return False
                args_to_pass.append(arg)

            args_to_pass.extend(emit_args)
        else:
            # Optimization: Don't create a new list when there are
            # no user_args
            args_to_pass = emit_args

        # The deprecated user_arg argument was added to the end
        # instead of the beginning.
        if user_arg is not None:
            args_to_pass = itertools.chain(args_to_pass, (user_arg,))

        return bool(callback(*args_to_pass)) 
Example #13
Source File: dispatcher.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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 
Example #14
Source File: dispatcher.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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 
Example #15
Source File: mp.py    From mpwn with MIT License 5 votes vote down vote up
def __init__(self, codec: 'Codec'=None, manager: 'Manager'=None):
        if codec is None:
            codec = Codec()
        if manager is None:
            manager = global_manager
        self.codec = codec
        self.interacting = False
        self._data = None # type: Optional[bytes]
        self.sinks = [] # type: List[weakref.ReferenceType[notify_fn]]
        self.lock = threading.RLock()
        manager.register(self) 
Example #16
Source File: loops.py    From dependencies with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _check_loops_for(class_name, attribute_name, dependencies, origin, expression):

    try:
        attrname = next(expression)
    except StopIteration:
        return

    try:
        spec = dependencies[attrname]
    except KeyError:
        return

    if spec[0] is nested_injector:
        _check_loops_for(
            class_name,
            attribute_name,
            _nested_dependencies(dependencies, spec),
            origin,
            expression,
        )
    elif attrname == "__parent__":
        from weakref import ReferenceType

        if isinstance(spec[1], ReferenceType):
            resolved_parent = spec[1]().__dependencies__
        else:
            resolved_parent = spec[1]
        _check_loops_for(
            class_name, attribute_name, resolved_parent, origin, expression
        )
    elif spec is origin:
        message = "{0!r} is a circle link in the {1!r} injector"
        raise DependencyError(message.format(attribute_name, class_name))
    elif spec[0] is this:
        _check_loops_for(
            class_name, attribute_name, dependencies, origin, _filter_expression(spec)
        ) 
Example #17
Source File: dispatcher.py    From python2017 with MIT License 5 votes vote down vote up
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 
Example #18
Source File: dispatcher.py    From python2017 with MIT License 5 votes vote down vote up
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 
Example #19
Source File: interface.py    From pyatv with MIT License 5 votes vote down vote up
def __init__(self) -> None:
        """Initialize a new StateProducer instance."""
        self.__listener: Optional[weakref.ReferenceType[Any]] = None 
Example #20
Source File: udn_test.py    From spitfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_method_cycle_elimination(self):
        template = Foo()
        template.placeholder_cache = {}
        self.assertEqual(udn.resolve_placeholder('foo_method', template, None),
                         template.foo_method)
        self.assertIn('foo_method', template.placeholder_cache)
        self.assertIsInstance(template.placeholder_cache['foo_method'],
                              weakref.ReferenceType)
        self.assertEqual(udn.resolve_placeholder('foo_method', template, None),
                         template.foo_method) 
Example #21
Source File: Utility.py    From p2pool-n with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sw):
        '''Constructor, May be extended, do not override.
            sw -- soapWriter instance
        '''
        self.sw = None
        if type(sw) != weakref.ReferenceType and sw is not None:
            self.sw = weakref.ref(sw)
        else:
            self.sw = sw 
Example #22
Source File: _activity.py    From ballistica with MIT License 5 votes vote down vote up
def _check_activity_death(cls, activity_ref: ReferenceType[Activity],
                              counter: List[int]) -> None:
        """Sanity check to make sure an Activity was destroyed properly.

        Receives a weakref to a ba.Activity which should have torn itself
        down due to no longer being referenced anywhere. Will complain
        and/or print debugging info if the Activity still exists.
        """
        try:
            import gc
            import types
            activity = activity_ref()
            print('ERROR: Activity is not dying when expected:', activity,
                  '(warning ' + str(counter[0] + 1) + ')')
            print('This means something is still strong-referencing it.')
            counter[0] += 1

            # FIXME: Running the code below shows us references but winds up
            #  keeping the object alive; need to figure out why.
            #  For now we just print refs if the count gets to 3, and then we
            #  kill the app at 4 so it doesn't matter anyway.
            if counter[0] == 3:
                print('Activity references for', activity, ':')
                refs = list(gc.get_referrers(activity))
                i = 1
                for ref in refs:
                    if isinstance(ref, types.FrameType):
                        continue
                    print('  reference', i, ':', ref)
                    i += 1
            if counter[0] == 4:
                print('Killing app due to stuck activity... :-(')
                _ba.quit()

        except Exception:
            print_exception('Error on _check_activity_death/') 
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_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 #24
Source File: util.py    From ballistica with MIT License 5 votes vote down vote up
def empty_weakref(objtype: Type[T]) -> ReferenceType[T]:
    """Return an invalidated weak-reference for the specified type."""
    # At runtime, all weakrefs are the same; our type arg is just
    # for the static type checker.
    del objtype  # Unused.
    # Just create an object and let it die. Is there a cleaner way to do this?
    return weakref.ref(_EmptyObj())  # type: ignore 
Example #25
Source File: kingofthehill.py    From ballistica with MIT License 5 votes vote down vote up
def __init__(self, settings: dict):
        super().__init__(settings)
        shared = SharedObjects.get()
        self._scoreboard = Scoreboard()
        self._swipsound = ba.getsound('swip')
        self._tick_sound = ba.getsound('tick')
        self._countdownsounds = {
            10: ba.getsound('announceTen'),
            9: ba.getsound('announceNine'),
            8: ba.getsound('announceEight'),
            7: ba.getsound('announceSeven'),
            6: ba.getsound('announceSix'),
            5: ba.getsound('announceFive'),
            4: ba.getsound('announceFour'),
            3: ba.getsound('announceThree'),
            2: ba.getsound('announceTwo'),
            1: ba.getsound('announceOne')
        }
        self._flag_pos: Optional[Sequence[float]] = None
        self._flag_state: Optional[FlagState] = None
        self._flag: Optional[Flag] = None
        self._flag_light: Optional[ba.Node] = None
        self._scoring_team: Optional[ReferenceType[Team]] = None
        self._hold_time = int(settings['Hold Time'])
        self._time_limit = float(settings['Time Limit'])
        self._flag_region_material = ba.Material()
        self._flag_region_material.add_actions(
            conditions=('they_have_material', shared.player_material),
            actions=(
                ('modify_part_collision', 'collide', True),
                ('modify_part_collision', 'physical', False),
                ('call', 'at_connect',
                 ba.Call(self._handle_player_flag_region_collide, True)),
                ('call', 'at_disconnect',
                 ba.Call(self._handle_player_flag_region_collide, False)),
            ))

        # Base class overrides.
        self.default_music = ba.MusicType.SCARY 
Example #26
Source File: dispatcher.py    From python with Apache License 2.0 5 votes vote down vote up
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 
Example #27
Source File: mp.py    From mpwn with MIT License 5 votes vote down vote up
def __init__(self, _read: byte_src_fn):
        self._read = _read
        self.started = False
        self.done = False
        self.buf = ByteFIFO()
        self.lock = threading.RLock()
        self.start()
        self.sinks = [] # type: List[weakref.ReferenceType[byte_sink_fn]] 
Example #28
Source File: _gameresults.py    From ballistica with MIT License 5 votes vote down vote up
def __init__(self) -> None:
        self._game_set = False
        self._scores: Dict[int, Tuple[ReferenceType[ba.SessionTeam],
                                      Optional[int]]] = {}
        self._sessionteams: Optional[List[ReferenceType[
            ba.SessionTeam]]] = None
        self._playerinfos: Optional[List[ba.PlayerInfo]] = None
        self._lower_is_better: Optional[bool] = None
        self._score_label: Optional[str] = None
        self._none_is_winner: Optional[bool] = None
        self._scoretype: Optional[ba.ScoreType] = None 
Example #29
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 #30
Source File: _stats.py    From ballistica with MIT License 5 votes vote down vote up
def __init__(self) -> None:
        self._activity: Optional[ReferenceType[ba.Activity]] = None
        self._player_records: Dict[str, PlayerRecord] = {}
        self.orchestrahitsound1: Optional[ba.Sound] = None
        self.orchestrahitsound2: Optional[ba.Sound] = None
        self.orchestrahitsound3: Optional[ba.Sound] = None
        self.orchestrahitsound4: Optional[ba.Sound] = None