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

Python weakref.weakref函数代码示例

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

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



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

示例1: __init__

 def __init__(self, channel, level, msg, args=None, kwargs=None,
              exc_info=None, extra=None, frame=None, dispatcher=None):
     #: the name of the logger that created it or any other textual
     #: channel description.  This is a descriptive name and should not
     #: be used for filtering.  A log record might have a
     #: :attr:`dispatcher` defined which provides more information for
     #: filtering if this is absolutely necessary.
     self.channel = channel
     #: The message of the log record as new-style format string.
     self.msg = msg
     #: the positional arguments for the format string.
     self.args = args or ()
     #: the keyword arguments for the format string.
     self.kwargs = kwargs or {}
     #: the level of the log record as integer.
     self.level = level
     #: optional exception information.  If set, this is a tuple in the
     #: form ``(exc_type, exc_value, tb)`` as returned by
     #: :func:`sys.exc_info`.
     self.exc_info = exc_info
     #: optional extra information as dictionary.  This is the place
     #: where custom log processors can attach custom context sensitive
     #: data.
     self.extra = ExtraDict(extra or ())
     #: If available, optionally the interpreter frame that created the
     #: log record.  Might not be available for all calls and is removed
     #: when the log record is closed.
     self.frame = frame
     #: the PID of the current process
     self.process = os.getpid()
     if dispatcher is not None:
         dispatcher = weakref(dispatcher)
     self._dispatcher = dispatcher
开发者ID:amarcp,项目名称:logbook,代码行数:33,代码来源:base.py


示例2: __init__

    def __init__(self, ayum):
        self.repos = {} # list of repos by repoid pointing a repo object 
                        # of repo options/misc data
        self.callback = None # progress callback used for populateSack() for importing the xml files
        self.cache = 0
        self.pkgSack = MetaSack()
        self.logger = logging.getLogger("yum.RepoStorage")

        self._setup = False

        self.ayum = weakref(ayum)
        # callbacks for handling gpg key imports for repomd.xml sig checks
        # need to be set from outside of the repos object to do anything
        # even quasi-useful
        # defaults to what is probably sane-ish
        self.gpg_import_func = _wrap_ayum_getKeyForRepo(ayum)
        self.gpgca_import_func = _wrap_ayum_getKeyForRepo(ayum, ca=True)
        self.confirm_func = None

        # This allow listEnabled() to be O(1) most of the time.
        self._cache_enabled_repos = []
        self.quick_enable_disable = {}

        #  This allows plugins to setup a repo. just before the first
        # listEnabled() call.
        self._list_enabled_hasrun = False
开发者ID:pnasrat,项目名称:yum,代码行数:26,代码来源:repos.py


示例3: __init__

    def __init__(self, *args, **kwargs):
        super(Kannel, self).__init__(*args, **kwargs)

        reference = weakref(self)

        # set up event handler for incoming messages
        def on_incoming(sender=None, request=None, response=None, **kwargs):
            transport = reference()
            if transport is not None:
                body, status_code = transport.handle(request)
                response.write(body)
                response.status_code = status_code

        kannel_event.connect(on_incoming, sender=self.name, weak=False)
        del on_incoming

        # set up event handler for outgoing messages
        def on_outgoing(sender=None, instance=None, created=False, **kwargs):
            transport = reference()
            if transport is not None:
                if created is True and instance.transport == transport.name:
                    transport.send(instance)

        signals.post_save.connect(on_outgoing, sender=Outgoing, weak=False)
        del on_outgoing
开发者ID:nicpottier,项目名称:ugandasms,代码行数:25,代码来源:transports.py


