當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.Is方法代碼示例

本文整理匯總了Python中ast.Is方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.Is方法的具體用法?Python ast.Is怎麽用?Python ast.Is使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.Is方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_MutateAST_visit_compare

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def test_MutateAST_visit_compare(idx, mut_op, lineno, compare_file, compare_expected_locs):
    """Test mutation of the == to != in the compare op."""
    tree = Genome(compare_file).ast

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=compare_expected_locs[idx], mutation=mut_op).visit(
        testing_tree
    )

    # revisit in read-only mode to gather the locations of the new nodes
    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    assert len(mast.locs) == 3

    # check that the lineno marked for mutation is changed, otherwise original ops should
    # still be present without modification
    for loc in mast.locs:
        if loc.lineno == lineno and loc.col_offset == 11:
            assert loc.op_type == mut_op
        else:
            assert loc.op_type in {ast.Eq, ast.Is, ast.In}  # based on compare_file fixture 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:25,代碼來源:test_transformers.py

示例2: comp_op_rewrite

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def comp_op_rewrite(op: t.Union[Tokenizer, t.List[Tokenizer]]):
    """
    ('<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not')
    """
    if isinstance(op, list):
        op = tuple(map(lambda it: it.value, op))
    else:
        op = op.value

    return {
        '<': ast.Lt,
        '>': ast.Gt,
        '==': ast.Eq,
        '>=': ast.GtE,
        '<=': ast.LtE,
        '<>': lambda: raise_exp(NotImplemented),
        '!=': ast.NotEq,
        'in': ast.In,
        ('is', ): ast.Is,
        ('is', 'not'): ast.IsNot,
        ('not', 'in'): ast.NotIn,
    }[op]() 
開發者ID:Xython,項目名稱:YAPyPy,代碼行數:24,代碼來源:helper.py

示例3: _process_is_literal

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def _process_is_literal(
        tokens: List[Token],
        i: int,
        compare: Union[ast.Is, ast.IsNot],
) -> None:
    while tokens[i].src != 'is':
        i -= 1
    if isinstance(compare, ast.Is):
        tokens[i] = tokens[i]._replace(src='==')
    else:
        tokens[i] = tokens[i]._replace(src='!=')
        # since we iterate backward, the dummy tokens keep the same length
        i += 1
        while tokens[i].src != 'not':
            tokens[i] = Token('DUMMY', '')
            i += 1
        tokens[i] = Token('DUMMY', '') 
開發者ID:asottile,項目名稱:pyupgrade,代碼行數:19,代碼來源:pyupgrade.py

示例4: visit_Assert

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def visit_Assert(self, node):
        if is_binary_comparison(node):
            if is_comparison_type(node, ast.Eq):
                return make_call_node(node, assert_equal.__name__)
            elif is_comparison_type(node, ast.NotEq):
                return make_call_node(node, assert_not_equal.__name__)
            elif is_comparison_type(node, ast.In):
                return make_call_node(node, assert_in.__name__)
            elif is_comparison_type(node, ast.NotIn):
                return make_call_node(node, assert_not_in.__name__)
            elif is_comparison_type(node, ast.Is):
                return make_call_node(node, assert_is.__name__)
            elif is_comparison_type(node, ast.IsNot):
                return make_call_node(node, assert_is_not.__name__)
            elif is_comparison_type(node, ast.Lt):
                return make_call_node(node, assert_less_than.__name__)
            elif is_comparison_type(node, ast.LtE):
                return make_call_node(node, assert_less_than_equal_to.__name__)
            elif is_comparison_type(node, ast.Gt):
                return make_call_node(node, assert_greater_than.__name__)
            elif is_comparison_type(node, ast.GtE):
                return make_call_node(node, assert_greater_than_equal_to.__name__)

        return node 
開發者ID:darrenburns,項目名稱:ward,代碼行數:26,代碼來源:rewrite.py

示例5: compare_expected_locs

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def compare_expected_locs():
    """The compare expected locations based on the fixture"""
    # Py 3.7
    if sys.version_info < (3, 8):
        return [
            LocIndex(ast_class="Compare", lineno=2, col_offset=11, op_type=ast.Eq),
            LocIndex(ast_class="CompareIs", lineno=5, col_offset=11, op_type=ast.Is),
            LocIndex(ast_class="CompareIn", lineno=8, col_offset=11, op_type=ast.In),
        ]
    # Py 3.8
    return [
        LocIndex(
            ast_class="Compare",
            lineno=2,
            col_offset=11,
            op_type=ast.Eq,
            end_lineno=2,
            end_col_offset=17,
        ),
        LocIndex(
            ast_class="CompareIs",
            lineno=5,
            col_offset=11,
            op_type=ast.Is,
            end_lineno=5,
            end_col_offset=17,
        ),
        LocIndex(
            ast_class="CompareIn",
            lineno=8,
            col_offset=11,
            op_type=ast.In,
            end_lineno=8,
            end_col_offset=17,
        ),
    ]


####################################################################################################
# TRANSFORMERS: IF FIXTURES
#################################################################################################### 
開發者ID:EvanKepner,項目名稱:mutatest,代碼行數:43,代碼來源:conftest.py

示例6: warn_about_none_ast

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def warn_about_none_ast(self, node, module_path, lineno):
        """
        Returns an AST issuing a warning if the value of node is `None`.
        This is used to warn the user when asserting a function that asserts
        internally already.
        See issue #3191 for more details.
        """

        # Using parse because it is different between py2 and py3.
        AST_NONE = ast.parse("None").body[0].value
        val_is_none = ast.Compare(node, [ast.Is()], [AST_NONE])
        send_warning = ast.parse(
            """\
from _pytest.warning_types import PytestAssertRewriteWarning
from warnings import warn_explicit
warn_explicit(
    PytestAssertRewriteWarning('asserting the value None, please use "assert is None"'),
    category=None,
    filename={filename!r},
    lineno={lineno},
)
            """.format(
                filename=module_path, lineno=lineno
            )
        ).body
        return ast.If(val_is_none, send_warning, []) 
開發者ID:sofia-netsurv,項目名稱:python-netsurv,代碼行數:28,代碼來源:rewrite.py

示例7: __init__

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def __init__(self) -> None:
        self.dicts: Dict[Offset, ListCompOrGeneratorExp] = {}
        self.sets: Dict[Offset, ast.expr] = {}
        self.set_empty_literals: Dict[Offset, ListOrTuple] = {}
        self.is_literal: Dict[Offset, Union[ast.Is, ast.IsNot]] = {} 
開發者ID:asottile,項目名稱:pyupgrade,代碼行數:7,代碼來源:pyupgrade.py

示例8: visit_Compare

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def visit_Compare(self, node: ast.Compare) -> None:
        left = node.left
        for op, right in zip(node.ops, node.comparators):
            if (
                    isinstance(op, (ast.Is, ast.IsNot)) and
                    (
                        isinstance(left, LITERAL_TYPES) or
                        isinstance(right, LITERAL_TYPES)
                    )
            ):
                self.is_literal[_ast_to_offset(right)] = op
            left = right

        self.generic_visit(node) 
開發者ID:asottile,項目名稱:pyupgrade,代碼行數:16,代碼來源:pyupgrade.py

示例9: invert

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def invert(node):
    """
    Invert the operation in an ast node object (get its negation).

    Args:
        node: An ast node object.

    Returns:
        An ast node object containing the inverse (negation) of the input node.
    """
    inverse = {ast.Eq: ast.NotEq,
               ast.NotEq: ast.Eq,
               ast.Lt: ast.GtE,
               ast.LtE: ast.Gt,
               ast.Gt: ast.LtE,
               ast.GtE: ast.Lt,
               ast.Is: ast.IsNot,
               ast.IsNot: ast.Is,
               ast.In: ast.NotIn,
               ast.NotIn: ast.In}

    if type(node) == ast.Compare:
        op = type(node.ops[0])
        inverse_node = ast.Compare(left=node.left, ops=[inverse[op]()],
                                   comparators=node.comparators)
    elif isinstance(node, ast.BinOp) and type(node.op) in inverse:
        op = type(node.op)
        inverse_node = ast.BinOp(node.left, inverse[op](), node.right)
    elif type(node) == ast.NameConstant and node.value in [True, False]:
        inverse_node = ast.NameConstant(value=not node.value)
    else:
        inverse_node = ast.UnaryOp(op=ast.Not(), operand=node)

    return inverse_node 
開發者ID:coetaur0,項目名稱:staticfg,代碼行數:36,代碼來源:builder.py

