• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python weakref.WeakValueDictionary类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: __init__

    def __init__(self, name, parent=None, nolabel=False, **kwargs):
        """ Creates a maya menu or menu item

        :param name: Used to access a menu via its parent. Unless the nolabel flag is set to True, the name will also become the label of the menu.
        :type name: str
        :param parent: Optional - The parent menu. If None, this will create a toplevel menu. If parent menu is a Menu instance, this will create a menu item. Default is None.
        :type parent: Menu|None
        :param nolabel: Optional - If nolabel=True, the label flag for the maya command will not be overwritten by name
        :type nolabel: bool
        :param kwargs: all keyword arguments used for the cmds.menu/cmds.menuitem command
        :type kwargs: named arguments
        :returns: None
        :rtype: None
        :raises: errors.MenuExistsError
        """
        WeakValueDictionary.__init__(self)
        self.__menustring = None
        self.__parent = parent
        self.__name = name
        self.__kwargs = kwargs
        if not nolabel:
            self.__kwargs['label'] = name
        if parent is not None:
            if name in parent:
                raise errors.MenuExistsError("A menu with this name: %s and parent: %s exists already!" % (name, parent))
            cmds.setParent(parent.menustring(), menu=1)
            self.__kwargs['parent'] = parent.menustring()
            self.__menustring = cmds.menuItem(**self.__kwargs)
            parent[name] = self
        else:
            cmds.setParent('MayaWindow')
            self.__menustring = cmds.menu(**self.__kwargs)
开发者ID:JukeboxPipeline,项目名称:jukeboxmaya,代码行数:32,代码来源:menu.py


示例2: __init__

    def __init__(self, nodes, ways, min_lat, max_lat, min_lon, max_lon, *args,
                 node_color=(0, 0, 0), way_color="allrandom", bg_color="white",
                 enlargement=50000):
        """Export map data (nodes and ways) as a map like image.

        Params:
        nodes - The raw nodes as read by any OSM file reader
        ways - The raw ways as read by any OSM file reader
        min_lat - The southern border of the map
        max_lat - The northern border of the map
        min_lon - The western border of the map
        max_lon - The eastern border of the map
        node_color - The colour of the nodes in the image
        way_color - The colour of the ways in the image
        bg_color - The colour of the image background
        enlargement - Multiplication factor from map coordinate to pixel
                      coordinate. Determines image size.
        """
        super(MapImageExporter, self).__init__(min_lat, max_lat, min_lon, max_lon, bg_color, enlargement)
        self.logger = logging.getLogger('.'.join((__name__, type(self).__name__)))

        self.nodes = WeakValueDictionary(nodes)
        self.ways = WeakValueDictionary(ways)

        self.node_color = node_color
        self.way_color = way_color
开发者ID:XeryusTC,项目名称:mapbots,代码行数:26,代码来源:exportimage.py


示例3: Signal

class Signal(object):
    """
    A Signal is callable. When called, it calls all the callables in its slots.
    """
    def __init__(self):
        self._slots = WeakValueDictionary()

    def __call__(self, *args, **kargs):
        for key in self._slots:
            func, _ = key
            func(self._slots[key], *args, **kargs)

    def connect(self, slot):
        """
        Slots must call this to register a callback method.
        :param slot: callable
        """
        key = (slot.im_func, id(slot.im_self))
        self._slots[key] = slot.im_self

    def disconnect(self, slot):
        """
        They can also unregister their callbacks here.
        :param slot: callable
        """
        key = (slot.im_func, id(slot.im_self))
        if key in self._slots:
            self._slots.pop(key)

    def clear(self):
        """
        Clears all slots
        """
        self._slots.clear()
开发者ID:aalex,项目名称:txfirmata,代码行数:34,代码来源:sig.py


