本文整理汇总了Python中weakref.WeakSet.add方法的典型用法代码示例。如果您正苦于以下问题:Python WeakSet.add方法的具体用法?Python WeakSet.add怎么用?Python WeakSet.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weakref.WeakSet
的用法示例。
在下文中一共展示了WeakSet.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class Signal(object):
def __init__(self):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
def __call__(self, *args, **kargs):
for f in self._functions:
f(*args, **kargs)
for obj, functions in self._methods.items():
for f in functions:
f(obj, *args, **kargs)
def connect(self, slot):
if inspect.ismethod(slot):
if not slot.__self__ 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)
示例2: BaseSubject
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class BaseSubject(object):
""" Object holding all the observers, aliased to dirigent.subject
"""
def __init__(self, init=None):
if init:
self.observers = WeakSet(init)
else:
self.observers = WeakSet()
def register(self, func):
""" Registers a callable.
Can be used as a decorator.
"""
self.observers.add(func)
return func
def unregister(self, func):
""" Unregisters a callable.
"""
if func in self.observers:
self.observers.remove(func)
return func
return False
def notify(self, *args, **kwargs):
""" Notifies all registered observers of an event.
"""
return [observer(*args, **kwargs) for observer in self.observers]
def __iter__(self):
return (observer for observer in self.observers)
__call__ = notify
on = bind = register
off = unbind = unregister
示例3: ConnectionFactory
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class ConnectionFactory(ReconnectingClientFactory):
"""Creates `.Connection` instances."""
protocol = Connection
log = Logger()
def __init__(self):
#: The `ConnectionSettings` object associated with this factory.
self.settings = ConnectionSettings()
#: A `WeakSet` containing associated `Connection` objects.
self.protocols = WeakSet()
def startedConnecting(self, connector):
self.log.info("Attempting to connect to server")
def buildProtocol(self, addr):
protocol = ReconnectingClientFactory.buildProtocol(self, addr)
protocol.settings = self.settings
# Set various properties defined by Twisted's IRCClient.
protocol.nickname = self.settings.nickname or protocol.nickname
protocol.password = self.settings.password or protocol.password
protocol.realname = self.settings.realname or protocol.realname
protocol.username = self.settings.username or protocol.username
protocol.userinfo = self.settings.userinfo or protocol.userinfo
self.protocols.add(protocol)
return protocol
def reload_settings(self, dct):
"""Update this connection's settings using *dct*, then call
`after_reload` on each of this factory's active connections."""
self.log.info("Reloading settings")
self.settings.replace(dct)
for protocol in self.protocols:
protocol.after_reload()
示例4: test_weak_destroy_and_mutate_while_iterating
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
def test_weak_destroy_and_mutate_while_iterating(self):
# Issue #7105: iterators shouldn't crash when a key is implicitly removed
items = [SomeClass(c) for c in string.ascii_letters]
s = WeakSet(items)
@contextlib.contextmanager
def testcontext():
try:
it = iter(s)
next(it)
# Schedule an item for removal and recreate it
u = SomeClass(str(items.pop()))
test_support.gc_collect() # just in case
yield u
finally:
it = None # should commit all removals
test_support.gc_collect()
with testcontext() as u:
self.assertNotIn(u, s)
with testcontext() as u:
self.assertRaises(KeyError, s.remove, u)
self.assertNotIn(u, s)
with testcontext() as u:
s.add(u)
self.assertIn(u, s)
t = s.copy()
with testcontext() as u:
s.update(t)
self.assertEqual(len(s), len(t))
with testcontext() as u:
s.clear()
self.assertEqual(len(s), 0)
示例5: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
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)
示例6: subscribe
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
def subscribe(self, event, listener_object):
event_handler_name = "on_%s_handler" % event
if not hasattr(listener_object, event_handler_name):
raise AttributeError("Listener object has no '%s' event handler." % event)
try:
event_listeners = self._listeners[event]
except KeyError:
event_listeners = WeakSet()
self._listeners[event] = event_listeners
event_listeners.add(listener_object)
示例7: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
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()
示例8: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
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
示例9: __init__
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class Channel:
"""A communication channel."""
def __init__(self, template="{msg}", members=None, logged=False):
"""Create a new channel.
:param str template: A formatting string to use as a message template
:param members: Optional, a list of sessions to fill members with;
if callable, it should return a list of sessions on-
demand in place of member tracking
:param bool logged: Whether to log messages to the console or not
:returns None:
"""
self.template = template
self.logged = logged
if callable(members):
self.members = members
else:
self.members = WeakSet()
if members:
for session in members:
self.members.add(session)
def send(self, data, *more, sep=" ", context=None, members=None):
"""Send a message to a channel.
`data` and all members of `more` will be converted to strings
and joined together by `sep` via the joins function.
:param any data: An initial chunk of data
:param any more: Optional, any additional data to send
:param str sep: Optional, a separator to join the resulting output by
:param dict context: Optional, additional context to be passed to
the template formatter
:param members: Optional, a list of sessions to use in place of the
channels own list; if callable, it should return a list
of sessions to use
:returns None:
"""
if not members:
members = self.members
if callable(members):
members = members()
message = joins(data, *more, sep=sep)
context = context or {}
message = self.template.format(msg=message, **context)
if self.logged:
log.info(strip_caret_codes(message))
for session in members:
session.send(message)
示例10: test_len
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
def test_len(self):
obj = Object()
obj2 = Object()
ws = WeakSet([obj])
self.assertIn(obj, ws)
self.assertEqual(len(ws), 1)
ws.add(obj2)
self.assertEqual(len(ws), 2)
self.assertIn(obj2, ws)
del obj
self.assertEqual(len(ws), 1)
self.assertIn(obj2, ws)
示例11: Subject
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class Subject(object):
def __init__(self, name):
self.name = name
self._observers = WeakSet()
def register_observer(self, observer):
self._observers.add(observer)
print('observer {0} now listening on {1}'.format(observer.name, self.name))
def notify_observers(self, msg):
print('{0} notifying observers about {1}'.format(self.__class__.__name__, msg))
for observer in self._observers:
observer.notify(self, msg)
示例12: LazyResult
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class LazyResult(object):
inited = False
deps = None # Stores hard references to upstream dependencies for invalidation purposes
def __init__(self, watcher = None):
self.watcher = watcher
def invalidate(self):
if not hasattr(self, '_value'):
return
if threading.current_thread() != MAIN_THREAD or evaluation_stack:
invalidation_queue.append(self)
invalidation_event.set()
return
del self._value
self.deps = None
try:
refs = tuple(self._refs)
except AttributeError:
return
self._refs.clear()
for ref in refs:
ref.invalidate()
def set(self, value):
assert not hasattr(self, '_value')
self._value = (value, None)
def get(self, f, *args):
assert threading.current_thread() == MAIN_THREAD
if not self.inited:
invalidation_strategy._watch_object(self)
self.inited = True
if evaluation_stack:
if not hasattr(self, '_refs'):
self._refs = WeakSet()
self._refs.add(evaluation_stack[-1])
try:
value, e = self._value
except AttributeError:
with LazyEvaluationContext(self):
try:
value = f(*args)
self._value = (value, None)
return value
except Exception, e:
self._value = (None, e)
raise
if e:
raise e
return value
示例13: Environments
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class Environments(object):
""" A common object for all environments in a request. """
def __init__(self):
self.envs = WeakSet() # weak set of environments
self.todo = {} # recomputations {field: [records]}
self.mode = False # flag for draft/onchange
def add(self, env):
""" Add the environment `env`. """
self.envs.add(env)
def __iter__(self):
""" Iterate over environments. """
return iter(self.envs)
示例14: __init__
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class ConnectionPool:
def __init__(self):
self._config_dict = None
self._queue = Queue()
self._outstanding_connections = WeakSet()
async def get_conn(self):
self._check_config()
try:
while True:
conn = self._queue.get_nowait()
if conn.is_open():
break
try:
await conn.close()
except Exception:
l.debug('Exception in close rethink connection', exc_info=True)
except QueueEmpty:
conn = await r.connect(**self._config_dict)
self._outstanding_connections.add(conn)
return conn
async def put_conn(self, conn):
self._queue.put_nowait(conn)
self._outstanding_connections.remove(conn)
def set_config(self, config):
self._config_dict = config
def get_config(self):
self._check_config()
return self._config_dict
async def teardown(self):
while True:
try:
conn = self._queue.get_nowait()
except QueueEmpty:
break
self._outstanding_connections.add(conn)
for conn in self._outstanding_connections:
try:
await conn.close()
except Exception:
l.debug('Exception in close rethink connection', exc_info=True)
def _check_config(self):
assert self._config_dict is not None, "Did you remember to run resync.setup()?"
示例15: ObservableEvent
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import add [as 别名]
class ObservableEvent(object):
def __init__(self, weakref=False):
self.listeners = WeakSet() if weakref else set()
def __iadd__(self, ob):
self.listeners.add(ob)
return self
def __isub__(self, ob):
self.listeners.discard(ob)
return self
def notify(self, *a, **k):
for ob in list(self.listeners):
ob(*a, **k)