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

Python utils.safe_infer函数代码示例

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

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



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

示例1: _check_cmp_argument

    def _check_cmp_argument(self, node):
        # Check that the `cmp` argument is used
        kwargs = []
        if (isinstance(node.func, astroid.Attribute)
                and node.func.attrname == 'sort'):
            inferred = utils.safe_infer(node.func.expr)
            if not inferred:
                return

            builtins_list = "{}.list".format(bases.BUILTINS)
            if (isinstance(inferred, astroid.List)
                    or inferred.qname() == builtins_list):
                kwargs = node.keywords

        elif (isinstance(node.func, astroid.Name)
              and node.func.name == 'sorted'):
            inferred = utils.safe_infer(node.func)
            if not inferred:
                return

            builtins_sorted = "{}.sorted".format(bases.BUILTINS)
            if inferred.qname() == builtins_sorted:
                kwargs = node.keywords

        for kwarg in kwargs or []:
            if kwarg.arg == 'cmp':
                self.add_message('using-cmp-argument', node=node)
                return
开发者ID:fkromer,项目名称:pylint,代码行数:28,代码来源:python3.py


示例2: get_constant_values

    def get_constant_values(self, node, key):
        try:
            ass = node.locals[key][-1]
        except KeyError:
            return

        try:
            xs = safe_infer(ass).get_children()
        except AttributeError:
            return

        return [(x, x.value) for x in xs if isinstance(safe_infer(x), astng.Const)]
开发者ID:dixit-anup,项目名称:maventotalproject,代码行数:12,代码来源:settings.py


示例3: visit_callfunc

 def visit_callfunc(self, node):
     func = utils.safe_infer(node.func)
     if (isinstance(func, astroid.BoundMethod)
         and isinstance(func.bound, astroid.Instance)
         and func.bound.name in ('str', 'unicode', 'bytes')
         and func.name in ('strip', 'lstrip', 'rstrip')
         and node.args):
         arg = utils.safe_infer(node.args[0])
         if not isinstance(arg, astroid.Const):
             return
         if len(arg.value) != len(set(arg.value)):
             self.add_message('bad-str-strip-call', node=node,
                              args=(func.bound.name, func.name))
开发者ID:vbanos,项目名称:grgov-mobile-search,代码行数:13,代码来源:strings.py


示例4: visit_callfunc

 def visit_callfunc(self, node):
     func = utils.safe_infer(node.func)
     if (
         isinstance(func, astroid.BoundMethod)
         and isinstance(func.bound, astroid.Instance)
         and func.bound.name in ("str", "unicode", "bytes")
         and func.name in ("strip", "lstrip", "rstrip")
         and node.args
     ):
         arg = utils.safe_infer(node.args[0])
         if not isinstance(arg, astroid.Const):
             return
         if len(arg.value) != len(set(arg.value)):
             self.add_message("E1310", node=node, args=(func.bound.name, func.name))
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:14,代码来源:strings.py


示例5: possible_exc_types

def possible_exc_types(node):
    """
    Gets all of the possible raised exception types for the given raise node.

    .. note::

        Caught exception types are ignored.


    :param node: The raise node to find exception types for.
    :type node: astroid.node_classes.NodeNG

    :returns: A list of exception types possibly raised by :param:`node`.
    :rtype: list(str)
    """
    excs = []
    if isinstance(node.exc, astroid.Name):
        inferred = safe_infer(node.exc)
        if inferred:
            excs = [inferred.name]
    elif (isinstance(node.exc, astroid.Call) and
          isinstance(node.exc.func, astroid.Name)):
        target = safe_infer(node.exc.func)
        if isinstance(target, astroid.ClassDef):
            excs = [target.name]
        elif isinstance(target, astroid.FunctionDef):
            for ret in target.nodes_of_class(astroid.Return):
                if ret.frame() != target:
                    # return from inner function - ignore it
                    continue

                val = safe_infer(ret.value)
                if (val and isinstance(val, (astroid.Instance, astroid.ClassDef))
                        and inherit_from_std_ex(val)):
                    excs.append(val.name)
    elif node.exc is None:
        handler = node.parent
        while handler and not isinstance(handler, astroid.ExceptHandler):
            handler = handler.parent

        if handler and handler.type:
            inferred_excs = astroid.unpack_infer(handler.type)
            excs = (exc.name for exc in inferred_excs
                    if exc is not astroid.Uninferable)


    try:
        return set(exc for exc in excs if not node_ignores_exception(node, exc))
    except astroid.InferenceError:
        return ()