示例4: __init__

    def __init__(self, treeConfig: TreeConfig, nameTuple: Tuple[str, ...], description: str,
                 msgArgsInfo: ArgsInfo, parent: Topic = None):
        """
        Create a topic. Should only be called by TopicManager via its
        getOrCreateTopic() method (which gets called in several places
        in pubsub, such as sendMessage, subscribe, and newTopic).

        :param treeConfig: topic tree configuration settings
        :param nameTuple: topic name, in tuple format (no dots)
        :param description: "docstring" for topic
        :param ArgsInfo msgArgsInfo: object that defines MDS for topic
        :param parent: parent of topic

        :raises ValueError: invalid topic name
        """
        if parent is None:
            if nameTuple != (ALL_TOPICS,):
                msg = 'Only one topic, named %s, can be root of topic tree'
                raise ValueError(msg % 'pub.ALL_TOPICS')
        else:
            validateName(nameTuple)
        self.__tupleName = nameTuple

        self.__handlingUncaughtListenerExc = False
        self._treeConfig = treeConfig

        self.__validator = None
        # Registered listeners were originally kept in a Python list; however
        # a few methods require lookup of the Listener for the given callable,
        # which is an O(n) operation. A set() could have been more suitable but
        # there is no way of retrieving an element from a set without iterating
        # over the set, again an O(n) operation. A dict() is ok too. Because
        # Listener.__eq__(callable) returns true if the Listener instance wraps
        # the given callable, and because Listener.__hash__ produces the hash
        # value of the wrapped callable, calling dict[callable] on a
        # dict(Listener -> Listener) mapping will be O(1) in most cases:
        # the dict will take the callables hash, find the list of Listeners that
        # have that hash, and then iterate over that inner list to find the
        # Listener instance which satisfies Listener == callable, and will return
        # the Listener.
        self.__listeners = dict()

        # specification:
        self.__description = None
        self.setDescription(description)
        self.__msgArgs = msgArgsInfo
        if msgArgsInfo.isComplete():
            self.__finalize()
        else:
            assert not self._treeConfig.raiseOnTopicUnspecified

        # now that we know the args are fine, we can link to parent
        self.__parentTopic = None
        self.__subTopics = {}
        if parent is None:
            assert self.hasMDS()
        else:
            self.__parentTopic = weakref(parent)
            assert self.__msgArgs.parentAI() is parent.__msgArgs
            parent.__adoptSubtopic(self)
开发者ID:schollii,项目名称:pypubsub,代码行数:60,代码来源:topicobj.py


示例5: __init__

    def __init__(self, *args, **kwargs):
        super(HTTP, self).__init__(*args, **kwargs)

        reference = weakref(self)

        # set up event handler for incoming messages
        def on_incoming(sender=None, name=None, request=None, response=None, **kwargs):
            transport = reference()
            if transport is not None and name == transport.name:
                body, status_code = transport.handle(request)
                response.write(body)
                response.status_code = status_code

        http_event.connect(on_incoming, weak=False)
        del on_incoming

        # set up event handler for outgoing messages
        def on_outgoing(sender=None, instance=None, created=False, **kwargs):
            transport = reference()
            if transport is not None:
                if created is True and instance.connection.transport == transport.name:
                    try:
                        suppress = instance.in_response_to.message.suppress_responses
                    except:
                        pass
                    else:
                        if suppress:
                            return
                    
                    transport.send(instance)

        signals.post_save.connect(on_outgoing, sender=Outgoing, weak=False)
        del on_outgoing
开发者ID:djangosms,项目名称:core,代码行数:33,代码来源:transports.py


示例6: __init__

    def __init__(self, history, row):
        self._history = weakref(history)

        self.tid              = row[0]
        self.beg_timestamp    = row[1]
        self.beg_rpmdbversion = row[2]
        self.end_timestamp    = row[3]
        self.end_rpmdbversion = row[4]
        self.loginuid         = row[5]
        self.return_code      = row[6]

        self._loaded_TW = None
        self._loaded_TD = None
        self._loaded_TS = None

        self._loaded_PROB = None

        self._have_loaded_CMD = False # cmdline can validly be None
        self._loaded_CMD = None

        self._loaded_ER = None
        self._loaded_OT = None

        self.altered_lt_rpmdb = None
        self.altered_gt_rpmdb = None
开发者ID:lucchouina,项目名称:RimRoot_Fedora_15_armv5,代码行数:25,代码来源:history.py


示例7: __init__

 def __init__(self, channel, level, msg, args=None, kwargs=None,
              exc_info=None, extra=None, frame=None, dispatcher=None):
     #: the name of the logger that created it or any other textual
     #: channel description.  This is a descriptive name and can be
     #: used for filtering.
     self.channel = channel
     #: The message of the log record as new-style format string.
     self.msg = msg
     #: the positional arguments for the format string.
     self.args = args or ()
     #: the keyword arguments for the format string.
     self.kwargs = kwargs or {}
     #: the level of the log record as integer.
     self.level = level
     #: optional exception information.  If set, this is a tuple in the
     #: form ``(exc_type, exc_value, tb)`` as returned by
     #: :func:`sys.exc_info`.
     #: This parameter can also be ``True``, which would cause the exception info tuple
     #: to be fetched for you.
     self.exc_info = exc_info
     #: optional extra information as dictionary.  This is the place
     #: where custom log processors can attach custom context sensitive
     #: data.
     self.extra = ExtraDict(extra or ())
     #: If available, optionally the interpreter frame that pulled the
     #: heavy init.  This usually points to somewhere in the dispatcher.
     #: Might not be available for all calls and is removed when the log
     #: record is closed.
     self.frame = frame
     #: the PID of the current process
     self.process = None
     if dispatcher is not None:
         dispatcher = weakref(dispatcher)
     self._dispatcher = dispatcher
