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

Python warnings.warn_explicit函数代码示例

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

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



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

示例1: _importconftest

    def _importconftest(self, conftestpath):
        try:
            return self._conftestpath2mod[conftestpath]
        except KeyError:
            pkgpath = conftestpath.pypkgpath()
            if pkgpath is None:
                _ensure_removed_sysmodule(conftestpath.purebasename)
            try:
                mod = conftestpath.pyimport()
                if hasattr(mod, "pytest_plugins") and self._configured:
                    from _pytest.deprecated import (
                        PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST
                    )

                    warnings.warn_explicit(
                        PYTEST_PLUGINS_FROM_NON_TOP_LEVEL_CONFTEST,
                        category=None,
                        filename=str(conftestpath),
                        lineno=0,
                    )
            except Exception:
                raise ConftestImportFailure(conftestpath, sys.exc_info())

            self._conftest_plugins.add(mod)
            self._conftestpath2mod[conftestpath] = mod
            dirpath = conftestpath.dirpath()
            if dirpath in self._path2confmods:
                for path, mods in self._path2confmods.items():
                    if path and path.relto(dirpath) or path == dirpath:
                        assert mod not in mods
                        mods.append(mod)
            self.trace("loaded conftestmodule %r" % (mod))
            self.consider_conftest(mod)
            return mod
开发者ID:sallner,项目名称:pytest,代码行数:34,代码来源:__init__.py


示例2: warnAboutFunction

def warnAboutFunction(offender, warningString):
    """
    Issue a warning string, identifying C{offender} as the responsible code.

    This function is used to deprecate some behavior of a function.  It differs
    from L{warnings.warn} in that it is not limited to deprecating the behavior
    of a function currently on the call stack.

    @param function: The function that is being deprecated.

    @param warningString: The string that should be emitted by this warning.
    @type warningString: C{str}

    @since: 11.0
    """
    # inspect.getmodule() is attractive, but somewhat
    # broken in Python < 2.6.  See Python bug 4845.
    offenderModule = sys.modules[offender.__module__]
    filename = inspect.getabsfile(offenderModule)
    lineStarts = list(findlinestarts(offender.func_code))
    lastLineNo = lineStarts[-1][1]
    globals = offender.func_globals

    kwargs = dict(
        category=DeprecationWarning,
        filename=filename,
        lineno=lastLineNo,
        module=offenderModule.__name__,
        registry=globals.setdefault("__warningregistry__", {}),
        module_globals=None)

    if sys.version_info[:2] < (2, 5):
        kwargs.pop('module_globals')

    warn_explicit(warningString, **kwargs)
开发者ID:BillAndersan,项目名称:twisted,代码行数:35,代码来源:deprecate.py


示例3: error

 def error(self,msg,err,node):
     if not err:
         try:
             warnings.warn_explicit(msg,SyntaxWarning,self.getFilename(),node.beginLine)
             return
         except Exception,e:
             if not isinstance(e,SyntaxWarning): raise e
开发者ID:mcarlson,项目名称:openlaszlo,代码行数:7,代码来源:SimpleCompiler.py


示例4: _unjelly_instance

    def _unjelly_instance(self, rest):
        """
        (internal) Unjelly an instance.

        Called to handle the deprecated I{instance} token.

        @param rest: The s-expression representing the instance.

        @return: The unjellied instance.
        """
        warnings.warn_explicit(
            "Unjelly support for the instance atom is deprecated since "
            "Twisted 15.0.0.  Upgrade peer for modern instance support.",
            category=DeprecationWarning, filename="", lineno=0)

        clz = self.unjelly(rest[0])
        if type(clz) is not types.ClassType:
            raise InsecureJelly("Instance found with non-class class.")
        if hasattr(clz, "__setstate__"):
            inst = _newInstance(clz, {})
            state = self.unjelly(rest[1])
            inst.__setstate__(state)
        else:
            state = self.unjelly(rest[1])
            inst = _newInstance(clz, state)
        if hasattr(clz, 'postUnjelly'):
            self.postCallbacks.append(inst.postUnjelly)
        return inst
