Python weakref.WeakKeyDictionary() Examples

The following are 30 code examples of weakref.WeakKeyDictionary(). 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: test_weakref.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_trashcan_16602(self):
        # Issue #16602: when a weakref's target was part of a long
        # deallocation chain, the trashcan mechanism could delay clearing
        # of the weakref and make the target object visible from outside
        # code even though its refcount had dropped to 0.  A crash ensued.
        class C(object):
            def __init__(self, parent):
                if not parent:
                    return
                wself = weakref.ref(self)
                def cb(wparent):
                    o = wself()
                self.wparent = weakref.ref(parent, cb)

        d = weakref.WeakKeyDictionary()
        root = c = C(None)
        for n in range(100):
            d[c] = c = C(c)
        del root
        gc.collect() 
Example #2
Source File: test_weakref.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_trashcan_16602(self):
        # Issue #16602: when a weakref's target was part of a long
        # deallocation chain, the trashcan mechanism could delay clearing
        # of the weakref and make the target object visible from outside
        # code even though its refcount had dropped to 0.  A crash ensued.
        class C(object):
            def __init__(self, parent):
                if not parent:
                    return
                wself = weakref.ref(self)
                def cb(wparent):
                    o = wself()
                self.wparent = weakref.ref(parent, cb)

        d = weakref.WeakKeyDictionary()
        root = c = C(None)
        for n in range(100):
            d[c] = c = C(c)
        del root
        gc.collect() 
Example #3
Source File: dispatcher.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, providing_args=None, use_caching=False):
        """
        Create a new signal.

        providing_args
            A list of the arguments this signal can pass along in a send() call.
        """
        self.receivers = []
        if providing_args is None:
            providing_args = []
        self.providing_args = set(providing_args)
        self.lock = threading.Lock()
        self.use_caching = use_caching
        # For convenience we create empty caches even if they are not used.
        # A note about caching: if use_caching is defined, then for each
        # distinct sender we cache the receivers that sender has in
        # 'sender_receivers_cache'. The cache is cleaned when .connect() or
        # .disconnect() is called and populated on send().
        self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
        self._dead_receivers = False 
Example #4
Source File: dispatcher.py    From bioforum with MIT License 6 votes vote down vote up
def __init__(self, providing_args=None, use_caching=False):
        """
        Create a new signal.

        providing_args
            A list of the arguments this signal can pass along in a send() call.
        """
        self.receivers = []
        if providing_args is None:
            providing_args = []
        self.providing_args = set(providing_args)
        self.lock = threading.Lock()
        self.use_caching = use_caching
        # For convenience we create empty caches even if they are not used.
        # A note about caching: if use_caching is defined, then for each
        # distinct sender we cache the receivers that sender has in
        # 'sender_receivers_cache'. The cache is cleaned when .connect() or
        # .disconnect() is called and populated on send().
        self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
        self._dead_receivers = False 
Example #5
Source File: signals.py    From backend with GNU General Public License v2.0 6 votes vote down vote up
def connect(self, slot, sender=None):
    if sender:
      if inspect.ismethod(slot):
        if sender not in self._methods_subs:
          self._methods_subs[sender] = weakref.WeakKeyDictionary()

        if slot.__self__ not in self._methods_subs[sender]:
          self._methods_subs[sender][slot.__self__] = set()

        self._methods_subs[sender][slot.__self__].add(slot.__func__)
      else:
        if sender not in self._functions_subs:
          self._functions_subs[sender] = weakref.WeakSet()
        self._functions_subs[sender].add(slot)
    else:
      if inspect.ismethod(slot):
        if slot.__self__ not in self._methods:
          self._methods[slot.__self__] = set()
        self._methods[slot.__self__].add(slot.__func__)
      else:
        self._functions.add(slot) 
Example #6
Source File: _compat.py    From pcocc with GNU General Public License v3.0 6 votes vote down vote up
def _make_cached_stream_func(src_func, wrapper_func):
    cache = WeakKeyDictionary()
    def func():
        stream = src_func()
        try:
            rv = cache.get(stream)
        except Exception:
            rv = None
        if rv is not None:
            return rv
        rv = wrapper_func()
        try:
            cache[stream] = rv
        except Exception:
            pass
        return rv
    return func 
Example #7
Source File: test_weakref.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_trashcan_16602(self):
        # Issue #16602: when a weakref's target was part of a long
        # deallocation chain, the trashcan mechanism could delay clearing
        # of the weakref and make the target object visible from outside
        # code even though its refcount had dropped to 0.  A crash ensued.
        class C(object):
            def __init__(self, parent):
                if not parent:
                    return
                wself = weakref.ref(self)
                def cb(wparent):
                    o = wself()
                self.wparent = weakref.ref(parent, cb)

        d = weakref.WeakKeyDictionary()
        root = c = C(None)
        for n in range(100):
            d[c] = c = C(c)
        del root
        gc.collect() 
