当前位置: 首页>>代码示例>>Python>>正文


Python WeakKeyDictionary.clear方法代码示例

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


在下文中一共展示了WeakKeyDictionary.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: FrameRegistry

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
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,代码行数:30,代码来源:specter.py

示例2: LazyInvalidation

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
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,代码行数:33,代码来源:lazy.py

示例3: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [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)
开发者ID:pathmann,项目名称:pyTSon,代码行数:59,代码来源:signalslot.py

示例4: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [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
开发者ID:ElricleNecro,项目名称:LISA,代码行数:56,代码来源:Signals.py

示例5: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [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()
开发者ID:dhomeier,项目名称:specview,代码行数:56,代码来源:signal_slot.py

示例6: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
class Signal(object):
    def __init__(self):
        # The original implementation used WeakSet to store functions,
        # but that causes lambdas without any other reference to be
        # garbage collected. So we use a normal set to avoid that.
        self._functions = set()
        self._methods = WeakKeyDictionary()

    # The original implementation used __call__, so one would just call the signal itself:
    #
    # my_signal("foo")
    #
    # This has been changed to the emit() method to both be more consistent with how signals/slots
    # work in Qt & GTK and to make it more easily apparent that a signal is being triggered.
    # The correct way to trigger a signal is therefore:
    #
    # my_signal.emit("foo")
    def emit(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()
开发者ID:rvykydal,项目名称:anaconda,代码行数:50,代码来源:signal.py

示例7: SIGNAL

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [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()
开发者ID:charlesdoutriaux,项目名称:uvcdat-devel,代码行数:40,代码来源:ConfigurationFunctions.py

示例8: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [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()
开发者ID:kittykat,项目名称:hotdoc,代码行数:40,代码来源:simple_signals.py

示例9: BaseResultConsumer

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
class BaseResultConsumer(object):

    def __init__(self, backend, app, accept,
                 pending_results, weak_pending_results,
                 pending_messages):
        self.backend = backend
        self.app = app
        self.accept = accept
        self._pending_results = pending_results
        self._weak_pending_results = weak_pending_results
        self._pending_messages = pending_messages
        self.on_message = None
        self.buckets = WeakKeyDictionary()
        self.drainer = drainers[detect_environment()](self)

    def start(self):
        raise NotImplementedError()

    def stop(self):
        pass

    def drain_events(self, timeout=None):
        raise NotImplementedError()

    def consume_from(self, task_id):
        raise NotImplementedError()

    def cancel_for(self, task_id):
        raise NotImplementedError()

    def _after_fork(self):
        self.buckets.clear()
        self.buckets = WeakKeyDictionary()
        self.on_message = None
        self.on_after_fork()

    def on_after_fork(self):
        pass

    def drain_events_until(self, p, timeout=None, on_interval=None):
        return self.drainer.drain_events_until(
            p, timeout=timeout, on_interval=on_interval)

    def _wait_for_pending(self, result,
                          timeout=None, on_interval=None, on_message=None,
                          **kwargs):
        self.on_wait_for_pending(result, timeout=timeout, **kwargs)
        prev_on_m, self.on_message = self.on_message, on_message
        try:
            for _ in self.drain_events_until(
                    result.on_ready, timeout=timeout,
                    on_interval=on_interval):
                yield
                sleep(0)
        except socket.timeout:
            raise TimeoutError('The operation timed out.')
        finally:
            self.on_message = prev_on_m

    def on_wait_for_pending(self, result, timeout=None, **kwargs):
        pass

    def on_out_of_band_result(self, message):
        self.on_state_change(message.payload, message)

    def on_state_change(self, meta, message):
        if self.on_message:
            self.on_message(meta)
        if meta['status'] in states.READY_STATES:
            task_id = meta['task_id']
            try:
                result = self._pending_results[task_id]
            except KeyError:
                try:
                    result = self._weak_pending_results[task_id]
                except KeyError:
                    # send to BufferMapping
                    self._pending_messages.append(task_id, meta)
            result._maybe_set_cache(meta)
            buckets = self.buckets
            try:
                buckets.pop(result)
            except KeyError:
                pass
        sleep(0)
开发者ID:lican09,项目名称:celery,代码行数:87,代码来源:async.py

示例10: BaseResultConsumer

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
class BaseResultConsumer(object):
    """Manager responsible for consuming result messages."""

    def __init__(self, backend, app, accept,
                 pending_results, pending_messages):
        self.backend = backend
        self.app = app
        self.accept = accept
        self._pending_results = pending_results
        self._pending_messages = pending_messages
        self.on_message = None
        self.buckets = WeakKeyDictionary()
        self.drainer = drainers[detect_environment()](self)

    def start(self, initial_task_id, **kwargs):
        raise NotImplementedError()

    def stop(self):
        pass

    def drain_events(self, timeout=None):
        raise NotImplementedError()

    def consume_from(self, task_id):
        raise NotImplementedError()

    def cancel_for(self, task_id):
        raise NotImplementedError()

    def _after_fork(self):
        self.buckets.clear()
        self.buckets = WeakKeyDictionary()
        self.on_message = None
        self.on_after_fork()

    def on_after_fork(self):
        pass

    def drain_events_until(self, p, timeout=None, on_interval=None):
        return self.drainer.drain_events_until(
            p, timeout=timeout, on_interval=on_interval)

    def _wait_for_pending(self, result,
                          timeout=None, on_interval=None, on_message=None,
                          **kwargs):
        self.on_wait_for_pending(result, timeout=timeout, **kwargs)
        prev_on_m, self.on_message = self.on_message, on_message
        try:
            for _ in self.drain_events_until(
                    result.on_ready, timeout=timeout,
                    on_interval=on_interval):
                yield
                sleep(0)
        except socket.timeout:
            raise TimeoutError('The operation timed out.')
        finally:
            self.on_message = prev_on_m

    def on_wait_for_pending(self, result, timeout=None, **kwargs):
        pass

    def on_out_of_band_result(self, message):
        self.on_state_change(message.payload, message)

    def _get_pending_result(self, task_id):
        for mapping in self._pending_results:
            try:
                return mapping[task_id]
            except KeyError:
                pass
        raise KeyError(task_id)

    def on_state_change(self, meta, message):
        if self.on_message:
            self.on_message(meta)
        if meta['status'] in states.READY_STATES:
            task_id = meta['task_id']
            try:
                result = self._get_pending_result(task_id)
            except KeyError:
                # send to buffer in case we received this result
                # before it was added to _pending_results.
                self._pending_messages.put(task_id, meta)
            else:
                result._maybe_set_cache(meta)
                buckets = self.buckets
                try:
                    # remove bucket for this result, since it's fulfilled
                    bucket = buckets.pop(result)
                except KeyError:
                    pass
                else:
                    # send to waiter via bucket
                    bucket.append(result)
        sleep(0)
开发者ID:2216288075,项目名称:meiduo_project,代码行数:97,代码来源:asynchronous.py

示例11: Single_Dispatch

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]

#.........这里部分代码省略.........
        ### `functools.wraps` fails to transfer `__doc__`
        self.__doc__  = getattr (func, "__doc__", None)
    # end def __init__

    def __call__ (self, * args, ** kw) :
        try :
            da = args [self.dispatch_on]
        except IndexError as exc :
            raise TypeError \
                ( "Function %r needs at least %s positional arguments; "
                  "got %s: %s, %s"
                % ( self.top_func.__name__
                  , self.dispatch_on + 1
                  , len (args), args, kw
                  )
                )
        func = self.dispatch (da.__class__)
        return func (* args, ** kw)
    # end def __call__

    def add_type (self, * Types, ** kw) :
        """Add implementations for `Types`"""
        func = kw.pop ("func", None)
        if func is None :
            return lambda func : self.add_type (* Types, func = func)
        else :
            registry = self.registry
            _derived = self._derived
            for T in Types :
                if T in registry and not T in _derived :
                    raise TypeError \
                        ( "Duplicate implementation for function %r for type %r"
                        % (self.top_func.__name__, T.__name__)
                        )
            return self._add_types (func, Types)
    # end def add_type

    def derived (self) :
        """Return a derived generic function with a copy of the dispatch table"""
        result          = self.__class__ \
            (self.top_func, self.top_type, self.dispatch_on)
        result.registry = dict (self.registry)
        result._derived = set  (self.registry)
        return result
    # end def derived

    def dispatch (self, T) :
        """Return the function implementation matching type `T`."""
        try :
            result = self.cache [T]
        except KeyError :
            try :
                result = self.registry [T]
            except KeyError :
                result = self.registry [self._best_match (T)]
            self.cache [T] = result
        return result
    # end def dispatch

    def override_type (self, * Types, ** kw) :
        """Add implementations for `Types`,
           overriding existing implementations, if any.
        """
        func = kw.pop ("func", None)
        if func is None :
            return lambda func : self.override_type (* Types, func = func)
        else :
            return self._add_types (func, Types)
    # end def override_type

    def _add_types (self, func, Types) :
        if __debug__ :
            try :
                top_name = getattr (self.top_func, "__name__")
                add_name = getattr (func, "__name__")
            except AttributeError :
                pass
            else :
                if top_name == add_name :
                    raise TypeError \
                        ( "Name clash; specify a different name for %s "
                          "to avoid shadowing of generic function %s"
                        % (func, self.top_func)
                        )
        registry = self.registry
        _derived = self._derived
        for T in Types :
            registry [T] = func
            _derived.discard (T)
        self.cache.clear ()
        ### needs to return `func` to allow decorator chaining
        return func
    # end def _add_types

    def _best_match (self, T) :
        registry = self.registry
        matches  = tuple (b for b in T.__mro__ [1:] if b in registry)
        if not matches :
            raise TypeError ("No match for argument type %s" % (T, ))
        return matches [0]
开发者ID:Tapyr,项目名称:tapyr,代码行数:104,代码来源:Single_Dispatch.py

示例12: emit

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
class Signal:
    ##  Signal types.
    #   These indicate the type of a signal, that is, how the signal handles calling the connected
    #   slots. 
    #   - Direct connections immediately call the connected slots from the thread that called emit(). 
    #   - Auto connections will push the call onto the event loop if the current thread is
    #     not the main thread, but make a direct call if it is. 
    #   - Queued connections will always push
    #     the call on to the event loop.
    Direct = 1
    Auto = 2
    Queued = 3

    ##  Initialize the instance.
    #
    #   \param kwargs Keyword arguments.
    #                 Possible keywords:
    #                 - type: The signal type. Defaults to Direct.
    def __init__(self, **kwargs):
        self.__functions = WeakSet()
        self.__methods = WeakKeyDictionary()
        self.__signals = WeakSet()
        self.__type = kwargs.get("type", Signal.Auto)
    
    ##  \exception NotImplementedError
    def __call__(self):
        raise NotImplementedError("Call emit() to emit a signal")
    
    ##  Get type of the signal
    #   \return \type{int} Direct(1), Auto(2) or Queued(3)
    def getType(self):
        return self.__type

    ##  Emit the signal which indirectly calls all of the connected slots.
    #
    #   \param args The positional arguments to pass along.
    #   \param kargs The keyword arguments to pass along.
    #
    #   \note If the Signal type is Queued and this is not called from the application thread
    #   the call will be posted as an event to the application main thread, which means the
    #   function will be called on the next application event loop tick.
    def emit(self, *args, **kargs):
        try:
            if self.__type == Signal.Queued:
                Signal._app.functionEvent(CallFunctionEvent(self.emit, args, kargs))
                return

            if self.__type == Signal.Auto:
                if threading.current_thread() is not Signal._app.getMainThread():
                    Signal._app.functionEvent(CallFunctionEvent(self.emit, args, kargs))
                    return
        except AttributeError: # If Signal._app is not set
            return

        # Call handler functions
        for func in self.__functions:
            func(*args, **kargs)

        # Call handler methods
        for dest, funcs in self.__methods.items():
            for func in funcs:
                func(dest, *args, **kargs)

        # Emit connected signals
        for signal in self.__signals:
            signal.emit(*args, **kargs)

    ##  Connect to this signal.
    #   \param connector The signal or slot (function) to connect.
    def connect(self, connector):
        if type(connector) == Signal:
            if connector == self:
                return
            self.__signals.add(connector)
        elif inspect.ismethod(connector):
            if connector.__self__ not in self.__methods:
                self.__methods[connector.__self__] = set()

            self.__methods[connector.__self__].add(connector.__func__)
        else:
            self.__functions.add(connector)

    ##  Disconnect from this signal.
    #   \param connector The signal or slot (function) to disconnect.
    def disconnect(self, connector):
        try:
            if connector in self.__signals:
                self.__signals.remove(connector)
            elif inspect.ismethod(connector) and connector.__self__ in self.__methods:
                self.__methods[connector.__self__].remove(connector.__func__)
            else:
                if connector in self.__functions:
                    self.__functions.remove(connector)

        except KeyError: #Ignore errors when connector is not connected to this signal.
            pass

    ##  Disconnect all connected slots.
    def disconnectAll(self):
        self.__functions.clear()
#.........这里部分代码省略.........
开发者ID:derekhe,项目名称:Uranium,代码行数:103,代码来源:Signal.py

示例13: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
class Signal(object):
    """
    The Signalling class
    """
    def __init__(self, optimized=False):
        self._functions = WeakSet()
        self._after_functions = WeakSet()
        self._methods = WeakKeyDictionary()
        self._after_methods = WeakKeyDictionary()
        self._optimized = optimized

    def __call__(self, *args, **kargs):
        res_list = []
        # Call handler functions
        for func in self._functions:
            res = func(*args, **kargs)
            if res and self._optimized:
                return res
            res_list.append(res)

        # Call handler methods
        for obj, funcs in self._methods.items():
            for func in funcs:
                res = func(obj, *args, **kargs)
                if res and self._optimized:
                    return res
                res_list.append(res)

        for func in self._after_functions:
            res = func(*args, **kargs)
            if res and self._optimized:
                return res
            res_list.append(res)

        # Call handler methods
        for obj, funcs in self._after_methods.items():
            for func in funcs:
                res = func(obj, *args, **kargs)
                if res and self._optimized:
                    return res
                res_list.append(res)

        if self._optimized:
            return None

        return res_list

    def connect(self, slot):
        """
        @slot: The method to be called on signal emission

        Connects to @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 connect_after(self, slot):
        """
        @slot: The method to be called at last stage of signal emission

        Connects to the signal after the signals has been handled by other
        connect callbacks.
        """
        if inspect.ismethod(slot):
            if slot.__self__ not in self._after_methods:
                self._after_methods[slot.__self__] = set()

            self._after_methods[slot.__self__].add(slot.__func__)

        else:
            self._after_functions.add(slot)

    def disconnect(self, slot):
        """
        Disconnect @slot from the signal
        """
        if inspect.ismethod(slot):
            if slot.__self__ in self._methods:
                self._methods[slot.__self__].remove(slot.__func__)
            elif slot.__self__ in self._after_methods:
                self._after_methods[slot.__self__].remove(slot.__func__)
        else:
            if slot in self._functions:
                self._functions.remove(slot)
            elif slot in self._after_functions:
                self._after_functions.remove(slot)

    def clear(self):
        """
        Cleanup the signal
        """
        self._functions.clear()
        self._methods.clear()
        self._after_functions.clear()
#.........这里部分代码省略.........
开发者ID:gdesmott,项目名称:hotdoc,代码行数:103,代码来源:simple_signals.py

示例14: clear

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [as 别名]
 def clear(self):
     WeakKeyDictionary.clear( self)
     self.doCallbacks('clear', None, None)        
开发者ID:bcorfman,项目名称:pug,代码行数:5,代码来源:CallbackWeakKeyDictionary.py

示例15: Signal

# 需要导入模块: from weakref import WeakKeyDictionary [as 别名]
# 或者: from weakref.WeakKeyDictionary import clear [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()
开发者ID:PennPanda,项目名称:libbot2,代码行数:101,代码来源:signal_slot.py


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