示例4: __init__

    def __init__(self, diskCacheFolder, name, logger):
        self._diskCacheFile = os.path.join(diskCacheFolder, '{}.json.bz2'.format(name))
        self._logger = logger
        # Initialize memory data cache
        self.__typeDataCache = {}
        self.__attributeDataCache = {}
        self.__effectDataCache = {}
        self.__modifierDataCache = {}
        self.__fingerprint = None
        # Initialize weakref object cache
        self.__typeObjCache = WeakValueDictionary()
        self.__attributeObjCache = WeakValueDictionary()
        self.__effectObjCache = WeakValueDictionary()
        self.__modifierObjCache = WeakValueDictionary()

        # If cache doesn't exist, silently finish initialization
        if not os.path.exists(self._diskCacheFile):
            return
        # Read JSON into local variable
        try:
            with bz2.BZ2File(self._diskCacheFile, 'r') as file:
                jsonData = file.read().decode('utf-8')
                data = json.loads(jsonData)
        # If file doesn't exist, JSON load errors occur, or
        # anything else bad happens, do not load anything
        # and leave values as initialized
        except:
            msg = 'error during reading cache'
            self._logger.error(msg, childName='cacheHandler')
        # Load data into data cache, if no errors occurred
        # during JSON reading/parsing
        else:
            self.__updateMemCache(data)
开发者ID:haart,项目名称:Eos,代码行数:33,代码来源:jsonCacheHandler.py


示例5: Signal

class Signal(object):
    def __init__(self):
        self.__slots = WeakValueDictionary()

    def __call__(self, *args, **kargs):
        for key in self.__slots:
            func, selfid = key
            if selfid is not None:
                func(self.__slots[key], *args, **kargs)
            else:
                func(*args, **kargs)


    def __get_key(self, slot):
        if hasattr(slot, 'im_func'):
            return (slot.im_func, id(slot.im_self))
        else:
            return (slot, None)

    def connect(self, slot):
        key = self.__get_key(slot)
        if hasattr(slot, 'im_func'):
            self.__slots[key] = slot.im_self
        else:
            self.__slots[key] = slot

    def disconnect(self, slot):
        key = self.__get_key(slot)
        if key in self.__slots:
            self.__slots.pop(key)

    def clear(self):
        self.__slots.clear()
开发者ID:eternicode,项目名称:SublimeTaskmaster,代码行数:33,代码来源:signal.py


示例6: __init__

class LRUCache:
	def __init__(self, max_size):
		self.LRU = [Node(time(), "none%s"%i) for i in range(max_size)]
		self.search = WeakValueDictionary()
		for i in self.LRU:
			self.search[i.name] = i
		
	def __setitem__(self, name, value):
		q = self.search.get(name, None)
		if q:
			q.data = value
			q.time = time()
		else:
			lru = self.LRU[0]
			self.search.pop(lru.name)
			lru.data = value
			lru.time = time()
			lru.name = name
			self.search[lru.name] = lru
		self.LRU.sort()
		
	def get(self, name, default=None):
		pos = None
		try:
			pos = self.search.__getitem__(name)
			pos.time = time()
			return pos.data
		except KeyError:
			if default is not None:
				return default
			else:
				raise
开发者ID:mizhal,项目名称:oldies-veronica-backend,代码行数:32,代码来源:CacheDict.py


示例7: Showcase

class Showcase(SessionSingleton):
    '''
    This class enables other classes to translate names previously registered
    to actual objects

    '''

    def __init__(self):
        self._objects = WeakValueDictionary()
        self._cases = WeakValueDictionary()

    def get(self, oid):
        '''
        :param str oid: the oid registered in the NameAuthority
        '''
        return self._objects.get(oid)

    def put(self, instance):
        '''
        :param INamed oid: the exposed object.
        '''
        self._objects[instance.oid] = instance

    def get_case(self, tag, default=None):
        '''
        :param str tag: The tag that the returned case should have
        '''
        return self._cases.get(tag, default)
开发者ID:crispamares,项目名称:indyva,代码行数:28,代码来源:showcase.py


示例8: __init__

 def __init__(self, maxsize, cullsize=2, peakmult=10, aggressive_gc=True,
              *args, **kwargs):
     self.cullsize = max(2, cullsize)
     self.maxsize = max(cullsize, maxsize)
     self.aggressive_gc = aggressive_gc
     self.peakmult = peakmult
     self.queue = deque()
     WeakValueDictionary.__init__(self, *args, **kwargs)
开发者ID:Veterini,项目名称:translate,代码行数:8,代码来源:lru.py


示例9: __init__

 def __init__(self):
     SendObject.__init__(self)
     WeakValueDictionary.__init__(self)
     def remove_wr(wr, selfref=ref(self)):
         self = selfref()
         if self is not None:
             del self[wr.key]
     self._remove = remove_wr