Example #8
Source File: GraphicsScene.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def __init__(self, clickRadius=2, moveDistance=5, parent=None):
        QtGui.QGraphicsScene.__init__(self, parent)
        self.setClickRadius(clickRadius)
        self.setMoveDistance(moveDistance)
        self.exportDirectory = None
        
        self.clickEvents = []
        self.dragButtons = []
        self.mouseGrabber = None
        self.dragItem = None
        self.lastDrag = None
        self.hoverItems = weakref.WeakKeyDictionary()
        self.lastHoverEvent = None
        self.minDragTime = 0.5  # drags shorter than 0.5 sec are interpreted as clicks
        
        self.contextMenu = [QtGui.QAction("Export...", self)]
        self.contextMenu[0].triggered.connect(self.showExportDialog)
        
        self.exportDialog = None 
Example #9
Source File: utils.py    From openpyxl-templates with MIT License 6 votes vote down vote up
def __init__(self, name, value=None, expected_type=None, expected_types=None, allow_none=False):
        self.name = name
        self._values = WeakKeyDictionary()

        if expected_types is not None:
            self.expected_types = expected_types
        else:
            self.expected_types = []

        if expected_type is not None:
            self.expected_types.append(expected_type)
        self.allow_none = allow_none
        self.__doc__ = "Values must be of type {0}".format(self.expected_types)

        if value is not None:
            self.validate(value)
            self.default_value = value 
Example #10
Source File: _compat.py    From jbox with MIT License 6 votes vote down vote up
def _make_cached_stream_func(src_func, wrapper_func):
    cache = WeakKeyDictionary()
    def func():
        stream = src_func()
        try:
            rv = cache.get(stream)
        except Exception:
            rv = None
        if rv is not None:
            return rv
        rv = wrapper_func()
        try:
            cache[stream] = rv
        except Exception:
            pass
        return rv
    return func 
Example #11
Source File: test_copy.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_deepcopy_weakkeydict(self):
        class C(object):
            def __init__(self, i):
                self.i = i
        a, b, c, d = [C(i) for i in xrange(4)]
        u = weakref.WeakKeyDictionary()
        u[a] = b
        u[c] = d
        # Keys aren't copied, values are
        v = copy.deepcopy(u)
        self.assertNotEqual(v, u)
        self.assertEqual(len(v), 2)
        self.assertFalse(v[a] is b)
        self.assertFalse(v[c] is d)
        self.assertEqual(v[a].i, b.i)
        self.assertEqual(v[c].i, d.i)
        del c
        self.assertEqual(len(v), 1) 
Example #12
Source File: dispatcher.py    From torngas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, providing_args=None, use_caching=False):
        """
        Create a new signal.

        providing_args
            A list of the arguments this signal can pass along in a send() call.
        """
        self.receivers = []
        if providing_args is None:
            providing_args = []
        self.providing_args = set(providing_args)
        self.lock = threading.Lock()
        self.use_caching = use_caching
        # For convenience we create empty caches even if they are not used.
        # A note about caching: if use_caching is defined, then for each
        # distinct sender we cache the receivers that sender has in
        # 'sender_receivers_cache'. The cache is cleaned when .connect() or
        # .disconnect() is called and populated on send().
        self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {}
        self._dead_receivers = False 
Example #13
Source File: _compat.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def _make_cached_stream_func(src_func, wrapper_func):
    cache = WeakKeyDictionary()
    def func():
        stream = src_func()
        try:
            rv = cache.get(stream)
        except Exception:
            rv = None
        if rv is not None:
            return rv
        rv = wrapper_func()
        try:
            cache[stream] = rv
        except Exception:
            pass
        return rv
    return func 
Example #14
Source File: data_runner.py    From hart with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, queue, enqueue_ops):
        """Create a PyQueueRunner.

        When you later call the `create_threads()` method, the `QueueRunner` will
        create one thread for each op in `enqueue_ops`.  Each thread will run its
        enqueue op in parallel with the other threads.  The enqueue ops do not have
        to all be the same op, but it is expected that they all enqueue tensors in
        `queue`.

        Args:
          qnqueue_handler: a python function that transforms
          queue: A `Queue`.
          enqueue_ops: List of enqueue ops to run in threads later.
        """
        self._queue = queue
        self._enqueue_ops = enqueue_ops

        self._lock = threading.Lock()
        # A map from a session object to the number of outstanding queue runner
        # threads for that session.
        self._runs_per_session = weakref.WeakKeyDictionary() 
Example #15
Source File: cbook.py    From Computable with MIT License 6 votes vote down vote up
def connect(self, s, func):
        """
        register *func* to be called when a signal *s* is generated
        func will be called
        """
        self._func_cid_map.setdefault(s, WeakKeyDictionary())
        if func in self._func_cid_map[s]:
            return self._func_cid_map[s][func]

        self._cid += 1
        cid = self._cid
        self._func_cid_map[s][func] = cid
        self.callbacks.setdefault(s, dict())
        proxy = _BoundMethodProxy(func)
        self.callbacks[s][cid] = proxy
        return cid 
Example #16
Source File: _compat.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _make_cached_stream_func(src_func, wrapper_func):
    cache = WeakKeyDictionary()
    def func():
        stream = src_func()
        try:
            rv = cache.get(stream)
        except Exception:
            rv = None
        if rv is not None:
            return rv
        rv = wrapper_func()
        try:
            stream = src_func()  # In case wrapper_func() modified the stream
            cache[stream] = rv
        except Exception:
            pass
        return rv
    return func 
Example #17
Source File: test_copy.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_deepcopy_weakkeydict(self):
        class C(object):
            def __init__(self, i):
                self.i = i
        a, b, c, d = [C(i) for i in xrange(4)]
        u = weakref.WeakKeyDictionary()
        u[a] = b
        u[c] = d
        # Keys aren't copied, values are
        v = copy.deepcopy(u)
        self.assertNotEqual(v, u)
        self.assertEqual(len(v), 2)
        self.assertFalse(v[a] is b)
        self.assertFalse(v[c] is d)
        self.assertEqual(v[a].i, b.i)
        self.assertEqual(v[c].i, d.i)
        del c
        self.assertEqual(len(v), 1) 
Example #18
Source File: __init__.py    From BinderFilter with MIT License 5 votes vote down vote up
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
        threading.Thread.__init__(self, group, target, name, args, kwargs)
        self._pid = None
        self._children = weakref.WeakKeyDictionary()
        self._start_called = False
        self._parent = current_process() 
Example #19
Source File: httpclient.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def _async_clients(cls):
        attr_name = '_async_client_dict_' + cls.__name__
        if not hasattr(cls, attr_name):
            setattr(cls, attr_name, weakref.WeakKeyDictionary())
        return getattr(cls, attr_name) 
Example #20
Source File: backend_pgf.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self):
        self.weak_key_dict = weakref.WeakKeyDictionary() 
Example #21
Source File: memorize.py    From pylivetrader with Apache License 2.0 5 votes vote down vote up
def __init__(self, get):
        self._get = get
        self._cache = WeakKeyDictionary() 
Example #22
Source File: test_weakref.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_weak_keyed_delitem(self):
        d = weakref.WeakKeyDictionary()
        o1 = Object('1')
        o2 = Object('2')
        d[o1] = 'something'
        d[o2] = 'something'
        self.assertEqual(len(d), 2)
        del d[o1]
        self.assertEqual(len(d), 1)
        self.assertEqual(d.keys(), [o2]) 
Example #23
Source File: test_weakref.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_weak_keyed_dict_setdefault(self):
        self.check_setdefault(weakref.WeakKeyDictionary,
                              C(), "value 1", "value 2") 
Example #24
Source File: test_break.py    From BinderFilter with MIT License 5 votes vote down vote up
def tearDown(self):
        signal.signal(signal.SIGINT, self._default_handler)
        unittest.signals._results = weakref.WeakKeyDictionary()
        unittest.signals._interrupt_handler = None 
Example #25
Source File: test_copy.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_copy_weakkeydict(self):
        self._check_copy_weakdict(weakref.WeakKeyDictionary) 
Example #26
Source File: cparser.py    From bioforum with MIT License 5 votes vote down vote up
def __init__(self):
        self._declarations = {}
        self._included_declarations = set()
        self._anonymous_counter = 0
        self._structnode2type = weakref.WeakKeyDictionary()
        self._options = {}
        self._int_constants = {}
        self._recomplete = []
        self._uses_new_feature = None 
Example #27
Source File: async_pubsub.py    From monaco with MIT License 5 votes vote down vote up
def __init__(self, connection_pool, threadpool_size=5, **kwargs):
        super(AsyncPubSub, self).__init__(connection_pool, **kwargs)
        if not hasattr(threading.current_thread(), "_children"):
            threading.current_thread()._children = WeakKeyDictionary()
        self.threadpool = ThreadPool(threadpool_size)
        self.running = [] 
Example #28
Source File: __init__.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
        threading.Thread.__init__(self, group, target, name, args, kwargs)
        self._pid = None
        self._children = weakref.WeakKeyDictionary()
        self._start_called = False
        self._parent = current_process() 
Example #29
Source File: signals.py    From backend with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
    self._functions = weakref.WeakSet()
    self._methods = weakref.WeakKeyDictionary()

    self._methods_subs = {}
    self._functions_subs = {}

    if not Signal.signal_error:
      Signal.signal_error = 1
      Signal.signal_error = Signal() 
Example #30
Source File: httpclient.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def _async_clients(cls) -> Dict[IOLoop, "AsyncHTTPClient"]:
        attr_name = "_async_client_dict_" + cls.__name__
        if not hasattr(cls, attr_name):
            setattr(cls, attr_name, weakref.WeakKeyDictionary())
        return getattr(cls, attr_name)