Python weakref.WeakValueDictionary() Examples

The following are 30 code examples of weakref.WeakValueDictionary(). 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: properties.py    From pyaaf2 with MIT License 6 votes vote down vote up
def insert(self, index, value):
        assert self.ref_classdef.isinstance(value.classdef)

        self.references.insert(index, self.next_free_key)

        objects = {}
        objects[index] = value
        # increment all cached object with > indices +1
        for key, value in self.objects.items():
            if key >= index:
                objects[key+1] = value
            else:
                objects[key] = value

        self.next_free_key += 1
        if self.attached:
            self.objects = weakref.WeakValueDictionary(objects)
        else:
            self.objects = objects
        self.attach() 
Example #2
Source File: properties.py    From pyaaf2 with MIT License 6 votes vote down vote up
def __init__(self, parent, pid, format, version=PROPERTY_VERSION):
        super(StrongRefSetProperty, self).__init__(parent, pid, format, version)

        self.references = {}

        self.index_name = None

        self.next_free_key = 0
        self.last_free_key = 0xFFFFFFFF

        # Pid of the referenced objects unique_key
        self.key_pid = None
        self.key_size = None

        if self.attached:
            self.objects = weakref.WeakValueDictionary()
        else:
            self.objects = {} 
Example #3
Source File: test_copy.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_deepcopy_weakvaluedict(self):
        class C(object):
            def __init__(self, i):
                self.i = i
        a, b, c, d = [C(i) for i in xrange(4)]
        u = weakref.WeakValueDictionary()
        u[a] = b
        u[c] = d
        # Keys are copied, values aren't
        v = copy.deepcopy(u)
        self.assertNotEqual(v, u)
        self.assertEqual(len(v), 2)
        (x, y), (z, t) = sorted(v.items(), key=lambda pair: pair[0].i)
        self.assertFalse(x is a)
        self.assertEqual(x.i, a.i)
        self.assertTrue(y is b)
        self.assertFalse(z is c)
        self.assertEqual(z.i, c.i)
        self.assertTrue(t is d)
        del x, y, z, t
        del d
        self.assertEqual(len(v), 1) 
Example #4
Source File: transforms.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __init__(self, shorthand_name=None):
        """
        Creates a new :class:`TransformNode`.

        **shorthand_name** - a string representing the "name" of this
                             transform. The name carries no significance
                             other than to improve the readability of
                             ``str(transform)`` when DEBUG=True.
        """
        # Parents are stored in a WeakValueDictionary, so that if the
        # parents are deleted, references from the children won't keep
        # them alive.
        self._parents = WeakValueDictionary()

        # TransformNodes start out as invalid until their values are
        # computed for the first time.
        self._invalid = 1
        self._shorthand_name = shorthand_name or '' 
Example #5
Source File: state.py    From discord.py with MIT License 6 votes vote down vote up
def clear(self):
        self.user = None
        self._users = weakref.WeakValueDictionary()
        self._emojis = {}
        self._calls = {}
        self._guilds = {}
        self._voice_clients = {}

        # LRU of max size 128
        self._private_channels = OrderedDict()
        # extra dict to look up private channels by user id
        self._private_channels_by_user = {}
        self._messages = self.max_messages and deque(maxlen=self.max_messages)

        # In cases of large deallocations the GC should be called explicitly
        # To free the memory more immediately, especially true when it comes
        # to reconnect loops which cause mass allocations and deallocations.
        gc.collect() 
Example #6
Source File: test_weakref.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_weak_valued_dict_update(self):
        self.check_update(weakref.WeakValueDictionary,
                          {1: C(), 'a': C(), C(): C()})
        # errors
        self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
        d = weakref.WeakValueDictionary()
        self.assertRaises(TypeError, d.update, {}, {})
        self.assertRaises(TypeError, d.update, (), ())
        self.assertEqual(list(d.keys()), [])
        # special keyword arguments
        o = Object(3)
        for kw in 'self', 'dict', 'other', 'iterable':
            d = weakref.WeakValueDictionary()
            d.update(**{kw: o})
            self.assertEqual(list(d.keys()), [kw])
            self.assertEqual(d[kw], o) 
Example #7
Source File: mouseEvents.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def __init__(self, moveEvent, acceptable):
        self.enter = False
        self.acceptable = acceptable
        self.exit = False
        self.__clickItems = weakref.WeakValueDictionary()
        self.__dragItems = weakref.WeakValueDictionary()
        self.currentItem = None
        if moveEvent is not None:
            self._scenePos = moveEvent.scenePos()
            self._screenPos = moveEvent.screenPos()
            self._lastScenePos = moveEvent.lastScenePos()
            self._lastScreenPos = moveEvent.lastScreenPos()
            self._buttons = moveEvent.buttons()
            self._modifiers = moveEvent.modifiers()
        else:
            self.exit = True 
Example #8
Source File: model.py    From bioforum with MIT License 6 votes vote down vote up
def global_cache(srctype, ffi, funcname, *args, **kwds):
    key = kwds.pop('key', (funcname, args))
    assert not kwds
    try:
        return ffi._typecache[key]
    except KeyError:
        pass
    try:
        res = getattr(ffi._backend, funcname)(*args)
    except NotImplementedError as e:
        raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))
    # note that setdefault() on WeakValueDictionary is not atomic
    # and contains a rare bug (http://bugs.python.org/issue19542);
    # we have to use a lock and do it ourselves
    cache = ffi._typecache
    with global_lock:
        res1 = cache.get(key)
        if res1 is None:
            cache[key] = res
            return res
        else:
            return res1 
Example #9
Source File: transforms.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, shorthand_name=None):
        """
        Creates a new :class:`TransformNode`.

        **shorthand_name** - a string representing the "name" of this
                             transform. The name carries no significance
                             other than to improve the readability of
                             ``str(transform)`` when DEBUG=True.
        """
        # Parents are stored in a WeakValueDictionary, so that if the
        # parents are deleted, references from the children won't keep
        # them alive.
        self._parents = WeakValueDictionary()

        # TransformNodes start out as invalid until their values are
        # computed for the first time.
        self._invalid = 1
        self._shorthand_name = shorthand_name or '' 
Example #10
Source File: test_weakref.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_weak_values(self):
        #
        #  This exercises d.copy(), d.items(), d[], del d[], len(d).
        #
        dict, objects = self.make_weak_valued_dict()
        for o in objects:
            self.assertEqual(weakref.getweakrefcount(o), 1,
                         "wrong number of weak references to %r!" % o)
            self.assertIs(o, dict[o.arg],
                         "wrong object returned by weak dict!")
        items1 = dict.items()
        items2 = dict.copy().items()
        items1.sort()
        items2.sort()
        self.assertEqual(items1, items2,
                     "cloning of weak-valued dictionary did not work!")
        del items1, items2
        self.assertEqual(len(dict), self.COUNT)
        del objects[0]
        self.assertEqual(len(dict), (self.COUNT - 1),
                     "deleting object did not cause dictionary update")
        del objects, o
        self.assertEqual(len(dict), 0,
                     "deleting the values did not clear the dictionary")
        # regression on SF bug #447152:
        dict = weakref.WeakValueDictionary()
        self.assertRaises(KeyError, dict.__getitem__, 1)
        dict[2] = C()
        self.assertRaises(KeyError, dict.__getitem__, 2) 
Example #11
Source File: model.py    From oss-ftp with MIT License 5 votes vote down vote up
def global_cache(srctype, ffi, funcname, *args, **kwds):
    key = kwds.pop('key', (funcname, args))
    assert not kwds
    try:
        return ffi._backend.__typecache[key]
    except KeyError:
        pass
    except AttributeError:
        # initialize the __typecache attribute, either at the module level
        # if ffi._backend is a module, or at the class level if ffi._backend
        # is some instance.
        if isinstance(ffi._backend, types.ModuleType):
            ffi._backend.__typecache = weakref.WeakValueDictionary()
        else:
            type(ffi._backend).__typecache = weakref.WeakValueDictionary()
    try:
        res = getattr(ffi._backend, funcname)(*args)
    except NotImplementedError as e:
        raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))
    # note that setdefault() on WeakValueDictionary is not atomic
    # and contains a rare bug (http://bugs.python.org/issue19542);
    # we have to use a lock and do it ourselves
    cache = ffi._backend.__typecache
    with global_lock:
        res1 = cache.get(key)
        if res1 is None:
            cache[key] = res
            return res
        else:
            return res1 
Example #12
Source File: test_weakref.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_weak_valued_dict_popitem(self):
        self.check_popitem(weakref.WeakValueDictionary,
                           "key1", C(), "key2", C()) 
Example #13
Source File: test_weakref.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_weak_valued_dict_setdefault(self):
        self.check_setdefault(weakref.WeakValueDictionary,
                              "key", C(), C()) 
Example #14
Source File: user.py    From steam with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)

        self._user_cache = WeakValueDictionary()

        self.on(self.EVENT_DISCONNECTED, self.__handle_disconnect)
        self.on(self.EVENT_LOGGED_ON, self.__handle_set_persona)
        self.on(EMsg.ClientPersonaState, self.__handle_persona_state)
        self.on(EMsg.ClientFriendMsgIncoming, self.__handle_message_incoming)
        self.on("FriendMessagesClient.IncomingMessage#1", self.__handle_message_incoming2) 
