本文整理汇总了Python中weakref.WeakSet.remove方法的典型用法代码示例。如果您正苦于以下问题:Python WeakSet.remove方法的具体用法?Python WeakSet.remove怎么用?Python WeakSet.remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类weakref.WeakSet
的用法示例。
在下文中一共展示了WeakSet.remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BaseSubject
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [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
示例2: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [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)
示例3: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [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)
示例4: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [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()
示例5: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [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
示例6: __init__
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [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()?"
示例7: Account
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class Account(Entity):
"""A user account."""
_uid_code = "A"
type = "account"
def __init__(self, data=None, active=False, savable=True):
super().__init__(data, active, savable)
self._sessions = WeakSet()
def __repr__(self):
if hasattr(self, "name") and self.name:
return joins("Account<", self.name, ">", sep="")
else:
return "Account<(unnamed)>"
def login(self, session):
"""Process an account login for a session.
:param sessions.Session session: The session logging in
:returns None:
"""
with EVENTS.fire("account_login", session, self):
log.info("%s has logged in to %s.", session, self)
session.send("\nMOTD will go here!")
if session not in self._sessions:
self._sessions.add(session)
if not self.active:
self.active = True
def logout(self, session):
"""Process an account logout for a session.
:param sessions.Session session: The session logging out
:returns None:
"""
with EVENTS.fire("account_logout", session, self):
log.info("%s has logged out of %s.", session, self)
if session in self._sessions:
self._sessions.remove(session)
if not self._sessions:
self.active = False
示例8: SIGNAL
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class SIGNAL(object):
def __init__( self, name = None ):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
self._name = name
def __call__(self, *args, **kargs):
# 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()
示例9: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class Signal(object):
def __init__(self):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
def __call__(self, *args, **kargs):
res = []
# Call handler functions
for func in self._functions:
res.append(func(*args, **kargs))
# Call handler methods
for obj, funcs in self._methods.items():
for func in funcs:
res.append(func(obj, *args, **kargs))
return res
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()
示例10: __init__
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class Agent:
def __init__(self, loop: AbstractEventLoop = None):
self._loop = loop
self._links = WeakSet()
self._monitors = WeakSet()
self._queue = Queue(loop=self._loop)
self._task = asyncio.ensure_future(self._main(), loop=self._loop)
@property
def alive(self) -> bool:
return self._task is not None
@property
def exited(self) -> bool:
return self._task is None
@property
def loop(self) -> AbstractEventLoop:
return self._loop
@property
def task(self) -> Task:
return self._task
def bidirectional_link(self, to: 'Agent'):
self._links.add(to)
to._links.add(self)
def unlink(self, from_: 'Agent'):
self._links.remove(from_)
from_._links.remove(self)
def monitor(self, monitored: 'Agent'):
self._links.add(monitored)
monitored._monitors.add(self)
def spawn_linked_task(self, coro_or_future, unlink_on_success: bool = True) -> 'LinkedTask':
return LinkedTask(self, coro_or_future, unlink_on_success=unlink_on_success, loop=self._loop)
async def _main(self):
# noinspection PyBroadException
try:
while self.alive:
fun = await self._queue.get()
await fun()
except Exception as exc:
self.exit(exc)
else:
self.exit(None)
def exit(self, exc: Optional[Exception] = None):
old_task = self._task
try:
if self.exited:
return
self._task = None
if exc:
logger.debug("%s is exiting because %s", self, exc)
else:
logger.debug("%s is exiting normally", self)
for link in self._links:
link.exit(exc)
for monitor in self._monitors:
method = getattr(monitor, 'on_monitored_exit', None)
if method:
method(self, exc)
else:
logger.warning("%s was monitoring an agent %s, but doesn't implemented on_monitored_exit",
monitor, self)
finally:
if old_task is not None:
old_task.cancel()
self._links = WeakSet()
self._monitors = WeakSet()
示例11: __init__
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class MountManager:
_running = False
_last_run = None
_stop = False
_mounting = False
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()
@lockmethod
def add_mount(self, cell, path, mode, authority, persistent, **kwargs):
root = cell._root()
if root not in self.paths:
paths = set()
self.paths[root] = paths
else:
paths = self.paths[root]
assert path not in paths, path
#print("add mount", path, cell)
paths.add(path)
item = MountItem(self, cell, path, mode, authority, persistent, **kwargs)
self.mounts[cell] = item
return item
@lockmethod
def add_link(self, link, path, persistent):
paths = self.paths[link._root()]
assert path not in paths, path
#print("add link", path, link)
paths.add(path)
item = LinkItem(link, path, persistent)
self.mounts[link] = item
return item
@lockmethod
def unmount(self, cell_or_link, from_del=False):
assert not is_dummy_mount(cell_or_link._mount), cell_or_link
root = cell_or_link._root()
if from_del and (cell_or_link not in self.mounts or root not in self.paths):
return
mountitem = self.mounts.pop(cell_or_link)
if not mountitem._destroyed:
paths = self.paths[root]
path = cell_or_link._mount["path"]
paths.discard(path)
mountitem.destroy()
@lockmethod
def unmount_context(self, context, from_del=False):
if context in self.contexts:
self.contexts.remove(context)
elif not from_del:
return
mount = context._mount
if context._root() is context:
self.paths.pop(context, None)
if mount is None:
return
#print("unmount context", context)
assert not is_dummy_mount(mount), context
try:
paths = self.paths[context._root()]
except KeyError:
if not from_del:
return
paths = set()
try:
paths.remove(mount["path"])
except KeyError:
pass
if mount["persistent"] == False:
dirpath = mount["path"].replace("/", os.sep)
try:
#print("rmdir", dirpath)
os.rmdir(dirpath)
except:
print("Error: cannot remove directory %s" % dirpath)
@lockmethod
def add_context(self, context, path, as_parent):
#print("add context", path, context, as_parent, context._mount["persistent"])
paths = self.paths[context._root()]
if not as_parent:
if context not in self.contexts:
assert path not in paths, path
paths.add(path)
self.contexts.add(context)
else:
if path in paths:
assert context in self.contexts, (path, context)
def _check_context(self, context, as_parent):
mount = context._mount
assert not is_dummy_mount(mount), context
dirpath = mount["path"].replace("/", os.sep)
#.........这里部分代码省略.........
示例12: HealthMonitor
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class HealthMonitor(object):
"""
Monitors whether a particular host is marked as up or down.
This class is primarily intended for internal use, although
applications may find it useful to check whether a given node
is up or down.
"""
is_up = True
"""
A boolean representing the current state of the node.
"""
def __init__(self, conviction_policy):
self._conviction_policy = conviction_policy
self._host = conviction_policy.host
# self._listeners will hold, among other things, references to
# Cluster objects. To allow those to be GC'ed (and shutdown) even
# though we've implemented __del__, use weak references.
self._listeners = WeakSet()
self._lock = RLock()
def register(self, listener):
with self._lock:
self._listeners.add(listener)
def unregister(self, listener):
with self._lock:
self._listeners.remove(listener)
def set_up(self):
if self.is_up:
return
self._conviction_policy.reset()
log.info("Host %s is considered up", self._host)
with self._lock:
listeners = self._listeners.copy()
for listener in listeners:
listener.on_up(self._host)
self.is_up = True
def set_down(self):
if not self.is_up:
return
self.is_up = False
log.info("Host %s is considered down", self._host)
with self._lock:
listeners = self._listeners.copy()
for listener in listeners:
listener.on_down(self._host)
def reset(self):
return self.set_up()
def signal_connection_failure(self, connection_exc):
is_down = self._conviction_policy.add_failure(connection_exc)
if is_down:
self.set_down()
return is_down
示例13: TestWeakSet
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
#.........这里部分代码省略.........
pl, ql, rl = map(lambda s: [SomeClass(c) for c in s], ['ab', 'abcde', 'def'])
p, q, r = map(WeakSet, (pl, ql, rl))
self.assertTrue(p < q)
self.assertTrue(p <= q)
self.assertTrue(q <= q)
self.assertTrue(q > p)
self.assertTrue(q >= p)
self.assertFalse(q < r)
self.assertFalse(q <= r)
self.assertFalse(q > r)
self.assertFalse(q >= r)
self.assertTrue(set('a').issubset('abc'))
self.assertTrue(set('abc').issuperset('a'))
self.assertFalse(set('a').issubset('cbs'))
self.assertFalse(set('cbs').issuperset('a'))
def test_gc(self):
# Create a nest of cycles to exercise overall ref count check
s = WeakSet(Foo() for i in range(1000))
for elem in s:
elem.cycle = s
elem.sub = elem
elem.set = WeakSet([elem])
def test_subclass_with_custom_hash(self):
# Bug #1257731
class H(WeakSet):
def __hash__(self):
return int(id(self) & 0x7fffffff)
s=H()
f=set()
f.add(s)
self.assertIn(s, f)
f.remove(s)
f.add(s)
f.discard(s)
def test_init(self):
s = WeakSet()
s.__init__(self.items)
self.assertEqual(s, self.s)
s.__init__(self.items2)
self.assertEqual(s, WeakSet(self.items2))
self.assertRaises(TypeError, s.__init__, s, 2);
self.assertRaises(TypeError, s.__init__, 1);
def test_constructor_identity(self):
s = WeakSet(self.items)
t = WeakSet(s)
self.assertNotEqual(id(s), id(t))
def test_hash(self):
self.assertRaises(TypeError, hash, self.s)
def test_clear(self):
self.s.clear()
self.assertEqual(self.s, WeakSet([]))
self.assertEqual(len(self.s), 0)
def test_copy(self):
dup = self.s.copy()
self.assertEqual(self.s, dup)
self.assertNotEqual(id(self.s), id(dup))
def test_add(self):
x = SomeClass('Q')
示例14: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class Signal(object):
""" class for signal slot concept
Example
-------
A simple example for a callback is
>>> event = Signal()
>>> event.connect(mfunc)
>>> # raise the signal
>>> event("hello")
>>>
>>> # functions can be disconnected
>>> even.disconnect(myfunc)
Since weak references are used, care has to be taken with object functions
>>> obj = MyClass()
>>> event.connect(obj.myfunc) # works
>>> event.connect(MyClass().myfunc) # will not work
The second example for member functions will not work since the Signal class
uses weakref and therefore does not increase the reference counter. MyClass()
only exists for the time of the function call and will be deleted afterwards
and the weakref will become invalid.
"""
def __init__(self):
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
def __call__(self, *args, **kargs):
""" raise the event """
# 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):
""" connect a function / member function to the signal """
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):
""" disconnect a function from the signal """
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):
""" remove all callbacks from the signal """
self._functions.clear()
self._methods.clear()
示例15: Signal
# 需要导入模块: from weakref import WeakSet [as 别名]
# 或者: from weakref.WeakSet import remove [as 别名]
class Signal(object):
"""Signal/slot implementation.
Author: Thiago Marcos P. Santos
Author: Christopher S. Case
Author: David H. Bronke
Created: August 28, 2008
Updated: December 12, 2011
License: MIT
Sample usage:
\code
class Model(object):
def __init__(self, value):
self.__value = value
self.changed = Signal()
def set_value(self, value):
self.__value = value
self.changed() # Emit signal
def get_value(self):
return self.__value
class View(object):
def __init__(self, model):
self.model = model
model.changed.connect(self.model_changed)
def model_changed(self):
print(" New value:", self.model.get_value())
print("Beginning Tests:")
model = Model(10)
view1 = View(model)
view2 = View(model)
view3 = View(model)
print("Setting value to 20...")
model.set_value(20)
print("Deleting a view, and setting value to 30...")
del view1
model.set_value(30)
print("Clearing all listeners, and setting value to 40...")
model.changed.clear()
model.set_value(40)
print("Testing non-member function...")
def bar():
print(" Calling Non Class Function!")
model.changed.connect(bar)
model.set_value(50)
\endcode
"""
def __init__(self):
"""Initialize a new signal"""
self._functions = WeakSet()
self._methods = WeakKeyDictionary()
def __call__(self, *args, **kargs):
"""Emits the signal and calls all connections"""
# 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):
"""Connects a slot to the signal so that when the signal is emitted, the slot is called."""
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):
"""Disconnects a slot from the signal"""
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):
"""Removes all slots from the signal"""
self._functions.clear()
self._methods.clear()