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


Python astroid.If方法代码示例

本文整理汇总了Python中astroid.If方法的典型用法代码示例。如果您正苦于以下问题:Python astroid.If方法的具体用法?Python astroid.If怎么用?Python astroid.If使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在astroid的用法示例。


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

示例1: _if_statement_is_always_returning

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _if_statement_is_always_returning(if_node):
    def _has_return_node(elems, scope):
        for node in elems:
            if isinstance(node, astroid.If):
                yield _if_statement_is_always_returning(node)
            elif isinstance(node, astroid.Return):
                yield node.scope() is scope

    scope = if_node.scope()
    body_returns = _all_elements_are_true(
        _has_return_node(if_node.body, scope=scope)
    )
    if if_node.orelse:
        orelse_returns = _all_elements_are_true(
            _has_return_node(if_node.orelse, scope=scope)
        )
    else:
        orelse_returns = False

    return body_returns and orelse_returns 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:22,代码来源:refactoring.py

示例2: _is_actual_elif

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _is_actual_elif(self, node):
        """Check if the given node is an actual elif

        This is a problem we're having with the builtin ast module,
        which splits `elif` branches into a separate if statement.
        Unfortunately we need to know the exact type in certain
        cases.
        """

        if isinstance(node.parent, astroid.If):
            orelse = node.parent.orelse
            # current if node must directly follow a "else"
            if orelse and orelse == [node]:
                if (node.lineno, node.col_offset) in self._elifs:
                    return True
        return False 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:18,代码来源:refactoring.py

示例3: visit_functiondef

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def visit_functiondef(self, node):
        if not self.linter.is_message_enabled('wrong-import-position', node.fromlineno):
            return
        # If it is the first non import instruction of the module, record it.
        if self._first_non_import_node:
            return

        # Check if the node belongs to an `If` or a `Try` block. If they
        # contain imports, skip recording this node.
        if not isinstance(node.parent.scope(), astroid.Module):
            return

        root = node
        while not isinstance(root.parent, astroid.Module):
            root = root.parent

        if isinstance(root, (astroid.If, astroid.TryFinally, astroid.TryExcept)):
            if any(root.nodes_of_class((astroid.Import, astroid.ImportFrom))):
                return

        self._first_non_import_node = node 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:23,代码来源:imports.py

示例4: _find_frame_imports

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _find_frame_imports(name, frame):
    """
    Detect imports in the frame, with the required
    *name*. Such imports can be considered assignments.
    Returns True if an import for the given name was found.
    """
    imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
    for import_node in imports:
        for import_name, import_alias in import_node.names:
            # If the import uses an alias, check only that.
            # Otherwise, check only the import name.
            if import_alias:
                if import_alias == name:
                    return True
            elif import_name and import_name == name:
                return True
    return None 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:19,代码来源:variables.py

示例5: visit_functiondef

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def visit_functiondef(self, node):
        if node.is_method():
            if node.name in self._unused_magic_methods:
                method_name = node.name
                if node.name.startswith("__"):
                    method_name = node.name[2:-2]
                self.add_message(method_name + "-method", node=node)
            elif node.name == "next":
                # If there is a method named `next` declared, if it is invokable
                # with zero arguments then it implements the Iterator protocol.
                # This means if the method is an instance method or a
                # classmethod 1 argument should cause a failure, if it is a
                # staticmethod 0 arguments should cause a failure.
                failing_arg_count = 1
                if utils.decorated_with(node, [bases.BUILTINS + ".staticmethod"]):
                    failing_arg_count = 0
                if len(node.args.args) == failing_arg_count:
                    self.add_message("next-method-defined", node=node) 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:20,代码来源:python3.py

示例6: visit_functiondef

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def visit_functiondef(self, node):
        if not self.linter.is_message_enabled("wrong-import-position", node.fromlineno):
            return
        # If it is the first non import instruction of the module, record it.
        if self._first_non_import_node:
            return

        # Check if the node belongs to an `If` or a `Try` block. If they
        # contain imports, skip recording this node.
        if not isinstance(node.parent.scope(), astroid.Module):
            return

        root = node
        while not isinstance(root.parent, astroid.Module):
            root = root.parent

        if isinstance(root, (astroid.If, astroid.TryFinally, astroid.TryExcept)):
            if any(root.nodes_of_class((astroid.Import, astroid.ImportFrom))):
                return

        self._first_non_import_node = node 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:23,代码来源:imports.py

示例7: node_type

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
    """Return the inferred type for `node`

    If there is more than one possible type, or if inferred type is Uninferable or None,
    return None
    """
    # check there is only one possible type for the assign node. Else we
    # don't handle it for now
    types = set()
    try:
        for var_type in node.infer():
            if var_type == astroid.Uninferable or is_none(var_type):
                continue
            types.add(var_type)
            if len(types) > 1:
                return None
    except astroid.InferenceError:
        return None
    return types.pop() if types else None 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:21,代码来源:utils.py

示例8: visit_if

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def visit_if(self, node):
        if isinstance(node.parent, astroid.If):
            orelse = node.parent.orelse
            # current if node must directly follow a "else"
            if orelse and orelse == [node]:
                if not self._elifs[self._if_counter]:
                    self.add_message('else-if-used', node=node)
        self._if_counter += 1 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:10,代码来源:check_elif.py