Example #15
Source File: bruker_tims.py    From ms_deisotope with Apache License 2.0 5 votes vote down vote up
def __init__(self, analysis_directory, use_recalibrated_state=False, scan_merging_parameters=None):
        if sys.version_info.major == 2:
            if not isinstance(analysis_directory, unicode):
                raise ValueError("analysis_directory must be a Unicode string.")
        if sys.version_info.major == 3:
            if not isinstance(analysis_directory, str):
                raise ValueError("analysis_directory must be a string.")
        if scan_merging_parameters is None:
            scan_merging_parameters = default_scan_merging_parameters.copy()
        else:
            for key, value in default_scan_merging_parameters.items():
                scan_merging_parameters.setdefault(key, value)

        self.dll = load_library()

        self.handle = self.dll.tims_open(
            analysis_directory.encode('utf-8'), 1 if use_recalibrated_state else 0)
        if self.handle == 0:
            throw_tims_error(self.dll)

        self.conn = sqlite3.connect(os.path.join(analysis_directory, "analysis.tdf"))
        self.conn.row_factory = sqlite3.Row

        self.initial_frame_buffer_size = 128 # may grow in readScans()
        self._read_metadata()
        self._frame_cache = WeakValueDictionary()
        self._scan_merging_parameters = scan_merging_parameters 
Example #16
Source File: _factories.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__(cls, *args, **kwargs):
        cls.__instances = weakref.WeakValueDictionary()
        cls.__strong_cache = OrderedDict()
        cls.__strong_cache_size = 8 
Example #17
Source File: _factories.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __init__(cls, *args, **kwargs):
        cls.__instances = weakref.WeakValueDictionary()
        cls.__strong_cache = OrderedDict()
        cls.__strong_cache_size = 8 
Example #18
Source File: transforms.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def __setstate__(self, data_dict):
        self.__dict__ = data_dict
        # turn the normal dictionary back into a WeakValueDictionary
        self._parents = WeakValueDictionary(self._parents) 
Example #19
Source File: model.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def global_cache(srctype, ffi, funcname, *args, **kwds):
    key = kwds.pop('key', (funcname, args))
    assert not kwds
    try:
        return ffi._backend.__typecache[key]
    except KeyError:
        pass
    except AttributeError:
        # initialize the __typecache attribute, either at the module level
        # if ffi._backend is a module, or at the class level if ffi._backend
        # is some instance.
        if isinstance(ffi._backend, types.ModuleType):
            ffi._backend.__typecache = weakref.WeakValueDictionary()
        else:
            type(ffi._backend).__typecache = weakref.WeakValueDictionary()
    try:
        res = getattr(ffi._backend, funcname)(*args)
    except NotImplementedError as e:
        raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))
    # note that setdefault() on WeakValueDictionary is not atomic
    # and contains a rare bug (http://bugs.python.org/issue19542);
    # we have to use a lock and do it ourselves
    cache = ffi._backend.__typecache
    with global_lock:
        res1 = cache.get(key)
        if res1 is None:
            cache[key] = res
            return res
        else:
            return res1 
Example #20
Source File: test_weakref.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_weak_valued_len_race(self):
        self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k)) 
Example #21
Source File: test_weakref.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_weak_valued_len_cycles(self):
        self.check_len_cycles(weakref.WeakValueDictionary, lambda n, k: (n, k)) 
Example #22
Source File: test_copy.py    From oss-ftp with MIT License 5 votes vote down vote up
def test_copy_weakvaluedict(self):
        self._check_copy_weakdict(weakref.WeakValueDictionary) 
Example #23
Source File: symtable.py    From oss-ftp with MIT License 5 votes vote down vote up
def __init__(self):
        self.__memo = weakref.WeakValueDictionary() 
Example #24
Source File: pool.py    From google-cloud-python-expenses-demo with Apache License 2.0 5 votes vote down vote up
def __init__(self, size=4, timeout=1<<31, logger=logger):

        self._lock = threading.RLock()
        self._logger = logger
        self._size = size
        self._timeout = timeout  # seconds

        # A weak mapping, id(resource) -> resource.
        self._all = weakref.WeakValueDictionary()

        # A stack of resources available to check out.
        self._available = [] 
Example #25
Source File: transforms.py    From Computable with MIT License 5 votes vote down vote up
def __setstate__(self, data_dict):
        self.__dict__ = data_dict
        # turn the normal dictionary back into a WeakValueDictionary
        self._parents = WeakValueDictionary(self._parents) 
Example #26
Source File: symtable.py    From Computable with MIT License 5 votes vote down vote up
def __init__(self):
        self.__memo = weakref.WeakValueDictionary() 
Example #27
Source File: test_copy.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_copy_weakvaluedict(self):
        self._check_copy_weakdict(weakref.WeakValueDictionary) 
Example #28
Source File: test_weakref.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_weak_valued_delitem(self):
        d = weakref.WeakValueDictionary()
        o1 = Object('1')
        o2 = Object('2')
        d['something'] = o1
        d['something else'] = o2
        self.assertTrue(len(d) == 2)
        del d['something']
        self.assertTrue(len(d) == 1)
        self.assertTrue(d.items() == [('something else', o2)]) 
Example #29
Source File: test_weakref.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_weak_valued_dict_update(self):
        self.check_update(weakref.WeakValueDictionary,
                          {1: C(), 'a': C(), C(): C()}) 
Example #30
Source File: test_weakref.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_weak_valued_dict_setdefault(self):
        self.check_setdefault(weakref.WeakValueDictionary,
                              "key", C(), C())