开发者ID:aswizzl,项目名称:luckybomb,代码行数:34,代码来源:base.py


示例8: __init__

	def __init__(s, debug_name, debug_locals):
		super().__init__()
		s.debug_name = debug_name
		s.debug_locals = weakref(debug_locals) if debug_locals != None else None
		if debug_locals != None:
			s.kbdbg_name = debug_locals.kbdbg_frame
		s.kbdbg_name += "_" + urllib.parse.quote_plus(debug_name)
开发者ID:koo5,项目名称:new_shit,代码行数:7,代码来源:pyin.py


示例9: __init__

 def __init__(self, source, extra_params, record):
     self.source = source
     self.extra_params = extra_params
     self.__record = weakref(record) if record is not None else lambda: None
     self.__cached_for_ctx = None
     self.__html = None
     self.__meta = None
开发者ID:fschulze,项目名称:lektor-rst,代码行数:7,代码来源:lektor_rst.py


示例10: prepare_grammar

	def prepare_grammar(s, scope):
		#s.marpa.t.input.clear()
		log("prepare grammar..")
		for i in s.editor.root.flatten():
			i.forget_symbols() # todo:start using visitors
		s.marpa.collect_grammar(scope)
		assert s.current_parser_node
		s.marpa.enqueue_precomputation(weakref(s.current_parser_node))
开发者ID:Social-Justice,项目名称:new_shit,代码行数:8,代码来源:server_frames.py


示例11: __init__

    def __init__(
        self,
        channel,
        level,
        msg,
        args=None,
        kwargs=None,
        exc_info=None,
        extra=None,
        frame=None,
        dispatcher=None,
        frame_correction=0,
    ):
        #: the name of the logger that created it or any other textual
        #: channel description.  This is a descriptive name and can be
        #: used for filtering.
        self.channel = channel
        #: The message of the log record as new-style format string.
        self.msg = msg
        #: the positional arguments for the format string.
        self.args = args or ()
        #: the keyword arguments for the format string.
        self.kwargs = kwargs or {}
        #: the level of the log record as integer.
        self.level = level
        #: optional exception information.  If set, this is a tuple in the
        #: form ``(exc_type, exc_value, tb)`` as returned by
        #: :func:`sys.exc_info`.
        #: This parameter can also be ``True``, which would cause the exception
        #: info tuple to be fetched for you.
        if not exc_info:
            # this is a special case where exc_info=False can be passed in
            # theory, and it should be the same as exc_info=None
            exc_info = None
        self.exc_info = exc_info
        #: optional extra information as dictionary.  This is the place
        #: where custom log processors can attach custom context sensitive
        #: data.

        # TODO: Replace the lambda with str when we remove support for python 2
        self.extra = defaultdict(lambda: u"", extra or ())
        #: If available, optionally the interpreter frame that pulled the
        #: heavy init.  This usually points to somewhere in the dispatcher.
        #: Might not be available for all calls and is removed when the log
        #: record is closed.
        self.frame = frame
        #: A positive integer telling the number of frames to go back from
        #: the frame which triggered the log entry. This is mainly useful
        #: for decorators that want to show that the log was emitted from
        #: form the function they decorate
        self.frame_correction = frame_correction
        #: the PID of the current process
        self.process = None
        if dispatcher is not None:
            dispatcher = weakref(dispatcher)
        self._dispatcher = dispatcher
开发者ID:thedrow,项目名称:logbook,代码行数:56,代码来源:base.py


示例12: contribute_to_class

    def contribute_to_class(self, ModelClass, name):
        # Use weakref because of possible memory leak / circular reference.
        self._model = weakref(ModelClass)
        original_save = ModelClass.save

        def save_and_clear_cache(instance, *args, **kwargs):
            original_save(instance, *args, **kwargs)
            self.clear(instance=instance)

        setattr(ModelClass, name, self)
开发者ID:CityOfPhiladelphia,项目名称:myphillyrising,代码行数:10,代码来源:modelcache.py


示例13: get_connection

    def get_connection(self, command_name, shard_hint=None):
        host_id = shard_hint
        if host_id is None:
            raise RuntimeError('The routing pool requires the host id '
                               'as shard hint')

        real_pool = self.cluster.get_pool_for_host(host_id)
        con = real_pool.get_connection(command_name)
        con.__creating_pool = weakref(real_pool)
        return con
开发者ID:artdokxxx,项目名称:rb,代码行数:10,代码来源:clients.py


示例14: __init__

    def __init__(self, topicMgr, nameTuple, description, parent=None,
                 argsSpec=None, reqdArgs=(), msgArgs=None, deadListenerCB=None):
        '''Specify the name, description, and parent of this Topic. Any remaining 
        keyword arguments (which will be put in msgArgs) describe the arguments that 
        a listener of this topic must support (i.e., the key is the argument name and
        the value is a documentation string explaining what the argument is for). 
        The reqdArgs is an optional list of names identifying which variables in 
        msgArgs keys are required arguments. E.g. 
        
            Topic(('a','b'), 'what is topic for', parentTopic, _reqdArgs=('c','d'), 
                c='what is c for', d='what is d for', e='what is e for')
            
        would create a Topic whose listeners would have to be of the form
        
            callable(c, d, e=...)
            
        ie 
            callable(c, d, e=...)
            callable(self, c, d, e=..., **kwargs) (method)
            
        would all be valid listeners but 
        
            callable(c, e=...) # error: required d is missing
            callable(c, d, e)  # error: e is optional
        
        would not be valid listeners of this topic. 
        
        The _useKwa is only used by the package to indicate whether the arguments are
        specified as part of __init__ (there is no other way since msgArgs cannot be None). 
        '''
        self.__validateName(nameTuple, parent is None)
        self.__tupleName = nameTuple

        self.__validator    = None
        self.__listeners    = []
        self.__deadListenerCB = deadListenerCB
        
        # specification: 
        self.__description  = None
        self.setDescription(description)
        getArgsSpec = topicMgr._getDefnProvider_().getSubSpec
        self.__msgArgs      = ArgsInfo(getArgsSpec, nameTuple, 
                                       parent, msgArgs, reqdArgs, argsSpec) 
        if self.__msgArgs.isComplete():
            self.__finalize()
        self.argsSpec = self.__msgArgs
        
        # now that we know the args are fine, we can link to parent
        self.__parentTopic = None
        if parent is None:
            assert self.isSendable()
        else:
            self.__parentTopic = weakref(parent)
            parent.__setSubtopic( self.getTailName(), self )
开发者ID:sproaty,项目名称:whyteboard,代码行数:54,代码来源:topics.py


示例15: __init__

 def __init__(self, client=None):
     breadcrumbs = raven.breadcrumbs.make_buffer(
         client is None or client.enable_breadcrumbs)
     if client is not None:
         client = weakref(client)
     self._client = client
     # Because the thread auto activates the thread local this also
     # means that we auto activate this thing.  Only if someone decides
     # to deactivate manually later another call to activate is
     # technically necessary.
     self.activate()
     self.data = {}
     self.exceptions_to_skip = set()
     self.breadcrumbs = breadcrumbs
开发者ID:MPOWER4RU,项目名称:raven-python,代码行数:14,代码来源:context.py


示例16: __init__

 def __init__(self, mgr, name, files):
     self._mgr = weakref(mgr)
     self.name = name
     self._css = []
     self._js = []
     for filename in files:
         assert "." in filename, "unknown file without extension"
         ext = filename.rsplit(".", 1)[-1]
         if ext == "js":
             self._js.append(filename)
         elif ext == "css":
             self._css.append(filename)
         else:
             assert False, 'unknown extension ".%s"' % ext
开发者ID:jlsandell,项目名称:solace,代码行数:14,代码来源:packs.py


示例17: test_weakref

def test_weakref():
    from weakref import ref as weakref
    from inspect import isfunction, ismethod

    class Foo:
        def instanceMethod(self): pass
        @classmethod
        def classMethod(cls): pass
        def __call__(self): pass

    assert isfunction(Foo.instanceMethod)
    wr = weakref(Foo.instanceMethod)
    assert wr() is not None, 'Foo.instanceMethod'

    assert ismethod(Foo.classMethod)
    wr = weakref(Foo.classMethod)
    gc.collect() # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'Foo.classMethod'

    foo = Foo()
    fooWR = weakref(foo)
    assert fooWR() is not None, 'foo'

    assert ismethod(foo.instanceMethod)
    wr = weakref(foo.instanceMethod)
    gc.collect() # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'foo.instanceMethod'

    assert ismethod(foo.classMethod)
    wr = weakref(foo.classMethod)
    gc.collect() # for pypy: the gc doesn't work the same as cpython's
    assert wr() is None, 'foo.classMethod'

    del foo
    gc.collect()
    assert fooWR() is None, 'foo'
开发者ID:schollii,项目名称:pypubsub,代码行数:36,代码来源:test1_listener.py


示例18: __init__

    def __init__(self, base, searchpath, optparser=None, types=None, 
            pluginconfpath=None,disabled=None,enabled=None):
        '''Initialise the instance.

        @param base: The
        @param searchpath: A list of paths to look for plugin modules.
        @param optparser: The OptionParser instance for this run (optional).
            Use to allow plugins to extend command line options.
        @param types: A sequence specifying the types of plugins to load.
            This should be sequnce containing one or more of the TYPE_...
            constants. If None (the default), all plugins will be loaded.
        @param pluginconfpath: A list of paths to look for plugin configuration
            files. Defaults to "/etc/yum/pluginconf.d".
        '''
        if not pluginconfpath:
            pluginconfpath = ['/etc/yum/pluginconf.d']

        self.searchpath = searchpath
        self.pluginconfpath = pluginconfpath
        self.base = weakref(base)
        self.optparser = optparser
        self.cmdline = (None, None)
        self.verbose_logger = logging.getLogger("yum.verbose.YumPlugins")
        self.disabledPlugins = disabled
        self.enabledPlugins  = enabled
        if types is None:
            types = ALL_TYPES
        if not isinstance(types, (list, tuple)):
            types = (types,)

        if id(TYPE_INTERFACE) in [id(t) for t in types]:
            self.verbose_logger.log(logginglevels.INFO_2,
                    'Deprecated constant TYPE_INTERFACE during plugin '
                    'initialization.\nPlease use TYPE_INTERACTIVE instead.')

        self._importplugins(types)

        self.cmdlines = {}

        # Call close handlers when yum exit's
        if self._pluginfuncs['close']:
            self.verbose_logger.error(
                _('One or more plugins uses "close" handling but should use atexit directly.'))
            atexit.register(self.run, 'close')

        # Let plugins register custom config file options
        self.run('config')
开发者ID:dmnks,项目名称:yum,代码行数:47,代码来源:plugins.py


示例19: newfunc

 def newfunc(*args, **kwargs):
     if policy == POLICY_MANY:
         # just start the timer
         t = (timer or Timer)(func, *args, **kwargs)
         t.start(interval)
         return True
     store = DecoratorDataStore(func, newfunc, args)
     # check current timer
     if 'timer' in store and store.timer and store.timer.active:
         if policy == POLICY_ONCE:
             # timer already running and not override
             return False
         # stop old timer
         store.timer.stop()
     # create new timer, store it in the object and start it
     t = (timer or Timer)(func, *args, **kwargs)
     store.timer = weakref(t)
     t.start(interval)
     return True
开发者ID:jpmunz,项目名称:smartplayer,代码行数:19,代码来源:timer.py


示例20: _find_control

 def _find_control(self, x, y):
     ctrl = self.get_control()
     if ctrl is not None and ctrl.active:
         return ctrl
     width, height = self.scale()
     if x < 0 or x > width or y < 0 or y > height:
         # the mouse is not even in the widget
         pass
     else:
         for level in range(0, 2):
             for curve in self._curves:
                 ctrl = curve.get_control(x, y, level)
                 if ctrl is not None:
                     self._ctrl = weakref(ctrl)
                     break
             if ctrl is not None:
                 break
     if ctrl is None:
         self._ctrl = None
     return ctrl
开发者ID:entropik,项目名称:multitoner,代码行数:20,代码来源:gtk_curve_editor.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python weakref.weakref_ref函数代码示例发布时间:2022-05-26
下一篇:
Python weakref.ref函数代码示例发布时间: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