示例9: _check_and_add_messages

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _check_and_add_messages(self):
        assigns = self._assigns.pop()
        for name, args in assigns.items():
            if len(args) <= 1:
                continue
            orig_node, orig_type = args[0]
            # Check if there is a type in the following nodes that would be
            # different from orig_type.
            for redef_node, redef_type in args[1:]:
                if redef_type == orig_type:
                    continue
                # if a variable is defined to several types in a if node,
                # this is not actually redefining.
                orig_parent = orig_node.parent
                redef_parent = redef_node.parent
                if isinstance(orig_parent, astroid.If):
                    if orig_parent == redef_parent:
                        if (redef_node in orig_parent.orelse and
                                orig_node not in orig_parent.orelse):
                            orig_node, orig_type = redef_node, redef_type
                            continue
                    elif (isinstance(redef_parent, astroid.If) and
                          redef_parent in orig_parent.nodes_of_class(astroid.If)):
                        orig_node, orig_type = redef_node, redef_type
                        continue
                orig_type = orig_type.replace(BUILTINS + ".", '')
                redef_type = redef_type.replace(BUILTINS + ".", '')
                self.add_message('redefined-variable-type', node=redef_node,
                                 args=(name, orig_type, redef_type))
                break 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:32,代码来源:redefined_variable_type.py

示例10: visit_if

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def visit_if(self, node):
        """increments the branches counter and checks boolean expressions"""
        self._check_boolean_expressions(node)
        branches = 1
        # don't double count If nodes coming from some 'elif'
        if node.orelse and (len(node.orelse) > 1 or
                            not isinstance(node.orelse[0], If)):
            branches += 1
        self._inc_branch(node, branches)
        self._stmts += branches 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:12,代码来源:design_analysis.py

示例11: _node_is_test_condition

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _node_is_test_condition(node):
    """ Checks if node is an if, while, assert or if expression statement."""
    return isinstance(node, (astroid.If, astroid.While, astroid.Assert, astroid.IfExp)) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:5,代码来源:refactoring.py

示例12: is_trailing_comma

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def is_trailing_comma(tokens, index):
    """Check if the given token is a trailing comma

    :param tokens: Sequence of modules tokens
    :type tokens: list[tokenize.TokenInfo]
    :param int index: Index of token under check in tokens
    :returns: True if the token is a comma which trails an expression
    :rtype: bool
    """
    token = tokens[index]
    if token.exact_type != tokenize.COMMA:
        return False
    # Must have remaining tokens on the same line such as NEWLINE
    left_tokens = itertools.islice(tokens, index + 1, None)
    same_line_remaining_tokens = list(itertools.takewhile(
        lambda other_token, _token=token: other_token.start[0] == _token.start[0],
        left_tokens
    ))
    # Note: If the newline is tokenize.NEWLINE and not tokenize.NL
    # then the newline denotes the end of expression
    is_last_element = all(
        other_token.type in (tokenize.NEWLINE, tokenize.COMMENT)
        for other_token in same_line_remaining_tokens
    )
    if not same_line_remaining_tokens or not is_last_element:
        return False
    def get_curline_index_start():
        """Get the index denoting the start of the current line"""
        for subindex, token in enumerate(reversed(tokens[:index])):
            # See Lib/tokenize.py and Lib/token.py in cpython for more info
            if token.type in (tokenize.NEWLINE, tokenize.NL):
                return index - subindex
        return 0
    curline_start = get_curline_index_start()
    for prevtoken in tokens[curline_start:index]:
        if '=' in prevtoken.string:
            return True
    return False 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:40,代码来源:refactoring.py

示例13: _in_iterating_context

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _in_iterating_context(node):
    """Check if the node is being used as an iterator.

    Definition is taken from lib2to3.fixer_util.in_special_context().
    """
    parent = node.parent
    # Since a call can't be the loop variant we only need to know if the node's
    # parent is a 'for' loop to know it's being used as the iterator for the
    # loop.
    if isinstance(parent, astroid.For):
        return True
    # Need to make sure the use of the node is in the iterator part of the
    # comprehension.
    if isinstance(parent, astroid.Comprehension):
        if parent.iter == node:
            return True
    # Various built-ins can take in an iterable or list and lead to the same
    # value.
    elif isinstance(parent, astroid.Call):
        if isinstance(parent.func, astroid.Name):
            parent_scope = parent.func.lookup(parent.func.name)[0]
            if _is_builtin(parent_scope) and parent.func.name in _ACCEPTS_ITERATOR:
                return True
        elif isinstance(parent.func, astroid.Attribute):
            if parent.func.attrname == 'join':
                return True
    # If the call is in an unpacking, there's no need to warn,
    # since it can be considered iterating.
    elif (isinstance(parent, astroid.Assign) and
          isinstance(parent.targets[0], (astroid.List, astroid.Tuple))):
        if len(parent.targets[0].elts) > 1:
            return True
    return False 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:35,代码来源:python3.py

示例14: _is_conditional_import

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def _is_conditional_import(node):
    """Checks if an import node is in the context of a conditional.
    """
    parent = node.parent
    return isinstance(parent, (astroid.TryExcept, astroid.ExceptHandler,
                               astroid.If, astroid.IfExp)) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:8,代码来源:python3.py

示例15: test_subscript_load_ctx

# 需要导入模块: import astroid [as 别名]
# 或者: from astroid import If [as 别名]
def test_subscript_load_ctx(node):
    """Test visitor of Subscript node when loaded in an (if) expression."""
    load_node = astroid.If()
    load_node.postinit(astroid.Const(True), [node], [])
    module, _ = cs._parse_text(load_node)
    for subscript_node in module.nodes_of_class(astroid.Subscript):
        list_node = subscript_node.value
        assert subscript_node.inf_type.getValue() == List[list_node.elts[0].inf_type.getValue()] 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:10,代码来源:test_subscript.py


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