开发者ID:Architektor,项目名称:PySnip,代码行数:28,代码来源:jelly.py


示例5: _warn_for_function

def _warn_for_function(warning, function):
    warnings.warn_explicit(
        warning,
        type(warning),
        lineno=function.__code__.co_firstlineno,
        filename=function.__code__.co_filename,
    )
开发者ID:lfernandez55,项目名称:flask_books,代码行数:7,代码来源:manager.py


示例6: get_info

    def get_info(reddit_session, url, comments_only=False):
        url_data = {}
        comment_limit = reddit_session.config.comment_limit
        comment_sort = reddit_session.config.comment_sort

        if reddit_session.user and reddit_session.user.is_gold:
            class_max = reddit_session.config.gold_comments_max
        else:
            class_max = reddit_session.config.regular_comments_max

        if comment_limit == -1:  # Use max for user class
            comment_limit = class_max
        elif comment_limit > 0:  # Use specified value
            if comment_limit > class_max:
                warnings.warn_explicit('comment_limit %d is too high (max: %d)'
                                       % (comment_limit, class_max),
                                       UserWarning, '', 0)
                comment_limit = class_max
        elif comment_limit == 0:  # Use default
            comment_limit = None

        if comment_limit:
            url_data['limit'] = comment_limit
        if comment_sort:
            url_data['sort'] = comment_sort
        s_info, c_info = reddit_session.request_json(url, url_data=url_data)
        if comments_only:
            return c_info['data']['children']
        submission = s_info['data']['children'][0]
        submission.comments = c_info['data']['children']
        return submission
开发者ID:logan,项目名称:praw,代码行数:31,代码来源:objects.py


示例7: get_info

 def get_info(reddit_session, url, comments_only=False):
     url_data = {}
     comment_limit = reddit_session.config.comment_limit
     comment_sort = reddit_session.config.comment_sort
     if comment_limit:
         if reddit_session.user and reddit_session.user.is_gold:
             limit_max = 1500
         else:
             limit_max = 500
         if comment_limit > limit_max:
             warnings.warn_explicit('comment_limit %d is too high (max: %d)'
                                    % (comment_limit, limit_max),
                                    UserWarning, '', 0)
             url_data['limit'] = limit_max
         elif comment_limit < 0:
             url_data['limit'] = limit_max
         else:
             url_data['limit'] = comment_limit
     if comment_sort:
         url_data['sort'] = comment_sort
     s_info, c_info = reddit_session.request_json(url, url_data=url_data)
     if comments_only:
         return c_info['data']['children']
     submission = s_info['data']['children'][0]
     submission.comments = c_info['data']['children']
     return submission
开发者ID:yetanotherx,项目名称:reddit_api,代码行数:26,代码来源:objects.py


示例8: process_key

 def process_key(self):
     token_type, token_string, token_line_number = self.consume()
     
     if pyradox.token.is_primitive_key_token_type(token_type):
         self.key_string = token_string
         self.key = pyradox.token.make_primitive(token_string, token_type)
         self.next = self.process_operator
     elif token_type == 'comment':
         if token_line_number == self.get_previous_line_number():
             # Comment following a previous value.
             self.append_line_comment(token_string[1:])
         else:
             self.pending_comments.append(token_string[1:])
         self.next = self.process_key
     elif token_type == 'end':
         if self.is_top_level:
             # top level cannot be ended, warn
             warnings.warn_explicit('Unmatched closing bracket at outer level of file. Skipping token.', ParseWarning, self.filename, token_line_number + 1)
             self.next = self.process_key
         else:
             self.next = None
     else:
         #invalid key
         warnings.warn_explicit('Token "%s" is not valid key. Skipping token.' % token_string, ParseWarning, self.filename, token_line_number + 1)
         self.next = self.process_key
开发者ID:ajul,项目名称:pyradox,代码行数:25,代码来源:txt.py


示例9: resource

def resource(_context, name, layer=IDefaultBrowserLayer,
             permission='zope.Public', factory=None,
             file=None, image=None, template=None):

    if permission == 'zope.Public':
        permission = CheckerPublic

    checker = NamesChecker(allowed_names, permission)

    too_many = bool(factory) + bool(file) + bool(image) + bool(template)
    if too_many > 1:
        raise ConfigurationError(
            "Must use exactly one of factory or file or image or template"
            " attributes for resource directives"
        )

    if image or template:
        import warnings
        warnings.warn_explicit(
            'The "template" and "image" attributes of resource '
            'directive are deprecated in favor of pluggable '
            'file resource factories based on file extensions. '
            'Use the "file" attribute instead.',
            DeprecationWarning,
            _context.info.file, _context.info.line)
        if image:
            file = image
        elif template:
            file = template

    _context.action(
        discriminator=('resource', name, IBrowserRequest, layer),
        callable=resourceHandler,
        args=(name, layer, checker, factory, file, _context.info),
        )
开发者ID:zopefoundation,项目名称:zope.browserresource,代码行数:35,代码来源:metaconfigure.py


示例10: __getitem__

 def __getitem__(self, key):
     if key in self.deprecation_messages:
         import warnings
         import linecache
         # DeprecationWarnings are ignored by default. Clear the filter so
         # they are not:
         previous_warning_filters = warnings.filters[:]
         try:
             warnings.resetwarnings()
             # Hacky stuff to get it to work from within execfile() with
             # correct line data:
             linecache.clearcache()
             caller = sys._getframe(1)
             globals = caller.f_globals
             lineno = caller.f_lineno
             module = globals['__name__']
             filename = globals.get('__file__')
             fnl = filename.lower()
             if fnl.endswith((".pyc", ".pyo")):
                 filename = filename[:-1]
             message = self.deprecation_messages[key]
             warnings.warn_explicit(message, DeprecationWarning, filename, lineno, module)
         finally:
             # Restore the warnings filter:
             warnings.filters[:] = previous_warning_filters
     return dict.__getitem__(self, key)
开发者ID:specialforcea,项目名称:labscriptsuite,代码行数:26,代码来源:analysis_subprocess.py


示例11: _handle_menu

def _handle_menu(_context, menu, title, for_, name, permission,
                 layer=IDefaultBrowserLayer):

    if menu or title:
        if not (menu and title):
            raise ConfigurationError(
                "If either menu or title are specified, they must "
                "both be specified.")
        if len(for_) != 1:
            raise ConfigurationError(
                "Menus can be specified only for single-view, not for "
                "multi-views.")

        if menuItemDirective is None:
            import warnings
            warnings.warn_explicit(
                'Page directive used with "menu" argument, while "zope.browsermenu" '
                'package is not installed. Doing nothing.',
                UserWarning,
                _context.info.file, _context.info.line)
            return []
    
        return menuItemDirective(
            _context, menu, for_[0], '@@' + name, title,
            permission=permission, layer=layer)

    return []
开发者ID:kislovm,项目名称:findburo,代码行数:27,代码来源:metaconfigure.py


示例12: pytest_pycollect_makeitem

def pytest_pycollect_makeitem(collector, name, obj):
    outcome = yield
    res = outcome.get_result()
    if res is not None:
        return
    # nothing was collected elsewhere, let's do it here
    if safe_isclass(obj):
        if collector.istestclass(obj, name):
            outcome.force_result(Class(name, parent=collector))
    elif collector.istestfunction(obj, name):
        # mock seems to store unbound methods (issue473), normalize it
        obj = getattr(obj, "__func__", obj)
        # We need to try and unwrap the function if it's a functools.partial
        # or a funtools.wrapped.
        # We musn't if it's been wrapped with mock.patch (python 2 only)
        if not (isfunction(obj) or isfunction(get_real_func(obj))):
            filename, lineno = getfslineno(obj)
            warnings.warn_explicit(
                message=PytestWarning(
                    "cannot collect %r because it is not a function." % name
                ),
                category=None,
                filename=str(filename),
                lineno=lineno + 1,
            )
        elif getattr(obj, "__test__", True):
            if is_generator(obj):
                res = Function(name, parent=collector)
                reason = deprecated.YIELD_TESTS.format(name=name)
                res.add_marker(MARK_GEN.xfail(run=False, reason=reason))
                res.warn(PytestWarning(reason))
            else:
                res = list(collector._genfunctions(name, obj))
            outcome.force_result(res)
开发者ID:mathieu-vallais,项目名称:Docker,代码行数:34,代码来源:python.py


示例13: warn

    def warn(self, code, message, fslocation=None, nodeid=None):
        """
        .. deprecated:: 3.8

            Use :py:func:`warnings.warn` or :py:func:`warnings.warn_explicit` directly instead.

        Generate a warning for this test session.
        """
        from _pytest.warning_types import RemovedInPytest4Warning

        if isinstance(fslocation, (tuple, list)) and len(fslocation) > 2:
            filename, lineno = fslocation[:2]
        else:
            filename = "unknown file"
            lineno = 0
        msg = "config.warn has been deprecated, use warnings.warn instead"
        if nodeid:
            msg = "{}: {}".format(nodeid, msg)
        warnings.warn_explicit(
            RemovedInPytest4Warning(msg),
            category=None,
            filename=filename,
            lineno=lineno,
        )
        self.hook.pytest_logwarning.call_historic(
            kwargs=dict(
                code=code, message=message, fslocation=fslocation, nodeid=nodeid
            )
        )
开发者ID:Stranger6667,项目名称:pytest,代码行数:29,代码来源:__init__.py


示例14: deprecated

def deprecated(f, *args, **kw):
    warnings.warn_explicit(
        "Call to deprecated function {}.".format(f.__name__),
        category=DeprecationWarning,
        filename=f.func_code.co_filename,
        lineno=f.func_code.co_firstlineno + 1
    )
开发者ID:rocktavious,项目名称:pyul,代码行数:7,代码来源:decoratorUtils.py


示例15: reportDeprecatedWorkerNameUsage

def reportDeprecatedWorkerNameUsage(message, stacklevel=None, filename=None,
                                    lineno=None):
    """Hook that is ran when old API name is used.

    :param stacklevel: stack level relative to the caller's frame.
    Defaults to caller of the caller of this function.
    """

    if filename is None:
        if stacklevel is None:
            # Warning will refer to the caller of the caller of this function.
            stacklevel = 3
        else:
            stacklevel += 2

        warnings.warn(DeprecatedWorkerNameWarning(message), None, stacklevel)

    else:
        assert stacklevel is None

        if lineno is None:
            lineno = 0

        warnings.warn_explicit(
            DeprecatedWorkerNameWarning(message),
            DeprecatedWorkerNameWarning,
            filename, lineno)
开发者ID:nand0p,项目名称:buildbot,代码行数:27,代码来源:worker_transition.py


示例16: Wrapper

 def Wrapper(*args, **kwargs):
   warnings.warn_explicit(
       '%s() is deprecated: %s' % (func.__name__, message),
       category=DeprecationWarning,
       filename=func.func_code.co_filename,
       lineno=func.func_code.co_firstlineno + 1)
   return func(*args, **kwargs)
开发者ID:earth-genome,项目名称:water-service,代码行数:7,代码来源:deprecation.py


示例17: p_colon_deprication

def p_colon_deprication(p):
    ''' colon_opt : ':'
    '''
    warnings.warn_explicit("use of ':' deprecated after rule names",
                           DeprecationWarning,
                           scanner.lexer.filename, p.lineno(1))
    p[0] = None
开发者ID:julienR2,项目名称:BluesMyMind,代码行数:7,代码来源:krbparser.py


示例18: stage_parfor_pass

    def stage_parfor_pass(self):
        """
        Convert data-parallel computations into Parfor nodes
        """
        # Ensure we have an IR and type information.
        assert self.func_ir
        parfor_pass = ParforPass(self.func_ir, self.type_annotation.typemap,
            self.type_annotation.calltypes, self.return_type, self.typingctx,
            self.flags.auto_parallel, self.flags)
        parfor_pass.run()

        if config.WARNINGS:
            # check the parfor pass worked and warn if it didn't
            has_parfor = False
            for blk in self.func_ir.blocks.values():
                for stmnt in blk.body:
                    if isinstance(stmnt, Parfor):
                        has_parfor = True
                        break
                else:
                    continue
                break

            if not has_parfor:
                # parfor calls the compiler chain again with a string
                if not self.func_ir.loc.filename == '<string>':
                    msg = ("parallel=True was specified but no transformation"
                           " for parallel execution was possible.")
                    warnings.warn_explicit(
                        msg,
                        errors.NumbaWarning,
                        self.func_id.filename,
                        self.func_id.firstlineno
                        )
开发者ID:cpcloud,项目名称:numba,代码行数:34,代码来源:compiler.py


示例19: set_referred_object

    def set_referred_object(self, referred_object):
        """
        Sets the object the ResourceIdentifier refers to.

        If it already a weak reference it will be used, otherwise one will be
        created. If the object is None, None will be set.

        Will also append self again to the global class level reference list so
        everything stays consistent.
        """
        # If it does not yet exists simply set it.
        if self.id not in ResourceIdentifier.__resource_id_weak_dict:
            ResourceIdentifier.__resource_id_weak_dict[self.id] = \
                referred_object
            return
        # Otherwise check if the existing element the same as the new one. If
        # it is do nothing, otherwise raise a warning and set the new object as
        # the referred object.
        if ResourceIdentifier.__resource_id_weak_dict[self.id] == \
                referred_object:
            return
        msg = "The resource identifier '%s' already exists and points to " + \
              "another object: '%s'." +\
              "It will now point to the object referred to by the new " + \
              "resource identifier."
        msg = msg % (
            self.id,
            repr(ResourceIdentifier.__resource_id_weak_dict[self.id]))
        # Always raise the warning!
        warnings.warn_explicit(msg, UserWarning, __file__,
                               inspect.currentframe().f_back.f_lineno)
        ResourceIdentifier.__resource_id_weak_dict[self.id] = \
            referred_object
开发者ID:Qigaoo,项目名称:obspy,代码行数:33,代码来源:base.py


示例20: stage_objectmode_backend

    def stage_objectmode_backend(self):
        """
        Lowering for object mode
        """
        lowerfn = self.backend_object_mode
        self._backend(lowerfn, objectmode=True)

        # Warn if compiled function in object mode and force_pyobject not set
        if not self.flags.force_pyobject:
            if len(self.lifted) > 0:
                warn_msg = ('Function "%s" was compiled in object mode without'
                            ' forceobj=True, but has lifted loops.' %
                            (self.func_id.func_name,))
            else:
                warn_msg = ('Function "%s" was compiled in object mode without'
                            ' forceobj=True.' % (self.func_id.func_name,))
            warnings.warn_explicit(warn_msg, errors.NumbaWarning,
                                   self.func_id.filename,
                                   self.func_id.firstlineno)
            if self.flags.release_gil:
                warn_msg = ("Code running in object mode won't allow parallel"
                            " execution despite nogil=True.")
                warnings.warn_explicit(warn_msg, errors.NumbaWarning,
                                       self.func_id.filename,
                                       self.func_id.firstlineno)
开发者ID:cpcloud,项目名称:numba,代码行数:25,代码来源:compiler.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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