本文整理汇总了Python中weakref.WeakValueDictionary.pop方法的典型用法代码示例。如果您正苦于以下问题:Python WeakValueDictionary.pop方法的具体用法?Python WeakValueDictionary.pop怎么用?Python WeakValueDictionary.pop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weakref.WeakValueDictionary
的用法示例。
在下文中一共展示了WeakValueDictionary.pop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
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
示例2: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
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()
示例3: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
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()
示例4: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
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
示例5: Monitor
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
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()
示例6: Subscriber
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
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)
示例7: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class Signal(object):
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):
key = (slot.__func__, id(slot.__self__))
self.__slots[key] = slot.__self__
def disconnect(self, slot):
key = (slot.__func__, id(slot.__self__))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
示例8: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class Signal(object):
"""A lightweight Signal class when Qt is not installed."""
def __init__(self, *types):
"""Create the Signal object. The type signatures are ignored."""
self.__slots = WeakValueDictionary()
def emit(self, *args, **kwargs):
"""Emit the signal, call all slots that are connected."""
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kwargs)
def connect(self, slot):
"""Connect this signal to a slot."""
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
"""Disconnect this signal from a slot."""
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
示例9: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class Signal(object):
"""
Signal slot object, used for handling events passed to the objects in the gui.
"""
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):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
def disconnect(self, slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
def clear(self):
self.__slots.clear()
示例10: Signal
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class Signal(object):
def __init__(self):
self.__slots = WeakValueDictionary()
# For keeping references to _FuncHost objects.
self.__funchosts = {}
def __call__(self, *args, **kargs):
for key in self.__slots:
func, _ = key
func(self.__slots[key], *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
self.__slots[key] = slot.im_self
else:
host = _FuncHost(slot)
self.connect(host.meth)
# We stick a copy in here just to keep the instance alive.
self.__funchosts[slot] = host
def disconnect(self, slot):
if inspect.ismethod(slot):
key = (slot.im_func, id(slot.im_self))
if key in self.__slots:
self.__slots.pop(key)
else:
if slot in self.__funchosts:
self.disconnect(self.__funchosts[slot].meth)
self.__funchosts.pop(slot)
def clear(self):
self.__slots.clear()
self.__funchosts.clear()
示例11: Layout
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class Layout(object):
def __init__(self):
self.solver = Solver()
self.introns = WeakValueDictionary()
def update(self, element):
self.solver.autosolve = False
for constraint in element.constraints[1]:
self.solver.remove_constraint(constraint)
for constraint in element.constraints[0]:
self.solver.add_constraint(constraint)
element.constraints = [], element.constraints[0]
self.solver.autosolve = True
def add_intron(self, source, intron):
self.introns[source] = intron
def pop_intron(self, source):
return self.introns.pop(source)
def get_intron(self, source, otherwise=None):
return self.introns.get(source, otherwise)
示例12: TrollReactor
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class TrollReactor(CBDictInterface):
"""Base class for Omegle API.
"""
def __init__(self, transmog=Transmogrifier(), listen=InteractiveViewport(),
n=2, refresh=2., debug=0):
# Independent setup
super(TrollReactor, self).__init__()
self.debug = debug
self.listeners = WeakValueDictionary()
# Argument assignment
self.eventQueue = deque()
self.connectTransmogrifier(transmog)
self.addListeners(listen)
self._n = n
self.refresh = refresh
self._allConnected = False
self.reconnectWait = 2.
self.idleTime = None
self.initializeStrangers() # Now we wait to receive idSet events
def connectTransmogrifier(self, transmog):
self.transmogrifier = transmog
self.transmogrifier.connect(self.eventQueue)
def initializeStrangers(self):
self._volatile = dict((Stranger(reactor, self, HTTP), None) for _ in xrange(self._n))
self._waiting = len(self._volatile.keys())
self.strangers = {}
self.idleTime = time()
self._allConnected = False
def multicastDisconnect(self, ids):
"""Announce disconnect for a group of strangers.
ids : iterable
id strings of strangers from whom to politely disconnect.
"""
for i in ids:
self.strangers[i].announceDisconnect()
def restart(self):
self.strangers.clear()
self.eventQueue.clear()
self._allConnected = False
sleep(self.reconnectWait) # blocking is OK here. We are trying to *avoid* making connections.
self.initializeStrangers()
def pumpEvents(self):
for id_ in self.strangers:
self.strangers[id_].getEventsPage()
reactor.callLater(self.refresh, self.pumpEvents)
def on_idSet(self, ev):
for s in self._volatile:
if s.id == ev.id: # we have the stranger that notified
self.strangers[s.id] = s # move to {id: stranger} dict
self._waiting -= 1
assert self._waiting >= 0, "Too many stranger IDs"
if self._waiting == 0:
self._allConnected = True
self.idleTime = time()
self.pumpEvents()
def on_error(self, ev):
# TODO: handle RECAPCHA
pass
def addListeners(self, listeners):
"""Add a listener or group of listeners to the reactor.
listeners : CBDictInterface instance or iterable
"""
listeners = mkIterableSequence(listeners)
for listen in listeners:
self.listeners[listen] = listen # weak-value dict
def removeListener(self, listener):
self.listeners.pop(listener)
def _processEventQueue(self):
while len(self.eventQueue):
ev = self.eventQueue.popleft()
for listener in self.listeners:
listener.notify(ev)
self.notify(ev)
def deltaIdleTime(self):
return time() - self.idleTime
def idle(self):
"""Respond to idle state.
This function is run whenever feed encounters a null event, and
does nothing by default. Override to define functionality.
#.........这里部分代码省略.........
示例13: TaskQueue
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class TaskQueue(AbstractTaskQueue):
"""Simple in-memory task queue implementation"""
@classmethod
def factory(cls, url, name=const.DEFAULT, *args, **kw):
obj = _REFS.get((url, name))
if obj is None:
obj = _REFS[(url, name)] = cls(url, name, *args, **kw)
return obj
def __init__(self, *args, **kw):
super(TaskQueue, self).__init__(*args, **kw)
self.queue = Queue()
self.results = WeakValueDictionary()
self.results_lock = Lock()
def _init_result(self, result, status, message):
with self.results_lock:
if result.id in self.results:
return False
self.results[result.id] = result
result.__status = status
result.__value = Queue()
result.__task = message
result.__args = {}
result.__lock = Lock()
result.__for = None
return True
def enqueue_task(self, result, message):
if self._init_result(result, const.ENQUEUED, message):
self.queue.put(result)
return True
return False
def defer_task(self, result, message, args):
if self._init_result(result, const.PENDING, message):
results = self.results
# keep references to results to prevent GC
result.__refs = [results.get(arg) for arg in args]
return True
return False
def undefer_task(self, task_id):
result = self.results[task_id]
self.queue.put(result)
def get(self, timeout=None):
try:
result = self.queue.get(timeout=timeout)
except Empty:
return None
result.__status = const.PROCESSING
return result.id, result.__task
def size(self):
return len(self.results)
def discard_pending(self):
with self.results_lock:
while True:
try:
self.queue.get_nowait()
except Empty:
break
self.results.clear()
def reserve_argument(self, argument_id, deferred_id):
result = self.results.get(argument_id)
if result is None:
return (False, None)
with result.__lock:
if result.__for is not None:
return (False, None)
result.__for = deferred_id
try:
message = result.__value.get_nowait()
except Empty:
message = None
if message is not None:
with self.results_lock:
self.results.pop(argument_id, None)
return (True, message)
def set_argument(self, task_id, argument_id, message):
result = self.results[task_id]
with self.results_lock:
self.results.pop(argument_id, None)
with result.__lock:
result.__args[argument_id] = message
return len(result.__args) == len(result.__refs)
def get_arguments(self, task_id):
try:
return self.results[task_id].__args
except KeyError:
return {}
def set_task_timeout(self, task_id, timeout):
pass
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class Entity:
def __init__(self, entType, entValue, entField):
if isinstance(entField, Field):
self.type = entType
self.value = entValue
self.field = entField
self.group = None
self.links = WeakValueDictionary() # dict of linked entities
self.field.registerEntity(self) # update the entity registry
else:
raise TypeError("Invalid field argument, field instance expected!")
def linkTo(self, eTwo):
''' Linking operation is bi-directional, affects both entities equally.'''
# check if entities not already linked
if Edge.linkId(self, eTwo) not in self.links.keys():
# update both entities' list of links
# create a new edge
newlink = Edge(self, eTwo, self.field)
self.links[newlink.id] = eTwo
eTwo.links[newlink.id] = self
# case when the first entity's group is not set
if self.group is None:
# assuming the second entity has already a group assigned
try:
eTwo.group.addMember(self)
# except the second entity has no group
except AttributeError:
newGroup = Group(self.field)
newGroup.addMember(self)
newGroup.addMember(eTwo)
# case when the first entity's group is set, but the second entity's is not
elif eTwo.group is None:
self.group.addMember(eTwo)
# case when both entities have groups set and they are different groups
elif self.group.name != eTwo.group.name:
if self.group.size > eTwo.group.size:
# first group wins
self.group.annexMembers(eTwo.group)
else:
# second group wins
eTwo.group.annexMembers(self.group)
def getLinks(self):
''' Print the list of entities directly linked.'''
return self.links.values()
def removeLink(self, eTwo):
''' Remove linked entity.'''
linkId = Edge.linkId(self, eTwo)
self.links.pop(linkId)
def __repr__(self):
return repr(self.value)
def __del__(self):
''' Delete itself from linked entities, and delete links.'''
# remove link from linked entity necessary? no because it's a weaklink
for linkId in self.links.keys():
self.field.eliminateEdge(linkId)
del self
示例15: PropAnimation
# 需要导入模块: from weakref import WeakValueDictionary [as 别名]
# 或者: from weakref.WeakValueDictionary import pop [as 别名]
class PropAnimation(QtCore.QPropertyAnimation):
base_time = 350
disable_animation = True
def __init__(self, widget, name, time_factor=1.0, force=False):
super(PropAnimation, self).__init__(widget, name)
self.stateChanged.connect(self._onStateChanged)
self._force = force
self.dic = WeakValueDictionary()
self.dic['widget'] = widget
self.__new = None
self.time = time_factor * self.base_time
self.setEasingCurve(QtCore.QEasingCurve.InOutQuad)
@property
def widget(self):
return self.dic['widget']
def _onStateChanged(self, state):
if state == self.Running:
running_animations.append(self)
if self.dic.get('__reparent'):
self.dic['__old_parent'] = self.widget.parentItem()
self.widget.setParentItem(self.dic['__reparent'])
elif state == self.Stopped:
try:
attr = getattr(self.dic['widget'], 'set' + str(self.propertyName()).capitalize())
except RuntimeError:
logger.ddebug('runtime error for {}'.format(self))
#FUCKIT
return
attr(self.__new)
self.__new = None
if self.dic.get('__reparent'):
self.widget.setParentItem(self.dic['__old_parent'])
self.dic.pop('__reparent')
self.dic.pop('__old_parent')
running_animations.remove(self)
def setup(self, new, old=None, reparent=None, path_function=None):
if self.state() == self.Running and not self._force:
return False
self.__new = new
if old is None:
old = getattr(self.dic['widget'], str(self.propertyName()))
if hasattr(old, '__call__'):
old = old()
if reparent:
self.dic['__reparent'] = reparent
old = self.widget.mapToItem(reparent, old)
new = self.widget.mapToItem(reparent, new)
if path_function:
points = path_function(old, new)
self.setKeyValues([])
for i, p in enumerate(points):
self.setKeyValueAt(float(i) / len(points), p)
self.setDuration(self.time)
self.setStartValue(old)
self.setEndValue(new)
return True
def start(self):
if self.state() == self.Running and not self._force:
return False
super(PropAnimation, self).start()
return True