本文整理汇总了Python中weakref.WeakValueDictionary类的典型用法代码示例。如果您正苦于以下问题:Python WeakValueDictionary类的具体用法?Python WeakValueDictionary怎么用?Python WeakValueDictionary使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WeakValueDictionary类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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()
示例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)
示例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()
示例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
示例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)
示例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)
示例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
示例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
示例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()
示例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
示例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
示例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
示例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()