示例10: test_correct_comparing

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def test_correct_comparing(self, node: Any = None) -> None:
        if not node:
            return
        if isinstance(node, Iterable):
            for item in node:
                self.test_correct_comparing(item)
            return

        if isinstance(node, ast.Expr):
            self.test_correct_comparing(node.value)
            return

        if isinstance(node, ast.BinOp):
            self.test_correct_comparing(node.left)
            self.test_correct_comparing(node.right)
            return

        if isinstance(node, ast.BoolOp):
            for val in node.values:
                self.test_correct_comparing(val)
            return

        if isinstance(node, ast.IfExp):
            self.test_correct_comparing(node.body)
            self.test_correct_comparing(node.test)
            self.test_correct_comparing(node.orelse)
            return

        if isinstance(node, ast.Compare):
            if isinstance(node.left, ast.Name):
                comparator = node.comparators[0]
                operation = node.ops[0]
                if isinstance(operation, ast.Is) or isinstance(operation, ast.IsNot):
                    # Is or IsNot are allowed for NameConstant - None - only
                    if isinstance(comparator, ast.NameConstant) and comparator.value is None:
                        return
                    node_text = self.stringify_node(node)
                    self.warnings.append(f'Checking "{node_text}" '
                                         'is unsafe, use "==" operator instead')
                    self.test_correct_comparing(comparator) 
開發者ID:LexPredict,項目名稱:lexpredict-contraxsuite,代碼行數:42,代碼來源:expressions.py

示例11: visit_Compare

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def visit_Compare(self, node: ast.Compare) -> Any:
        """Recursively visit the comparators and apply the operations on them."""
        # pylint: disable=too-many-branches
        left = self.visit(node=node.left)

        comparators = [self.visit(node=comparator) for comparator in node.comparators]

        result = None  # type: Optional[Any]
        for comparator, op in zip(comparators, node.ops):
            if isinstance(op, ast.Eq):
                comparison = left == comparator
            elif isinstance(op, ast.NotEq):
                comparison = left != comparator
            elif isinstance(op, ast.Lt):
                comparison = left < comparator
            elif isinstance(op, ast.LtE):
                comparison = left <= comparator
            elif isinstance(op, ast.Gt):
                comparison = left > comparator
            elif isinstance(op, ast.GtE):
                comparison = left >= comparator
            elif isinstance(op, ast.Is):
                comparison = left is comparator
            elif isinstance(op, ast.IsNot):
                comparison = left is not comparator
            elif isinstance(op, ast.In):
                comparison = left in comparator
            elif isinstance(op, ast.NotIn):
                comparison = left not in comparator
            else:
                raise NotImplementedError("Unhandled op of {}: {}".format(node, op))

            if result is None:
                result = comparison
            else:
                result = result and comparison

            left = comparator

        self.recomputed_values[node] = result
        return result 
開發者ID:Parquery,項目名稱:icontract,代碼行數:43,代碼來源:_recompute.py

示例12: COMPARE

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def COMPARE(self, node):
        left = node.left
        for op, right in zip(node.ops, node.comparators):
            if (
                    isinstance(op, (ast.Is, ast.IsNot)) and (
                        _is_const_non_singleton(left) or
                        _is_const_non_singleton(right)
                    )
            ):
                self.report(messages.IsLiteral, node)
            left = right

        self.handleChildren(node) 
開發者ID:PyCQA,項目名稱:pyflakes,代碼行數:15,代碼來源:checker.py

示例13: p_comp_op_9

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def p_comp_op_9(p):
    '''comp_op : IS'''
    #             1
    p[0] = ast.Is(rule=inspect.currentframe().f_code.co_name) 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:6,代碼來源:hgawk_grammar.py

示例14: _

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def _(
    src=each("assert x == y", "assert x is y", "assert x < y", "assert x is not y"),
    node_type=each(ast.Eq, ast.Is, ast.Lt, ast.IsNot),
):
    assert_node = ast.parse(src).body[0]
    assert is_comparison_type(assert_node, node_type) 
開發者ID:darrenburns,項目名稱:ward,代碼行數:8,代碼來源:test_rewrite.py

示例15: _check_constant

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import Is [as 別名]
def _check_constant(self, op: ast.cmpop, comparator: ast.expr) -> None:
        if not isinstance(op, (ast.Eq, ast.NotEq, ast.Is, ast.IsNot)):
            return
        real = get_assigned_expr(comparator)
        if not isinstance(real, (ast.List, ast.Dict, ast.Tuple)):
            return

        length = len(real.keys) if isinstance(
            real, ast.Dict,
        ) else len(real.elts)

        if not length:
            self.add_violation(FalsyConstantCompareViolation(comparator)) 
開發者ID:wemake-services,項目名稱:wemake-python-styleguide,代碼行數:15,代碼來源:compares.py


注:本文中的ast.Is方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。