开发者ID:glennmatthews,项目名称:pylint,代码行数:50,代码来源:_check_docs_utils.py


示例6: _check_try_except_raise

    def _check_try_except_raise(self, node):
        def gather_exceptions_from_handler(handler):
            exceptions = []
            if handler.type:
                exceptions_in_handler = utils.safe_infer(handler.type)
                if isinstance(exceptions_in_handler, astroid.Tuple):
                    exceptions = {
                        exception
                        for exception in exceptions_in_handler.elts
                        if isinstance(exception, astroid.Name)
                    }
                elif exceptions_in_handler:
                    exceptions = [exceptions_in_handler]
            return exceptions

        bare_raise = False
        handler_having_bare_raise = None
        excs_in_bare_handler = []
        for handler in node.handlers:
            if bare_raise:
                # check that subsequent handler is not parent of handler which had bare raise.
                # since utils.safe_infer can fail for bare except, check it before.
                # also break early if bare except is followed by bare except.

                excs_in_current_handler = gather_exceptions_from_handler(handler)
                if not excs_in_current_handler:
                    bare_raise = False
                    break

                for exc_in_current_handler in excs_in_current_handler:
                    inferred_current = utils.safe_infer(exc_in_current_handler)
                    if any(
                        utils.is_subclass_of(
                            utils.safe_infer(exc_in_bare_handler), inferred_current
                        )
                        for exc_in_bare_handler in excs_in_bare_handler
                    ):
                        bare_raise = False
                        break

            # `raise` as the first operator inside the except handler
            if _is_raising([handler.body[0]]):
                # flags when there is a bare raise
                if handler.body[0].exc is None:
                    bare_raise = True
                    handler_having_bare_raise = handler
                    excs_in_bare_handler = gather_exceptions_from_handler(handler)
        if bare_raise:
            self.add_message("try-except-raise", node=handler_having_bare_raise)
开发者ID:aluoch-sheila,项目名称:NEIGHBOURHOOD,代码行数:49,代码来源:exceptions.py


示例7: visit_slice

    def visit_slice(self, node):
        # Check the type of each part of the slice
        for index in (node.lower, node.upper, node.step):
            if index is None:
                continue

            index_type = safe_infer(index)

            if index_type is None or index_type is astroid.YES:
                continue

            # Constants must of type int or None
            if isinstance(index_type, astroid.Const):
                if isinstance(index_type.value, (int, type(None))):
                    continue
            # Instance values must be of type int, None or an object
            # with __index__
            elif isinstance(index_type, astroid.Instance):
                if index_type.pytype() in (BUILTINS + '.int',
                                           BUILTINS + '.NoneType'):
                    continue

                try:
                    index_type.getattr('__index__')
                    return
                except astroid.NotFoundError:
                    pass

            # Anything else is an error
            self.add_message('invalid-slice-index', node=node)
开发者ID:CoherentLabs,项目名称:depot_tools,代码行数:30,代码来源:typecheck.py


示例8: _determine_function_name_type

def _determine_function_name_type(node):
    """Determine the name type whose regex the a function's name should match.

    :param node: A function node.
    :returns: One of ('function', 'method', 'attr')
    """
    if not node.is_method():
        return 'function'
    if node.decorators:
        decorators = node.decorators.nodes
    else:
        decorators = []
    for decorator in decorators:
        # If the function is a property (decorated with @property
        # or @abc.abstractproperty), the name type is 'attr'.
        if (isinstance(decorator, astroid.Name) or
            (isinstance(decorator, astroid.Getattr) and
             decorator.attrname == 'abstractproperty')):
            infered = safe_infer(decorator)
            if infered and infered.qname() in PROPERTY_CLASSES:
                return 'attr'
        # If the function is decorated using the prop_method.{setter,getter}
        # form, treat it like an attribute as well.
        elif (isinstance(decorator, astroid.Getattr) and
              decorator.attrname in ('setter', 'deleter')):
            return 'attr'
    return 'method'
开发者ID:vbanos,项目名称:grgov-mobile-search,代码行数:27,代码来源:base.py


示例9: visit_asyncwith

    def visit_asyncwith(self, node):
        for ctx_mgr, _ in node.items:
            inferred = checker_utils.safe_infer(ctx_mgr)
            if inferred is None or inferred is astroid.Uninferable:
                continue

            if isinstance(inferred, bases.AsyncGenerator):
                # Check if we are dealing with a function decorated
                # with contextlib.asynccontextmanager.
                if decorated_with(inferred.parent, self._async_generators):
                    continue
            else:
                try:
                    inferred.getattr("__aenter__")
                    inferred.getattr("__aexit__")
                except exceptions.NotFoundError:
                    if isinstance(inferred, astroid.Instance):
                        # If we do not know the bases of this class,
                        # just skip it.
                        if not checker_utils.has_known_bases(inferred):
                            continue
                        # Just ignore mixin classes.
                        if self._ignore_mixin_members:
                            if inferred.name[-5:].lower() == "mixin":
                                continue
                else:
                    continue

            self.add_message(
                "not-async-context-manager", node=node, args=(inferred.name,)
            )
开发者ID:bluesheeptoken,项目名称:pylint,代码行数:31,代码来源:async.py


示例10: nodeisinstance

def nodeisinstance(node, klasses, check_base_classes=True):
    if not isinstance(node, astng.Class):
        return False

    for base in node.bases:
        val = safe_infer(base)
        if not val:
            continue

        if type(val).__name__ == '_Yes':
            continue

        nodes = [val]
        if check_base_classes:
            try:
                nodes = chain([val], val.ancestors())
            except TypeError:
                pass

        for node in nodes:
            qual = '%s.%s' % (node.root().name, node.name)
            if qual in klasses:
                return True

    return False
开发者ID:galileo-press,项目名称:django-lint,代码行数:25,代码来源:utils.py


示例11: _check_open_encoding

 def _check_open_encoding(self, node):
     """Check that an open() call always has an encoding set."""
     try:
         mode_arg = utils.get_argument_from_call(node, position=1,
                                                 keyword='mode')
     except utils.NoSuchArgumentError:
         mode_arg = None
     _encoding = None
     try:
         _encoding = utils.get_argument_from_call(node, position=2)
     except utils.NoSuchArgumentError:
         try:
             _encoding = utils.get_argument_from_call(node,
                                                      keyword='encoding')
         except utils.NoSuchArgumentError:
             pass
     if _encoding is None:
         if mode_arg is not None:
             mode = utils.safe_infer(mode_arg)
         if (mode_arg is not None and isinstance(mode, astroid.Const) and
                 'b' in getattr(mode, 'value', '')):
             # Files opened as binary don't need an encoding.
             return
         else:
             self.add_message('open-without-encoding', node=node)
开发者ID:HalosGhost,项目名称:qutebrowser,代码行数:25,代码来源:openencoding.py


示例12: visit_asyncwith

    def visit_asyncwith(self, node):
        for ctx_mgr, _ in node.items:
            infered = checker_utils.safe_infer(ctx_mgr)
            if infered is None or infered is astroid.YES:
                continue

            if isinstance(infered, astroid.Instance):
                try:
                    infered.getattr('__aenter__')
                    infered.getattr('__aexit__')
                except exceptions.NotFoundError:
                    if isinstance(infered, astroid.Instance):
                        # If we do not know the bases of this class,
                        # just skip it.
                        if not checker_utils.has_known_bases(infered):
                            continue
                        # Just ignore mixin classes.
                        if self._ignore_mixin_members:
                            if infered.name[-5:].lower() == 'mixin':
                                continue
                else:
                    continue

            self.add_message('not-async-context-manager',
                             node=node, args=(infered.name, ))
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:25,代码来源:async.py


示例13: visit_call

 def visit_call(self, node):
     """Visit a Call node."""
     if hasattr(node, 'func'):
         infer = utils.safe_infer(node.func)
         if infer:
             if getattr(node.func, 'name', None) == 'set_trace':
                 self.add_message('set-trace', node=node)
开发者ID:AdaJass,项目名称:qutebrowser,代码行数:7,代码来源:settrace.py


示例14: visit_subscript

    def visit_subscript(self, node):
        supported_protocol = None
        if isinstance(node.value, (astroid.ListComp, astroid.DictComp)):
            return

        if node.ctx == astroid.Load:
            supported_protocol = supports_getitem
            msg = "unsubscriptable-object"
        elif node.ctx == astroid.Store:
            supported_protocol = supports_setitem
            msg = "unsupported-assignment-operation"
        elif node.ctx == astroid.Del:
            supported_protocol = supports_delitem
            msg = "unsupported-delete-operation"

        if isinstance(node.value, astroid.SetComp):
            self.add_message(msg, args=node.value.as_string(), node=node.value)
            return

        if is_inside_abstract_class(node):
            return

        inferred = safe_infer(node.value)
        if inferred is None or inferred is astroid.YES:
            return

        if not supported_protocol(inferred):
            self.add_message(msg, args=node.value.as_string(), node=node.value)
开发者ID:yannack,项目名称:pylint,代码行数:28,代码来源:typecheck.py


示例15: _no_context_variadic

def _no_context_variadic(node, variadic_name, variadic_type, variadics):
    """Verify if the given call node has variadic nodes without context

    This is a workaround for handling cases of nested call functions
    which don't have the specific call context at hand.
    Variadic arguments (variable positional arguments and variable
    keyword arguments) are inferred, inherently wrong, by astroid
    as a Tuple, respectively a Dict with empty elements.
    This can lead pylint to believe that a function call receives
    too few arguments.
    """
    statement = node.statement()
    for name in statement.nodes_of_class(astroid.Name):
        if name.name != variadic_name:
            continue

        inferred = safe_infer(name)
        if isinstance(inferred, (astroid.List, astroid.Tuple)):
            length = len(inferred.elts)
        elif isinstance(inferred, astroid.Dict):
            length = len(inferred.items)
        else:
            continue

        inferred_statement = inferred.statement()
        if not length and isinstance(inferred_statement, astroid.FunctionDef):
            is_in_starred_context = _has_parent_of_type(node, variadic_type, statement)
            used_as_starred_argument = _is_name_used_as_variadic(name, variadics)
            if is_in_starred_context or used_as_starred_argument:
                return True
    return False
开发者ID:yannack,项目名称:pylint,代码行数:31,代码来源:typecheck.py


示例16: _no_context_variadic

    def _no_context_variadic(node):
        """Verify if the given call node has variadic nodes without context

        This is a workaround for handling cases of nested call functions
        which don't have the specific call context at hand.
        Variadic arguments (variable positional arguments and variable
        keyword arguments) are inferred, inherently wrong, by astroid
        as a Tuple, respectively a Dict with empty elements.
        This can lead pylint to believe that a function call receives
        too few arguments.
        """
        for arg in node.args:
            if not isinstance(arg, astroid.Starred):
                continue

            inferred = safe_infer(arg.value)
            if isinstance(inferred, astroid.Tuple):
                length = len(inferred.elts)
            elif isinstance(inferred, astroid.Dict):
                length = len(inferred.items)
            else:
                return False
            if not length and isinstance(inferred.statement(), astroid.FunctionDef):
                return True
        return False
开发者ID:CharlesFerguson,项目名称:pylint,代码行数:25,代码来源:typecheck.py


示例17: _check_raising_stopiteration_in_generator_next_call

    def _check_raising_stopiteration_in_generator_next_call(self, node):
        """Check if a StopIteration exception is raised by the call to next function

        If the next value has a default value, then do not add message.

        :param node: Check to see if this Call node is a next function
        :type node: :class:`astroid.node_classes.Call`
        """

        def _looks_like_infinite_iterator(param):
            inferred = utils.safe_infer(param)
            if inferred is not None or inferred is not astroid.Uninferable:
                return inferred.qname() in KNOWN_INFINITE_ITERATORS
            return False

        inferred = utils.safe_infer(node.func)
        if getattr(inferred, 'name', '') == 'next':
            frame = node.frame()
            # The next builtin can only have up to two
            # positional arguments and no keyword arguments
            has_sentinel_value = len(node.args) > 1
            if (isinstance(frame, astroid.FunctionDef)
                    and frame.is_generator()
                    and not has_sentinel_value
                    and not utils.node_ignores_exception(node, StopIteration)
                    and not _looks_like_infinite_iterator(node.args[0])):
                self.add_message('stop-iteration-return', node=node)
开发者ID:Mariatta,项目名称:pylint,代码行数:27,代码来源:refactoring.py


示例18: _check_consider_get

    def _check_consider_get(self, node):
        def type_and_name_are_equal(node_a, node_b):
            for _type in [astroid.Name, astroid.AssignName]:
                if all(isinstance(_node, _type) for _node in [node_a, node_b]):
                    return node_a.name == node_b.name
            if all(isinstance(_node, astroid.Const) for _node in [node_a, node_b]):
                return node_a.value == node_b.value
            return False

        if_block_ok = (
            isinstance(node.test, astroid.Compare)
            and len(node.body) == 1
            and isinstance(node.body[0], astroid.Assign)
            and isinstance(node.body[0].value, astroid.Subscript)
            and type_and_name_are_equal(node.body[0].value.value, node.test.ops[0][1])
            and type_and_name_are_equal(node.body[0].value.slice.value, node.test.left)
            and len(node.body[0].targets) == 1
            and isinstance(utils.safe_infer(node.test.ops[0][1]), astroid.Dict))

        if if_block_ok and not node.orelse:
            self.add_message('consider-using-get', node=node)
        elif (if_block_ok and len(node.orelse) == 1
              and isinstance(node.orelse[0], astroid.Assign)
              and type_and_name_are_equal(node.orelse[0].targets[0], node.body[0].targets[0])
              and len(node.orelse[0].targets) == 1):
            self.add_message('consider-using-get', node=node)
开发者ID:Mariatta,项目名称:pylint,代码行数:26,代码来源:refactoring.py


示例19: visit_raise

 def visit_raise(self, node):
     """visit raise possibly inferring value"""
     # ignore empty raise
     if node.exc is None:
         return
     if PY3K and node.cause:
         cause = safe_infer(node.cause)
         if cause is YES or cause is None:
             return
         if isinstance(cause, astroid.Const):
             if cause.value is not None:
                 self.add_message('bad-exception-context',
                                  node=node)
         elif (not isinstance(cause, astroid.Class) and
               not inherit_from_std_ex(cause)):
             self.add_message('bad-exception-context',
                              node=node)
     expr = node.exc
     if self._check_raise_value(node, expr):
         return
     else:
         try:
             value = next(unpack_infer(expr))
         except astroid.InferenceError:
             return
         self._check_raise_value(node, value)
开发者ID:willemneal,项目名称:Docky,代码行数:26,代码来源:exceptions.py


示例20: visit_call

 def visit_call(self, node):
     """Visit a Call node."""
     if hasattr(node, 'func'):
         infer = utils.safe_infer(node.func)
         if infer and infer.root().name == 'qutebrowser.config.config':
             if getattr(node.func, 'attrname', None) in ['get', 'set']:
                 self._check_config(node)
开发者ID:DoITCreative,项目名称:qutebrowser,代码行数:7,代码来源:config.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python config.find_pylintrc函数代码示例发布时间:2022-05-25
下一篇:
Python utils.node_ignores_exception函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap