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


Python warnings.warn_explicit函数代码示例

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


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


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