开发者ID:yrttyr,项目名称:Multiplayer-snake-game,代码行数:8,代码来源:objects.py


示例10: Signal

class Signal(object):
    
    def __init__(self,sender,max_connections=0, exc_catch=True):
        self._maxconn=max_connections
        self._sender=sender
        self._exc_catch=exc_catch
        self._slots = WeakValueDictionary()
        self._lock = threading.Lock()

    @property
    def connected(self):
        return len(self._slots)

    def connect(self, slot):
        if self._maxconn>0 and len(self._slots)>=self._maxconn:
            raise SignalError("Maximum number of connections was exceeded")
        assert callable(slot), "Signal slots must be callable."
        # Check for **kwargs
        try:
            argspec = inspect.getargspec(slot)
        except TypeError:
            try:
                argspec = inspect.getargspec(slot.__call__)
            except (TypeError, AttributeError):
                argspec = None
        if argspec:
            assert argspec[2] is not None,  \
                "Signal receivers must accept keyword arguments (**kwargs)."
        self._lock.acquire()
        try:
            key = (slot.im_func, id(slot.im_self))
            self._slots[key] = slot.im_self
        finally:
            self._lock.release()

    def disconnect(self, slot):
        self._lock.acquire()
        try:
            key = (slot.im_func, id(slot.im_self))
            if key in self._slots: self._slots.pop(key)
        finally:
            self._lock.release()

    def __call__(self,*args,**kwargs):
        assert not kwargs.has_key("sender"),  \
                "'sender' keyword argument is occupied"
        responses = []
        kwargs["sender"]=self._sender
        for key in self._slots:
            func, _ = key
            try:
                response=func(self._slots[key], *args, **kwargs)
                responses.append((func,response))
            except Exception, err:
                if self._exc_catch: self.exception("Slot {0} exception: {1}".format(str(func), err))
                else: raise Exception(traceback.format_exc())
        return responses    
开发者ID:pyfrid,项目名称:pyfrid-base,代码行数:57,代码来源:signal.py


示例11: Monitor

class Monitor(QObject):
	"""File monitor

	This monitor can be used to track single files
	"""

	def __init__(self, **kwargs):
		super(Monitor, self).__init__(**kwargs)

		self.watched = WeakValueDictionary()
		self.delMapper = QSignalMapper(self)
		self.delMapper.mapped[str].connect(self.unmonitorFile)

		self.watcher = MonitorWithRename(parent=self)
		self.watcher.fileChanged.connect(self._onFileChanged)

	def monitorFile(self, path):
		"""Monitor a file and return an object that tracks only `path`

		:rtype: SingleFileWatcher
		:return: an object tracking `path`, the same object is returned if the method is called
		         with the same path.
		"""
		path = os.path.abspath(path)

		self.watcher.addPath(path)

		proxy = self.watched.get(path)
		if not proxy:
			proxy = SingleFileWatcher(path)
			proxy.destroyed.connect(self.delMapper.map)
			self.delMapper.setMapping(proxy, path)
			self.watched[path] = proxy

		return proxy

	@Slot(str)
	def unmonitorFile(self, path):
		"""Stop monitoring a file

		Since there is only one :any:`SingleFileWatcher` object per path, all objects monitoring
		`path` will not receive notifications anymore.
		To let only one object stop monitoring the file, simply disconnect its `modified` signal.
		When the :any:`SingleFileWatcher` object returned by method :any:`monitorFile` is
		destroyed, the file is automatically un-monitored.
		"""
		path = os.path.abspath(path)

		self.watcher.removePath(path)
		self.watched.pop(path, None)

	@Slot(str)
	def _onFileChanged(self, path):
		proxy = self.watched.get(path)
		if proxy:
			proxy.modified.emit()
开发者ID:hydrargyrum,项目名称:eye,代码行数:56,代码来源:file_monitor.py


示例12: __init__

 def __init__(self, n=None):
     WeakValueDictionary.__init__(self)
     if n<1: # user doesn't want any Most Recent value queue
         self.__class__ = WeakValueDictionary # revert to regular WVD
         return
     if isinstance(n, int):
         self.n = n # size limit
     else:
         self.n = 50
     self.i = 0 # counter
     self._keepDict = {} # most recent queue
