• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python weakref.WeakSet类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中weakref.WeakSet的典型用法代码示例。如果您正苦于以下问题:Python WeakSet类的具体用法?Python WeakSet怎么用?Python WeakSet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了WeakSet类的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: take_damage

 def take_damage(self, amount):
     self.damage += amount
     if self.damage >= self.health and not self.has_exploded:
         # create an explosion
         self.has_exploded = True
         Explosion(self._body.position, BLOCK_SIZE,
                   velocity=self._body.velocity)
         # remove joints
         for block in self._adjacent_blocks:
             toremove = self._joints & block._joints
             for joint in toremove:
                 block._joints.remove(joint)
         SPACE.remove(*self._joints)
         self._joints = WeakSet()
         # remove ties to the construction
         for block in self._adjacent_blocks:
             block._adjacent_blocks.remove(self)
         self._adjacent_blocks = WeakSet()
     elif self.damage >= self.health * 2:
         Explosion(self._body.position, BLOCK_SIZE,
                   velocity=self._body.velocity)
         for i in range(random.randint(1,5)):
             Resource(self)
         SPACE.remove(self._body, self._shape)
         SPACE.blocks.remove(self)
         if self in SPACE.controllable_blocks:
             SPACE.controllable_blocks.remove(self)
         if self in SPACE.controller_blocks:
             SPACE.controller_blocks.remove(self)
开发者ID:mappy13,项目名称:nihil-ace,代码行数:29,代码来源:blocks.py


示例3: BaseSubject

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
开发者ID:waawal,项目名称:dirigent,代码行数:35,代码来源:basesubject.py


示例4: ConnectionFactory

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()
开发者ID:kxz,项目名称:omnipresence,代码行数:34,代码来源:connection.py


示例5: Signal

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)
开发者ID:BaxterTU2014,项目名称:baxter_interface,代码行数:28,代码来源:signals.py


示例6: _setup

 def _setup(self):
     self.children = WeakSet()
     self.daemon_children = WeakSet()
     self.exception = None
     self.tb_list = None
     self.stack_list = None
     self.except_func = None
     self.finally_func = None
开发者ID:boto,项目名称:botoflow,代码行数:8,代码来源:async_task_context.py


示例7: test_init

 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);
开发者ID:Stewori,项目名称:jython,代码行数:8,代码来源:test_weakset.py


示例8: reset

 def reset(self):
     for call in self.calls:
         if call.active():
             call.cancel()
     for loop in self.loops:
         if loop.running:
             loop.stop()
     self.calls = WeakSet()
     self.loops = WeakSet()
开发者ID:Colorpinpoint,项目名称:pysnip,代码行数:9,代码来源:scheduler.py


示例9: setUp

 def setUp(self):
     # need to keep references to them
     self.items = [SomeClass(c) for c in ('a', 'b', 'c')]
     self.items2 = [SomeClass(c) for c in ('x', 'y', 'z')]
     self.letters = [SomeClass(c) for c in string.ascii_letters]
     self.s = WeakSet(self.items)
     self.d = dict.fromkeys(self.items)
     self.obj = SomeClass('F')
     self.fs = WeakSet([self.obj])
开发者ID:89sos98,项目名称:main,代码行数:9,代码来源:test_weakset.py


示例10: __init__

    def __init__(self, **kwargs):
        self.__functions = WeakSet()
        self.__methods = WeakKeyDictionary()
        self.__signals = WeakSet()
        self.__type = kwargs.get("type", Signal.Auto)

        self.__emitting = False
        self.__connect_queue = []
        self.__disconnect_queue = []
开发者ID:TimurAykutYildirim,项目名称:Uranium,代码行数:9,代码来源:Signal.py


示例11: subscribe

 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)
开发者ID:iwschris,项目名称:ezodf2,代码行数:10,代码来源:observer.py


示例12: __init__

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)
开发者ID:Polatrite,项目名称:atria,代码行数:53,代码来源:channels.py


示例13: test_len

 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)
开发者ID:serg0987,项目名称:python,代码行数:12,代码来源:test_weakfer.py


示例14: Subject

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)
开发者ID:bionikspoon,项目名称:python-design-patterns,代码行数:13,代码来源:observer_pattern.py


示例15: LazyResult

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
开发者ID:chrisalice,项目名称:gittools,代码行数:51,代码来源:lazy.py


示例16: Environments

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)
开发者ID:odoousers2014,项目名称:odoo,代码行数:14,代码来源:api.py


示例17: test_weak_destroy_and_mutate_while_iterating

    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)
开发者ID:Stewori,项目名称:jython,代码行数:33,代码来源:test_weakset.py


示例18: test_intersection

 def test_intersection(self):
     s = WeakSet(self.letters)
     i = s.intersection(self.items2)
     for c in self.letters:
         self.assertEqual(c in i, c in self.items2 and c in self.letters)
     self.assertEqual(s, WeakSet(self.letters))
     self.assertEqual(type(i), WeakSet)
     for C in set, frozenset, dict.fromkeys, list, tuple:
         x = WeakSet([])
         self.assertEqual(i.intersection(C(self.items)), x)
     self.assertEqual(len(i), len(self.items2))
     self.items2.pop()
     test_support.gc_collect()
     self.assertEqual(len(list(i)), len(list(self.items2)))
开发者ID:Stewori,项目名称:jython,代码行数:14,代码来源:test_weakset.py


示例19: 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


示例20: setUp

 def setUp(self):
     # need to keep references to them
     self.items = [ustr(c) for c in ('a', 'b', 'c')]
     self.items2 = [ustr(c) for c in ('x', 'y', 'z')]
     self.ab_items = [ustr(c) for c in 'ab']
     self.abcde_items = [ustr(c) for c in 'abcde']
     self.def_items = [ustr(c) for c in 'def']
     self.ab_weakset = WeakSet(self.ab_items)
     self.abcde_weakset = WeakSet(self.abcde_items)
     self.def_weakset = WeakSet(self.def_items)
     self.letters = [ustr(c) for c in string.ascii_letters]
     self.s = WeakSet(self.items)
     self.d = dict.fromkeys(self.items)
     self.obj = ustr('F')
     self.fs = WeakSet([self.obj])
开发者ID:0jpq0,项目名称:kbengine,代码行数:15,代码来源:test_weakset.py



注:本文中的weakref.WeakSet类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python weakref.WeakValueDictionary类代码示例发布时间:2022-05-26
下一篇:
Python weakref.WeakKeyDictionary类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap