本文整理汇总了Python中weakref.WeakKeyDictionary类的典型用法代码示例。如果您正苦于以下问题:Python WeakKeyDictionary类的具体用法?Python WeakKeyDictionary怎么用?Python WeakKeyDictionary使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WeakKeyDictionary类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: LazyInvalidation
class LazyInvalidation(object):
def __enter__(self):
assert threading.current_thread() == MAIN_THREAD
assert not evaluation_stack
self._watchMap = WeakKeyDictionary()
self._watchable_objects = WeakSet()
global invalidation_strategy
invalidation_strategy._invalidate_all()
invalidation_strategy = self
def _watch_object(self, object):
if object.watcher is not None and object.watcher not in self._watchMap:
self._watchMap[object.watcher] = WeakWatchIntermediary(object, object.watcher)
def _add_dependency(self, object):
if evaluation_stack:
evaluation_stack[-1].deps.append(object)
def _unwatch_object(self, object):
object.invalidate()
self._watchable_objects.discard(object)
def __exit__(self, type, value, traceback):
global invalidation_strategy
invalidation_strategy = LazyConstants()
for intermediary in self._watchMap.itervalues():
intermediary.release()
self._watchMap.clear()
def _invalidate_all(self):
raise TypeError('Cannot nest lazy_invalidation contexts')
开发者ID:chrisalice,项目名称:gittools,代码行数:31,代码来源:lazy.py
示例2: FrameRegistry
class FrameRegistry(object):
"""
This class implements a method to keep track of wrapped frames. In short,
Qt will give us frames that are QWebFrames, and we want to only deal with
WebFrames that we control. This registry will either wrap a given frame,
or return the previously-wrapped one from the registry.
"""
def __init__(self, klass, *args, **kwargs):
self._registry = WeakKeyDictionary()
self.klass = klass
self.args = args
self.kwargs = kwargs
def wrap(self, frame):
if frame is None:
return None
existing = self._registry.get(frame)
if existing is not None:
return existing
# Create web frame, passing the underlying value, and ourselves.
new = self.klass(frame, self, *self.args, **self.kwargs)
self._registry[frame] = new
return new
def clear(self):
self._registry.clear()
开发者ID:andrew-d,项目名称:Specter.py,代码行数:28,代码来源:specter.py
示例3: __init__
class EventManager:
"""this object is responsible for coordinating most communication
between the Model, View, and Controller."""
def __init__(self ):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
self.eventQueue= []
#----------------------------------------------------------------------
def RegisterListener( self, listener ):
self.listeners[ listener ] = 1
#----------------------------------------------------------------------
def UnregisterListener( self, listener ):
if listener in self.listeners.keys():
del self.listeners[ listener ]
#----------------------------------------------------------------------
def Post( self, event ):
if not isinstance(event, TickEvent): Debug( " Message: " + event.name )
for listener in self.listeners.keys():
#NOTE: If the weakref has died, it will be
#automatically removed, so we don't have
#to worry about it.
listener.Notify( event )
开发者ID:Xicnet,项目名称:burnstation,代码行数:25,代码来源:example1.py
示例4: __init__
class EventMediator:
def __init__(self):
self.Listeners = WeakKeyDictionary()
self.EventQueue = []
def RegisterListener(self, listener):
self.Listeners[listener] = 1
def UnregisterListener(self, listener):
if listener in self.Listeners.keys():
del self.Listeners[listener]
def Post(self, event):
if not isinstance(event, TickEvent):
self.EventQueue.append(event)
else:
Events = copy(self.EventQueue)
self.EventQueue = []
while len(Events) > 0:
ev = Events.pop(0)
for listener in self.Listeners.keys():
listener.Notify(ev)
for listener in self.Listeners.keys():
listener.Notify(event)
开发者ID:Ouro130Ros,项目名称:MenlosBook,代码行数:25,代码来源:EventMediator.py
示例5: EventManager
class EventManager(object):
def __init__(self):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
def register_listener(self, listener):
"""
Register new listener
"""
self.listeners[listener] = 1
def unregister_listener(self, listener):
"""
Unregister existing listener
"""
if listener in self.listeners.keys():
del self.listeners[listener]
def post(self, event):
"""
Post new event
"""
for listener in self.listeners.keys():
listener.notify(event)
开发者ID:pielgrzym,项目名称:pung,代码行数:30,代码来源:event_manager.py
示例6: ShapeManager
class ShapeManager( object ):
def __init__( self, canvas ):
self.canvasItemToPartMap = WeakKeyDictionary()
self.canvasItemToShapeMap = WeakKeyDictionary()
self.canvas = canvas
def associateCanvasItemWithShape( self, canvasItem, shape ):
self.canvasItemToShapeMap[ canvasItem ] = ref( shape )
def associateCanvasItemWithPart( self, canvasItem, part ):
self.canvasItemToPartMap[ canvasItem ] = mrt
def getPartByCanvasItem( self, canvasItem ):
return self.canvasItemToPartMap.get( canvasItem, None )
def getShapeByCanvasItem( self, canvasItem ):
r = self.canvasItemToShapeMap.get( canvasItem, None )
if r != None:
return r()
return None
def createComplexShape( self, molds, modelObject = None ):
return ComplexShape( self, self.canvas, molds, modelObject )
def createConnector( self, modelObject = None ):
return Connector( self, self.canvas, modelObject )
开发者ID:ecell,项目名称:ecell3-model-editor,代码行数:26,代码来源:__init__.py
示例7: __init__
class EventHandler:
"""this object is responsible for coordinating most communication
between the Model, View, and Controller.
"""
def __init__(self ):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
#----------------------------------------------------------------------
def register_listener( self, listener ):
self.listeners[ listener ] = 1
#----------------------------------------------------------------------
def unregister_listener( self, listener ):
if listener in self.listeners.keys():
del self.listeners[ listener ]
#----------------------------------------------------------------------
def post( self, event ):
"""Post a new event. It will be broadcast to all listeners"""
for listener in self.listeners.keys():
#NOTE: If the weakref has died, it will be
#automatically removed, so we don't have
#to worry about it.
listener.notify( event )
开发者ID:ArinT,项目名称:Ridge,代码行数:25,代码来源:event_handler.py
示例8: __init__
class EventManager:
"""Event Manager -- coordinate communication between the Model,
View, and Controller."""
def __init__(self):
self.listeners = WeakKeyDictionary()
# self.event_queue= []
def register_listener(self, listener):
self.listeners[listener] = True
def UnregisterListener(self, listener):
if listener in self.listeners.keys():
del self.listeners[listener]
def post(self, ev):
if not (isinstance(ev, TickEvent) or \
isinstance(ev, StepEvent) or \
isinstance(ev, HelpEvent) or \
isinstance(ev, ToggleViewEvent) or \
isinstance(ev, ToggleAutoEvent) or \
isinstance(ev, BusyEvent) or \
isinstance(ev, ReadyEvent)):
debug(" ** " + ev.name)
for listener in self.listeners.keys():
# If the weakref has died, remove it and continue
# through the list
if listener is None:
del self.listeners[listener]
continue
listener.notify(ev)
开发者ID:riedelcastro,项目名称:wumpusworld,代码行数:33,代码来源:event.py
示例9: EventManager
class EventManager(object):
"""
We coordinate communication between the Model, View, and Controller.
"""
def __init__(self):
from weakref import WeakKeyDictionary
self.listeners = WeakKeyDictionary()
def register_listener(self, listener):
"""
Adds a listener to our spam list.
It will receive post()ed events through it's notify(event) call.
"""
self.listeners[listener] = 1
def unregister_listener(self, listener):
"""
Remove a listener from our spam list.
This is implemented but hardly used.
Our weak ref spam list will auto remove any listeners who stop existing.
"""
if listener in self.listeners.keys():
del self.listeners[listener]
def post(self, event):
"""
Post a new event to the message queue.
It will be broadcast to all listeners.
"""
if not isinstance(event, TickEvent) and \
not isinstance(event, CharUpdateEvent):
print(str(event)) # print the event (unless it is TickEvent)
for listener in self.listeners.keys():
listener.notify(event)
开发者ID:henkburgstra,项目名称:pyRPG,代码行数:34,代码来源:eventmanager.py
示例10: __init__
class EventManager:
"""
Superclass for all event managers. Keeps a list of listeners and
dispatches events to them.
"""
def __init__(self):
self.listeners = WeakKeyDictionary()
#--------------------------------------------------------------------------
def register_listener(self,listener):
self.listeners[listener] = 1
#--------------------------------------------------------------------------
def unregister_listener(self,listener):
if listener in self.listeners.keys():
del self.listeners[listener]
#--------------------------------------------------------------------------
def post(self,event):
for listener in self.listeners.keys():
listener.notify(event)
开发者ID:goshdarngames,项目名称:flood,代码行数:25,代码来源:events.py
示例11: __init__
class EventManager:
"""
this class is responsible for coordinating most communication between
the Model, View and Controller.
I use WeakKeyDictionary to keep track of the registered listeners. From the
python documentation:
Mapping class that references keys weakly. Entries in the dictionary will
be discarded when there is no longer a strong reference to the key.
Using this dictionary takes care of object scope, avoiding dispatching to
a non existing listener.
@todo: I need to implement event categories, avoiding spamming notifies for
events that only matters for some listeners.
"""
def __init__(self):
self.listeners = WeakKeyDictionary()
def RegisterListener(self, listener):
self.listeners[listener] = 1
def UnregisterListener(self, listener):
if listener in self.listeners.keys():
del self.listeners[listener]
def Post(self, event):
for listener in self.listeners.keys():
listener.Notify(event)
开发者ID:edisongustavo,项目名称:battleships,代码行数:30,代码来源:events.py
示例12: __init__
def __init__(self, latency):
self.latency = latency
self.mounts = WeakKeyDictionary()
self.contexts = WeakSet()
self.lock = RLock()
self.cell_updates = deque()
self._tick = Event()
self.paths = WeakKeyDictionary()
开发者ID:sjdv1982,项目名称:seamless,代码行数:8,代码来源:mount.py
示例13: Signal
class Signal(object):
"""
Simple class to emit signals to connected callable receivers.
"""
def __init__(self):
"""
Instantiate a new object
"""
self.funcs = WeakSet()
self.meths = WeakKeyDictionary()
def connect(self, c):
"""
Connect a callable as receiver for the signal
@param c: signal receiver
@type c: Callable
"""
if inspect.ismethod(c):
if c.__self__ not in self.meths:
self.meths[c.__self__] = set()
self.meths[c.__self__].add(c.__func__)
else:
if c not in self.funcs:
self.funcs.add(c)
def disconnect(self, c):
"""
Disconnect the callable from receiving the signal
@param c: signal receiver
@type c: Callable
"""
if inspect.ismethod(c):
if c.__self__ in self.meths:
self.meths[c.__self__].remove(c.__func__)
else:
if c in self.funcs:
self.funcs.remove(c)
def disconnectAll(self):
"""
Disconnects all signal receivers
"""
self.funcs.clear()
self.meths.clear()
def emit(self, *args, **kwargs):
"""
Fires the signal to all connected receivers
"""
for c in self.funcs:
c(*args, **kwargs)
for obj, funcs in self.meths.items():
for func in funcs:
func(obj, *args, **kwargs)
开发者ID:pathmann,项目名称:pyTSon,代码行数:57,代码来源:signalslot.py
示例14: __init__
def __init__(self, type, default=None, nillable=False):
if default is None and not nillable:
raise TypeError("default must be specified if object is not nillable")
self.type = type
self.default = default
self.nillable = nillable
self.values = WeakKeyDictionary()
self.oldvalues = WeakKeyDictionary()
self.dirty = WeakKeyDictionary()
开发者ID:LaoHanTeam,项目名称:python-sipsimple,代码行数:9,代码来源:__init__.py
示例15: __init__
class EventManager:
"""this object is responsible for coordinating most communication
between the Model, View, and Controller."""
def __init__(self, initlist=None ):
self.listeners = WeakKeyDictionary()
self.eventQueue = []
self.__lock = threading.Lock()
#----------------------------------------------------------------------
def RegisterListener( self, listener , eventList):
#if not hasattr( listener, "Notify" ): raise blah blah...
self.listeners[ listener ] = eventList
def addListener(self, listener, eventList):
if self.listeners.has_key( listener ):
self.listeners[ listener ].append( eventList )
else:
self.listeners[ listener ] = eventList
#----------------------------------------------------------------------
def UnregisterListener( self, listener ):
if listener in self.listeners.keys():
del self.listeners[ listener ]
#----------------------------------------------------------------------
def Post( self, event ):
if event==OneSecondEvent:
self.sendEvent( event )
if not event==TickEvent:
self.__lock.acquire()
self.eventQueue.append( event )
self.__lock.release()
else:
self.flushEvents()
#at the end, notify listeners of the Tick event
for listener in self.listeners.keys():
listener.Notify( event )
def flushEvents(self):
if self.eventQueue:
for k in range(len(self.eventQueue)):
ev = self.eventQueue.pop(0)
self.sendEvent(ev)
def sendEvent(self, ev):
for listener in self.listeners.keys():
throwable_events = self.listeners[listener]
if ev in throwable_events:
listener.Notify( ev )
开发者ID:jbittencourt,项目名称:cooperativa_client,代码行数:56,代码来源:eventmanager.py
示例16: __init__
def __init__(self, default_index=0, choices=None, display_func=None, **kwargs):
if choices is not None and 'default' not in kwargs:
kwargs['default'] = choices[default_index]
super(SelectionCallbackProperty, self).__init__(**kwargs)
self.default_index = default_index
self.default_choices = choices or []
self._default_display_func = display_func
self._choices = WeakKeyDictionary()
self._display = WeakKeyDictionary()
self._force_next_sync = WeakKeyDictionary()
开发者ID:glue-viz,项目名称:glue,代码行数:10,代码来源:selection.py
示例17: _init_descriptor_environment
def _init_descriptor_environment(self):
"""There's no way to distinguis between description and simple
generator mode, so the initialization of the necessary
per-instance mappings is done at the first __get__
execution.
"""
self._dep = WeakKeyDictionary()
self._value = WeakKeyDictionary()
self._comp = WeakKeyDictionary()
self._descriptor_initialized = True
开发者ID:azazel75,项目名称:metapensiero.reactive,代码行数:10,代码来源:value.py
示例18: __init__
def __init__(self, id, name, parent, user, priority, dispatchKey, maxRN,
creationTime=None, startTime=None,
updateTime=None, endTime=None,
status=NODE_READY):
'''
Base class for each node in dispatcher tree structure. Holds main model
fields.
:param id int: unique id for this node
:param name str: a short string describing this node
:param parent: a FolderNode or None if this node is a root node
:param priority int: priority value
:param dispatchKey int: dispatchKey value
:param maxRN int: maximum number of render nodes that can be allocated to this tree node
:param creationTime: timestamp indicating when the node was created
:param startTime: timestamp indicating when the node was started
:param updateTime: timestamp indicating when the node was updated
:param endTime: timestamp indicating when the node was ended
:param status int: current node's status
'''
if not self.dispatcher:
from octopus.dispatcher.dispatcher import Dispatcher
self.dispatcher = Dispatcher(None)
self.__dict__['parent'] = None
models.Model.__init__(self)
self.id = int(id) if id is not None else None
self.name = str(name)
self.parent = parent
self.user = str(user)
self.priority = int(priority)
self.dispatchKey = int(dispatchKey)
self.maxRN = int(maxRN)
self.optimalMaxRN = 0
self.allocatedRN = 0
self.poolShares = WeakKeyDictionary()
self.additionnalPoolShares = WeakKeyDictionary()
self.completion = 1.0
self.status = status
self.creationTime = time() if not creationTime else creationTime
self.startTime = startTime
self.updateTime = updateTime
self.endTime = endTime
self.dependencies = []
self.reverseDependencies = []
self.lastDependenciesSatisfaction = False
self.lastDependenciesSatisfactionDispatchCycle = -1
self.readyCommandCount = 0
self.doneCommandCount = 0
self.commandCount = 0
self.averageTimeByFrameList = []
self.averageTimeByFrame = 0.0
self.minTimeByFrame = 0.0
self.maxTimeByFrame = 0.0
self.timer = None
开发者ID:madmouser1,项目名称:OpenRenderManagement,代码行数:55,代码来源:node.py
示例19: Signal
class Signal(object):
def __init__(self):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
self._activated = True
def __call__(self, *args, **kargs):
# call connected functions only if activated
if self._activated:
# Call handler functions
for func in self._functions:
func(*args, **kargs)
# Call handler methods
for obj, funcs in self._methods.items():
for func in funcs:
func(obj, *args, **kargs)
def connect(self, slot):
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)
def disconnect(self, slot):
if inspect.ismethod(slot):
if slot.__self__ in self._methods:
self._methods[slot.__self__].remove(slot.__func__)
else:
if slot in self._functions:
self._functions.remove(slot)
def clear(self):
self._functions.clear()
self._methods.clear()
def activate(self):
"""
Activate the signal to emit.
"""
self._activated = True
def deactivate(self):
"""
Deactivate the signal to emit.
"""
self._activated = False
开发者ID:ElricleNecro,项目名称:LISA,代码行数:54,代码来源:Signals.py
示例20: Signal
class Signal(object):
def __init__(self):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
def __call__(self, *args, **kargs):
# Call handler functions
to_be_removed = []
for func in self._functions.copy():
try:
func(*args, **kargs)
except RuntimeError:
Warning.warn('Signals func->RuntimeError: func "{}" will be removed.'.format(func))
to_be_removed.append(func)
for remove in to_be_removed:
self._functions.discard(remove)
# Call handler methods
to_be_removed = []
emitters = self._methods.copy()
for obj, funcs in emitters.items():
msg_debug('obj is type "{}"'.format(type(obj)))
for func in funcs.copy():
try:
func(obj, *args, **kargs)
except RuntimeError:
warnings.warn('Signals methods->RuntimeError, obj.func "{}.{}" will be removed'.format(obj, func))
to_be_removed.append((obj, func))
for obj, func in to_be_removed:
self._methods[obj].discard(func)
def connect(self, slot):
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)
def disconnect(self, slot):
if inspect.ismethod(slot):
if slot.__self__ in self._methods:
self._methods[slot.__self__].remove(slot.__func__)
else:
if slot in self._functions:
self._functions.remove(slot)
def clear(self):
self._functions.clear()
self._methods.clear()
开发者ID:dhomeier,项目名称:specview,代码行数:54,代码来源:signal_slot.py
注:本文中的weakref.WeakKeyDictionary类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论