开发者ID:antonwang,项目名称:pygr,代码行数:11,代码来源:classutil.py


示例13: __init__

 def __init__(self, n=None):
     WeakValueDictionary.__init__(self)
     if n<1: # user doesn't want any Most Recent value queue
         self.__class__ = WeakValueDictionary # revert to regular WVD
         return
     if n is True: # assign default value
         self.n = 50
     else:
         self.n = int(n) # size limit
     self._head = self._tail = None
     self._keepDict = {} # most recent queue
开发者ID:BD2KGenomics,项目名称:brca-pipeline,代码行数:11,代码来源:classutil.py


示例14: __init__

 def __init__(self, callback):
     WeakValueDictionary.__init__ (self)
     # The superclass WeakValueDictionary assigns self._remove as a
     # callback to all the KeyedRef it creates. So we have to override
     # self._remove.
     # Note however that self._remobe is *not* a method because, as a
     # callback, it can be invoked after the dictionary is collected.
     # So it is a plain function, stored as an *instance* attribute.
     def remove(wr, _callback=callback, _original=self._remove):
         _original(wr)
         _callback(wr.key)
     self._remove = remove
开发者ID:oaubert,项目名称:advene2,代码行数:12,代码来源:reftools.py


示例15: __init__

    def __init__(self):
        atexit.register(self.cleanUp)
        self._polling_period = self.DefaultPollingPeriod
        self.polling_timers = {}
        self._polling_enabled = True
        self._attrs = WeakValueDictionary()
        self._devs = WeakValueDictionary()
        self._auths = WeakValueDictionary()

        import taurusmanager
        manager = taurusmanager.TaurusManager()
        self._serialization_mode = manager.getSerializationMode()
开发者ID:srgblnch,项目名称:taurus,代码行数:12,代码来源:taurusfactory.py


示例16: Subscriber

class Subscriber(Link, MutableMapping):
    def __init__(self, connect):
        super(Subscriber, self).__init__()
        self._dict = WeakValueDictionary()
        self._names = WeakKeyDictionary()
        self.connect = connect
        self.call()

    def subscribe(self, obj):
        self.__setitem__('_', obj)

    def unsubscribe(self, obj):
        wr = get_wrapper(obj)
        self._unsubscribe(wr)
        keys = wr._unsubscribe(self)
        keys.append(self._names[wr])
        for key in keys:
            self._dict.pop(key, None)

    def __setitem__(self, key, obj):
        wr = get_wrapper(obj)
        self._names[wr] = key
        self._subscribe(wr)
        keys = wr._subscribe(self)
        keys.append(key)
        assert not(key != '_' and key in self._dict), 'same name'
        for key in keys:
            self._dict[key] = wr.obj
        return obj

    def __getitem__(self, key):
        return self._dict[key]

    def __delitem__(self, key):
        self.unsubscribe(self[key])

    def __hash__(self):
        return Link.__hash__(self)

    def kill(self):
        for obj in set(self.links):
            self.unsubscribe(obj)
        super(Subscriber, self).kill()

    def call(self):
        pass

    def send(self, data):
        self.connect.send(data)

    def receive(self, data):
        receive(self, data)
开发者ID:yrttyr,项目名称:Multiplayer-snake-game,代码行数:52,代码来源:base.py


示例17: ObjectPool

class ObjectPool(object):
    """
        This class allows to fetch mvc model objects using their UUID.
        This requires to model to have a property called "uuid". All
        class inheriting from the base 'Model' class will have this.
        If implementing a custom model, the UUID property is responsible
        for the removal and addition to the pool when it changes values.
        Also see the UUIDPropIntel class for an example implementation.
        We can use this to store complex relations between objects where 
        references to each other can be replaced with the UUID.
        For a multi-threaded version see ThreadedObjectPool. 
    """

    def __init__(self, *args, **kwargs):
        object.__init__(self)
        self._objects = WeakValueDictionary()

    def add_or_get_object(self, obj):
        try:
            self.add_object(obj, force=False, silent=False)
            return obj
        except KeyError:
            return self.get_object(obj.uuid)

    def add_object(self, obj, force=False, fail_on_duplicate=False):
        if not obj.uuid in self._objects or force:
            self._objects[obj.uuid] = obj
        elif fail_on_duplicate:
            raise KeyError, "UUID %s is already taken by another object %s, cannot add object %s" % (obj.uuid, self._objects[obj.uuid], obj)
        else:
            # Just change the objects uuid, will break refs, but
            # it prevents issues with inherited properties etc.
            logger.warning("A duplicate UUID was passed to an ObjectPool for a %s object." % obj)
            obj.uuid = get_new_uuid()

    def change_all_uuids(self):
        # first get a copy off all uuids & objects:
        items = self._objects.items()
        for uuid, obj in items: # @UnusedVariable
            obj.uuid = get_new_uuid()

    def remove_object(self, obj):
        if obj.uuid in self._objects and self._objects[obj.uuid] == obj:
            del self._objects[obj.uuid]

    def get_object(self, uuid):
        obj = self._objects.get(uuid, None)
        return obj

    def clear(self):
        self._objects.clear()
开发者ID:claudioquaglia,项目名称:PyXRD,代码行数:51,代码来源:object_pool.py


示例18: MapImageExporter

class MapImageExporter(MapExporter):
    def __init__(self, nodes, ways, min_lat, max_lat, min_lon, max_lon, *args,
                 node_color=(0, 0, 0), way_color="allrandom", bg_color="white",
                 enlargement=50000):
        """Export map data (nodes and ways) as a map like image.

        Params:
        nodes - The raw nodes as read by any OSM file reader
        ways - The raw ways as read by any OSM file reader
        min_lat - The southern border of the map
        max_lat - The northern border of the map
        min_lon - The western border of the map
        max_lon - The eastern border of the map
        node_color - The colour of the nodes in the image
        way_color - The colour of the ways in the image
        bg_color - The colour of the image background
        enlargement - Multiplication factor from map coordinate to pixel
                      coordinate. Determines image size.
        """
        super(MapImageExporter, self).__init__(min_lat, max_lat, min_lon, max_lon, bg_color, enlargement)
        self.logger = logging.getLogger('.'.join((__name__, type(self).__name__)))

        self.nodes = WeakValueDictionary(nodes)
        self.ways = WeakValueDictionary(ways)

        self.node_color = node_color
        self.way_color = way_color

    def export(self, filename="export.png"):
        """Export the information to an image file

        Params:
        filename - The filename to export to, must have a valid image
                   extention. Default: export.png
        """
        self.logger.info('Exporting a map image to %s', filename)

        # Draw all ways
        self.logger.info('Drawing the ways')
        for id, way in self.ways.items():
            coords = [ ((self.nodes[node].lon - self.min_lon) * self.enlargement,
                    (self.nodes[node].lat - self.min_lat) * self.enlargement) for node in way.nodes]
            self.draw.line(coords, fill=self.way_color)

        # draw all nodes as points
        self.logger.info('Drawing the nodes')
        for id, node in self.nodes.items():
            self.draw.point( ((node.lon - self.min_lon) * self.enlargement,
                (node.lat - self.min_lat) * self.enlargement), fill=self.node_color)

        self._save_image(filename)
开发者ID:XeryusTC,项目名称:mapbots,代码行数:51,代码来源:exportimage.py


示例19: __init__

 def __init__(self, allow_none_id=False):
     """
     :param bool allow_none_id: Flag specifying if calling :meth:`add`
         with an entity that does not have an ID is allowed.
     """
     #
     self.__allow_none_id = allow_none_id
     # List of cached entities. This is the only place we are holding a
     # real reference to the entity.
     self.__entities = []
     # Dictionary mapping entity IDs to entities for fast lookup by ID.
     self.__id_map = WeakValueDictionary()
     # Dictionary mapping entity slugs to entities for fast lookup by slug.
     self.__slug_map = WeakValueDictionary()
开发者ID:BigData-Tools,项目名称:everest,代码行数:14,代码来源:cache.py


示例20: __init__

    def __init__(self, config):
        self._entries = dict()

        # indexed by (domain, user) tuple
        self._entry_by_domain = WeakValueDictionary()

        self._config = config
开发者ID:gmambro,项目名称:credential-helper,代码行数:7,代码来源:server.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python weapon.Weapon类代码示例发布时间:2022-05-26
下一篇:
Python weakref.WeakSet类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap