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

Python weakref.finalize函数代码示例

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

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



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

示例1: _connect_signal

    def _connect_signal(self, receiver, sender, weak, dispatch_uid):
        assert callable(receiver), 'Signal receivers must be callable'
        if not fun_accepts_kwargs(receiver):
            raise ValueError(
                'Signal receiver must accept keyword arguments.')

        if isinstance(sender, PromiseProxy):
            sender.__then__(
                self._connect_proxy, receiver, sender, weak, dispatch_uid,
            )
            return receiver

        lookup_key = _make_lookup_key(receiver, sender, dispatch_uid)

        if weak:
            ref, receiver_object = _boundmethod_safe_weakref(receiver)
            if PY3:
                receiver = ref(receiver)
                weakref.finalize(receiver_object, self._remove_receiver)
            else:
                receiver = ref(receiver, self._remove_receiver)

        with self.lock:
            self._clear_dead_receivers()
            for r_key, _ in self.receivers:
                if r_key == lookup_key:
                    break
            else:
                self.receivers.append((lookup_key, receiver))
            self.sender_receivers_cache.clear()

        return receiver
开发者ID:2216288075,项目名称:meiduo_project,代码行数:32,代码来源:signal.py


示例2: __init__

    def __init__(self, username=None, password=None):
        self._username = self._remove_nonascii(username)
        self._password = self._remove_nonascii(password)
        self.logger.info('Initialized with user: %s', self._username)

        self.session = Session()
        # urllib3 will sleep for {backoff factor} * (2 ^ ({number of total retries} - 1)) seconds between attempts.
        self.session.mount('http://', HTTPAdapter(
            max_retries=Retry(total=2, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504])
        ))
        self.session.mount('https://', HTTPAdapter(
            max_retries=Retry(total=2, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504])
        ))
        self.set_useragent()
        # Avoid ResourceWarning: unclosed <ssl.SSLSocket ...> with python 3
        finalize(self, self.session.close)

        cookie_file = os.path.join(self.appdata_path, self._make_fs_safe(username)+'.lwp')
        self.session.cookies = LWPCookieJar(cookie_file)
        if not os.path.exists(cookie_file):
            # initialize new cookie file
            self.logger.info('Creating new cookie file: "%s"', cookie_file)
            self.set_mobile_cookies()
            self._save_cookies()
            os.chmod(cookie_file,  stat.S_IRUSR | stat.S_IWUSR)
        else:
            # load cookies
            self.logger.info('Loading cookies from file: "%s"', cookie_file)
            self.session.cookies.load(ignore_discard=True)
            if not self._has_cookie('forceMobile') or not self._has_cookie('mobileClient'):
                self.clear_mobile_cookies()
                self.set_mobile_cookies()
                self._save_cookies()
开发者ID:jbzdarkid,项目名称:steamweb,代码行数:33,代码来源:steamwebbrowser.py


示例3: __init__

    def __init__(self, handler):
        _path = msg.join_path(self._path, '__init__')

        self.handler = handler
        self.pub_subs = {
            'w': self.handler.ws_pub_sub,
            'd': mb,
            'l': self.handler.local_pub_sub,
        }

        for attr_name in dir(self):
            attribute = getattr(self, attr_name)
            if hasattr(attribute, 'msg_types'):
                for _type, channels in attribute.msg_types:
                    msg.code_debug(
                        _path,
                        'Adding action: %r ...' % attribute
                    )
                    self.register_action_in(
                        msg_type=_type, action=attribute,
                        channels=channels)

        finalize(
            self, msg.code_debug, self._path,
            'Deleting WSClass {0} from {0.handler} '
            '...'.format(self)
        )
开发者ID:pipegreyback,项目名称:artificialAlan,代码行数:27,代码来源:wsclass.py


示例4: _delete_widget

    def _delete_widget(self, widget):
        """
        Delete the OWBaseWidget instance.
        """
        widget.close()
        # Save settings to user global settings.
        widget.saveSettings()
        # Notify the widget it will be deleted.
        widget.onDeleteWidget()

        state = self.__widget_processing_state[widget]
        if state & WidgetManager._DelayDeleteMask:
            # If the widget is in an update loop and/or blocking we
            # delay the scheduled deletion until the widget is done.
            log.debug("Widget %s removed but still in state :%s. "
                      "Deferring deletion.", widget, state)
            self.__delay_delete.add(widget)
        else:
            widget.deleteLater()
            name = "{} '{}'".format(type(widget).__name__, widget.captionTitle)
            if log.isEnabledFor(logging.DEBUG):
                finalize(
                    widget, log.debug, "Destroyed namespace: %s", name
                )
            del self.__widget_processing_state[widget]
开发者ID:PrimozGodec,项目名称:orange3,代码行数:25,代码来源:widgetsscheme.py


示例5: initializeGL

    def initializeGL(self):
        print('initialize GL')

        if self._get_proc_address is 'ctypes':
            import ctypes,ctypes.util
            lgl = ctypes.cdll.LoadLibrary(ctypes.util.find_library('GL'))
            get_proc_address = lgl.glXGetProcAddress
            get_proc_address.restype = ctypes.c_void_p
            get_proc_address.argtypes = [ ctypes.c_char_p ]
            _get_proc_address = lambda name: get_proc_address(name if isinstance(name,bytes) else name.encode('latin1'))
        else:
            qgl_get_proc_address = Q.QGLContext.currentContext().getProcAddress
            _get_proc_address = lambda name: int(qgl_get_proc_address(name.decode('latin1') if isinstance(name,bytes) else name))

        if self._get_proc_address_debug:
            def getprocaddr(name):
                res = _get_proc_address(name)
                print('{} -> address {}'.format(name,res))
                return res
        else:
            getprocaddr = _get_proc_address

        self.ogl = self.m.opengl_cb_context
        self.ogl.init_gl(getprocaddr,None)

        weakref.finalize(self, lambda:self.ogl.set_update_callback(None))
        self.wakeup.connect(self.onWakeup,Q.Qt.QueuedConnection|Q.Qt.UniqueConnection)
        self.frameSwapped.connect(self.onFrameSwapped)
        self.ogl.set_update_callback(self.wakeup.emit)
        self.openglInitialized.emit(Q.QOpenGLContext.currentContext())
开发者ID:gdkar,项目名称:qtmpv,代码行数:30,代码来源:av_player.py


示例6: inner

 def inner():
     img = ax.imshow([[0, 1], [2, 3]])
     cursor = mplcursors.cursor(img)
     f_img = weakref.finalize(img, lambda: None)
     f_cursor = weakref.finalize(cursor, lambda: None)
     img.remove()
     return f_img, f_cursor
开发者ID:bbgky,项目名称:mplcursors,代码行数:7,代码来源:test_basic.py


示例7: __init__

    def __init__(self):
        super(QObject, self).__init__()

        conn_parent, conn_child = socketpair()

        # TODO: figure out which of the two sockets should be set to 
        #       inheritable and which should be passed to the child
        if hasattr(conn_child, 'set_inheritable'):
            conn_child.set_inheritable(True)

        # Use a local variable for child so that we can talk to the child in
        # on_finalize without needing a reference to self
        child = mp.Process(target=_converter_process_func, args=(conn_parent, conn_child))
        child.daemon = True
        child.start()
        self.child = child

        conn_child.close()
        self.conn = conn_parent

        self.busy = False
        self.notificationPending = False
        self.conversionNotifier = QSocketNotifier(self.conn.fileno(),
                                                  QSocketNotifier.Read)
        self.conversionNotifier.activated.connect(self._conversionNotifierActivated)

        def on_finalize(conn):
            sendObject(conn_parent, {'command':'quit'})
            conn_parent.close()
            child.join()

        weakref.finalize(self, on_finalize, conn_parent)
开发者ID:FiveDotsSoft,项目名称:retext,代码行数:32,代码来源:converterprocess.py


示例8: connect

    def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
        """
        Connect receiver to sender for signal.

        Arguments:

            receiver
                A function or an instance method which is to receive signals.
                Receivers must be hashable objects.

                If weak is True, then receiver must be weak referenceable.

                Receivers must be able to accept keyword arguments.

                If a receiver is connected with a dispatch_uid argument, it
                will not be added if another receiver was already connected
                with that dispatch_uid.

            sender
                The sender to which the receiver should respond. Must either be
                of type Signal, or None to receive events from any sender.

            weak
                Whether to use weak references to the receiver. By default, the
                module will attempt to use weak references to the receiver
                objects. If this parameter is false, then strong references will
                be used.

            dispatch_uid
                An identifier used to uniquely identify a particular instance of
                a receiver. This will usually be a string, though it may be
                anything hashable.
        """

        if dispatch_uid:
            lookup_key = (dispatch_uid, _make_id(sender))
        else:
            lookup_key = (_make_id(receiver), _make_id(sender))

        if weak:
            ref = weakref.ref
            receiver_object = receiver
            # Check for bound methods
            if hasattr(receiver, '__self__') and hasattr(receiver, '__func__'):
                ref = WeakMethod
                receiver_object = receiver.__self__
            if six.PY3:
                receiver = ref(receiver)
                weakref.finalize(receiver_object, self._remove_receiver)
            else:
                receiver = ref(receiver, self._remove_receiver)

        with self.lock:
            self._clear_dead_receivers()
            for r_key, _ in self.receivers:
                if r_key == lookup_key:
                    break
            else:
                self.receivers.append((lookup_key, receiver))
            self.sender_receivers_cache.clear()
开发者ID:summer1988,项目名称:pythunder,代码行数:60,代码来源:dispatcher.py


示例9: __init__

    def __init__(self):
        conn_parent, conn_child = mp.Pipe()

        # Use a local variable for child so that we can talk to the child in
        # on_finalize without needing a reference to self
        child = mp.Process(target=_converter_process_func, args=(conn_parent, conn_child))
        child.daemon = True
        child.start()
        self.child = child

        conn_child.close()
        self.conn = conn_parent

        self.busy = False
        self.conversionNotifier = QSocketNotifier(self.conn.fileno(),
                                                  QSocketNotifier.Read)

        # assign the activated signal of the notifier to a conversionDone
        # member to get a more meaningful signal name for others to connect to
        self.conversionDone = self.conversionNotifier.activated

        def on_finalize(conn):
            conn_parent.send({'command':'quit'})
            conn_parent.close()
            child.join()

        weakref.finalize(self, on_finalize, conn_parent)
开发者ID:liyongming1982,项目名称:retext,代码行数:27,代码来源:converterprocess.py


示例10: __init__

 def __init__(self,name=None,dir='/tmp',text=False,encoding=None, expires=None):
     if name is None:
         fd,path = tempfile.mkstemp(suffix='.tmp',dir=dir,text=False)
     else:
         path = os.path.join(dir,name)
         if os.path.exists(path) and ((expires is None) or (time.time() + expires > os.stat(path).st_mtime)):
             self.new = False
         else:
             path = path + '.tmp'
         encoding = encoding if encoding else 'utf-8' if text else None
     self.name = path
     if name is not None:
         mode = 'w+' if self.new else 'r+'
         mode += 't' if text else 'b'
         self.file = open(path, mode, encoding=encoding)
         if encoding or text:
             self.raw = self.file.raw
         else:
             self.raw = self.file
     else:
         self.raw = os.fdopen(fd,'w+b')
         if encoding:
             if encoding is True:
                 encoding = 'utf-8'
             self.file = io.TextIOWrapper(self.raw,encoding=encoding)
         else:
             self.file = self.raw
     weakref.finalize(self, self.ifnew, os.unlink, path)
开发者ID:cyisfor,项目名称:gnunet-webserver,代码行数:28,代码来源:mytemp.py


示例11: __init__

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._silent = False

        # console, qtconsole uses `kernel-$pid`, notebook uses `kernel-$uuid`.
        self._has_console_frontend = bool(re.match(
            r"\Akernel-\d+\Z",
            Path(self.config["IPKernelApp"]["connection_file"]).stem))

        if os.name == "posix":
            with ExitStack() as stack:
                for name in ["stdout", "stderr"]:
                    stream = getattr(sys, "__{}__".format(name))
                    def callback(data, *, _name=name, _stream=stream):
                        if not self._silent:
                            self._send_stream(
                                _name, data.decode(_stream.encoding))
                    stack.enter_context(
                        _redirection.redirect(stream.fileno(), callback))
                weakref.finalize(self, stack.pop_all().close)

        self._dead_engines = []
        engine_name = os.environ.get("IMATLAB_CONNECT")
        if engine_name:
            if re.match(r"\A(?a)[a-zA-Z]\w*\Z", engine_name):
                self._engine = matlab.engine.connect_matlab(engine_name)
            else:
                self._engine = matlab.engine.connect_matlab()
        else:
            self._engine = matlab.engine.start_matlab()
        self._history = MatlabHistory(Path(self._call("prefdir")))
        self._engine.addpath(
            str(Path(sys.modules[__name__.split(".")[0]].__file__).
                with_name("data")),
            "-end")
开发者ID:anntzer,项目名称:matlab_kernel,代码行数:35,代码来源:_kernel.py


示例12: __init__

    def __init__(
            self,
            scidb_url=None,
            scidb_auth=None,
            http_auth=None,
            verify=None,
            admin=False,
            namespace=None,
            use_arrow=False,
            result_size_limit=256,
            no_ops=False):
        if scidb_url is None:
            scidb_url = os.getenv('SCIDB_URL', 'http://localhost:8080')

        self.scidb_url = scidb_url
        self.verify = verify
        self.admin = admin
        self.namespace = namespace
        self.use_arrow = use_arrow
        self.result_size_limit = result_size_limit
        self.no_ops = no_ops

        if http_auth:
            self._http_auth = requests.auth.HTTPDigestAuth(*http_auth)
            self.http_auth = (http_auth[0], Password_Placeholder())
        else:
            self._http_auth = self.http_auth = None

        admin_shim = 1 if self.admin else 0
        if scidb_auth:
            self._id = self._shim(Shim.new_session,
                                  user=scidb_auth[0],
                                  password=scidb_auth[1],
                                  admin=admin_shim).text
            self.scidb_auth = (scidb_auth[0], Password_Placeholder())
        else:
            self._id = self._shim(Shim.new_session,
                                  admin=admin_shim).text
            self.scidb_auth = None

        finalize(self,
                 _shim_release_session,
                 self.scidb_url,
                 self._http_auth,
                 self.verify,
                 self._id)

        self.arrays = Arrays(self)

        self._uid = uuid.uuid1().hex
        self._lock = threading.Lock()
        self._array_cnt = 0
        self._formatter = string.Formatter()

        if self.no_ops:
            self.operators = None
            self._dir = None
        else:
            self.load_ops()
开发者ID:Paradigm4,项目名称:SciDB-Py,代码行数:59,代码来源:db.py


示例13: watch

 def watch(self,action,done):
     self.action = action
     self.done = done
     if self.cancelled:
         done.add_done_callback(self.nocancel)
         weakref.finalize(self,self.cancel)
         self.cancelled = False
     return done
开发者ID:cyisfor,项目名称:gnunet-webserver,代码行数:8,代码来源:gnunet.py


示例14: __init__

 def __init__(self, title, width, height):
   self.win = SDL_CreateWindow(title.encode('utf-8'), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                        width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE)
   weakref.finalize(self.win, SDL_DestroyWindow, self.win)
   self.dirtyRects = []
   self.width = width
   self.height = height
   self.scale = 1
开发者ID:yarnoiser,项目名称:weird,代码行数:8,代码来源:window.py


示例15: __new__

 def __new__(cls, filename):
   if filename in AdvConfig._configs:
     n=AdvConfig._configs[filename]
     n.sync()
   else:
     n=super(AdvConfig,cls).__new__(cls)
     AdvConfig._configs[filename]=n
     finalize(n, n.sync)
   return n
开发者ID:CarlEdman,项目名称:MakeMP4,代码行数:9,代码来源:AdvConfig.py


示例16: __init__

 def __init__(self, service):
     super().__init__(service)
     logging.getLogger("chardet").setLevel(logging.WARNING)
     self.common_loop = service.loop
     self.common_connector = TCPConnector(limit=GET_URL_PARALLEL_LIMIT, loop=self.common_loop)
     self.common_cookie_jar = self.new_cookie_jar()
     self.common_client_timeout = aiohttp.ClientTimeout(sock_connect=GET_URL_CONNECT_TIMEOUT,
                                                        sock_read=GET_URL_RECV_TIMEOUT)
     logging.debug("init %s" % self.common_connector)
     weakref.finalize(self, _close_connector, self.common_loop, self.common_connector)
开发者ID:wwqgtxx,项目名称:wwqLyParse,代码行数:10,代码来源:aiohttp.py


示例17: _get_properties

    def _get_properties(self, request):
        req_id = id(request)

        if req_id in self._request_properties:
            return self._request_properties[req_id]
        else:
            finalize(request, self._free_properties, req_id)
            properties = {}
            self._request_properties[req_id] = properties
            return properties
开发者ID:sherwoodwang,项目名称:pyramid-redis-token-authentication,代码行数:10,代码来源:_impl.py


示例18: __init__

	def __init__(self, filename):
		''' Read contents of dictionary from file, set up deletion hook '''
		self.filename = filename
		dict.__init__(self)
		try:
			with open(self.filename, 'rb') as cache_file:
				self.update(load(cache_file))
		except FileNotFoundError:
			pass # on read, don't create the file if it does not exist
		# when object is deleted, update file
		finalize(self, lambda: self.dump_to_file())
开发者ID:Daerdemandt,项目名称:python-decorators,代码行数:11,代码来源:memoize_using_file.py


示例19: register_injector

    def register_injector(cls, instance, injector):
        """Registers the injector for a specific instance, using weak references.

        Arguments
        ---------
        instance: any
            an arbitrary object
        injector: Injector
            the injector to be used
        """
        cls.INSTANCE_REGISTRY[id(instance)] = injector
        weakref.finalize(instance, lambda: cls.INSTANCE_REGISTRY.pop(id(instance)))
开发者ID:simone-campagna,项目名称:dope,代码行数:12,代码来源:attr.py


示例20: __init__

    def __init__(self, parent):
        self.parent = parent

        self.__methods = []

        if self.__options__:
            self.__config = Config(
                self.__class__.__gsettings__.get("schema"),
                self.__class__.__gsettings__.get("path")
            )

        weakref.finalize(self, self._on_plugin_delete)
开发者ID:blueman-project,项目名称:blueman,代码行数:12,代码来源:BasePlugin.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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