本文整理汇总了Python中ast.Compare方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Compare方法的具体用法?Python ast.Compare怎么用?Python ast.Compare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Compare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def visit_Compare(self, node):
"""Compare nodes occur for all sequences of comparison (`in`, gt, lt, etc.)
operators. We only want to match `___ in instanceof(dict)` here, so we
restrict this to Compare ops with a single operator which is `In` or
`NotIn`.
"""
node = self.generic_visit(node)
if len(node.ops) == 1 and isinstance(node.ops[0], (ast.In, ast.NotIn)):
cmps = node.comparators
if len(cmps) == 1 and self._is_valid_resolved(cmps[0]):
rslvd = cmps[0]
if isinstance(rslvd.value, dict):
node = ast.Compare(
node.left,
node.ops,
[_resolved(rslvd.representation+".keys()",
sorted(rslvd.value.keys()),
valid=False)])
return node
示例2: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def visit_Compare(self, node, **kwargs):
ops = node.ops
comps = node.comparators
# base case: we have something like a CMP b
if len(comps) == 1:
op = self.translate_In(ops[0])
binop = ast.BinOp(op=op, left=node.left, right=comps[0])
return self.visit(binop)
# recursive case: we have a chained comparison, a CMP b CMP c, etc.
left = node.left
values = []
for op, comp in zip(ops, comps):
new_node = self.visit(ast.Compare(comparators=[comp], left=left,
ops=[self.translate_In(op)]))
left = comp
values.append(new_node)
return self.visit(ast.BoolOp(op=ast.And(), values=values))
示例3: format_executing_node_exception
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def format_executing_node_exception(self, event):
try:
assert not NO_ASTTOKENS
node = Source.executing(event.frame).node
assert node
description = {
ast.Call: 'calling',
ast.Subscript: 'subscripting',
ast.Attribute: 'getting attribute',
ast.Compare: 'comparing',
}.get(type(node), 'evaluating')
source = event.source.get_text_with_indentation(node)
plain_prefix = u'!!! When {}: '.format(description)
prefix = u'{c.red}{}{c.reset}'.format(plain_prefix, c=self.c)
return indented_lines(
prefix,
source,
plain_prefix=plain_prefix
)
except Exception:
return []
示例4: normalize_compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def normalize_compare(node):
"""Rewrites a compare expression to a `and` expression
1 < 2 < 3 > 0
1 < 2 and 2 < 3 and 3 > 0"""
and_values = []
left = node.left
for (op, val) in zip(node.ops, node.comparators):
comp = ast.Compare(ops=[op],
left=left,
comparators=[val],
lineno=node.lineno,
col_offset=node.col_offset)
and_values.append(comp)
left = val
return ast.BoolOp(op=ast.And(),
values=and_values,
lineno=node.lineno,
col_offset=node.col_offset)
示例5: _compare_to_3
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def _compare_to_3(
test: ast.Compare,
op: Union[Type[ast.cmpop], Tuple[Type[ast.cmpop], ...]],
) -> bool:
if not (
isinstance(test.ops[0], op) and
isinstance(test.comparators[0], ast.Tuple) and
len(test.comparators[0].elts) >= 1 and
all(isinstance(n, ast.Num) for n in test.comparators[0].elts)
):
return False
# checked above but mypy needs help
elts = cast('List[ast.Num]', test.comparators[0].elts)
return elts[0].n == 3 and all(n.n == 0 for n in elts[1:])
示例6: unparse_IfExp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def unparse_IfExp(self, item):
ops, truth_vals = [], []
if isinstance(item.test, ast.Compare):
left, ops, right = self.unparse(item.test)
else:
result = self.unparse(item.test)
if isinstance(result, dict):
k, v = result.popitem()
if not v:
truth_vals = [False]
for i, op in enumerate(ops):
if i == 0:
truth_vals.append(op(left, right[i]))
else:
truth_vals.append(op(right[i - 1], right[i]))
if all(truth_vals):
unparsed = self.unparse(item.body)
else:
unparsed = self.unparse(item.orelse)
return unparsed
示例7: transform_bool_op
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def transform_bool_op(self, op, values):
name, precedence, assoc = _ExprTranspiler.get_op_info(op)
if name == 'and' or name == 'or':
expr = None
for i in range(1, len(values)):
expr = 'np.logical_%s(%s, {x%d})' % (name, '{x0}' if i == 1 else expr, i)
return expr
xes = []
for i in range(len(values)):
value = values[i]
x = '{x%d}' % i
other_op = getattr(value, 'op', None)
if other_op:
_, other_precedence, other_assoc = self.get_op_info(other_op)
if i == 0 and other_precedence < precedence \
or i > 0 and other_precedence <= precedence:
x = '(%s)' % x
xes.append(x)
return (' %s ' % name).join(xes)
# Compare(left, ops, comparators
示例8: visit_While
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def visit_While(self, node):
label_visitor = LabelVisitor()
test = node.test # the test condition of the while loop
label_visitor.visit(test)
while_node = self.append_node(Node(
'while ' + label_visitor.result + ':',
node,
path=self.filenames[-1]
))
if isinstance(test, ast.Compare):
# quirk. See https://greentreesnakes.readthedocs.io/en/latest/nodes.html#Compare
self.process_loop_funcs(test.left, while_node)
for comp in test.comparators:
self.process_loop_funcs(comp, while_node)
else: # while foo():
self.process_loop_funcs(test, while_node)
return self.loop_node_skeleton(while_node, node)
示例9: verify_ast
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def verify_ast(expr, variables_and_values):
"""Verifies that |expr| is of the form
expr ::= expr ( "or" | "and" ) expr
| identifier "==" ( string | int )
Also collects the variable identifiers and string/int values in the dict
|variables_and_values|, in the form {'var': set([val1, val2, ...]), ...}.
"""
assert isinstance(expr, (ast.BoolOp, ast.Compare))
if isinstance(expr, ast.BoolOp):
assert isinstance(expr.op, (ast.And, ast.Or))
for subexpr in expr.values:
verify_ast(subexpr, variables_and_values)
else:
assert isinstance(expr.left.ctx, ast.Load)
assert len(expr.ops) == 1
assert isinstance(expr.ops[0], ast.Eq)
var_values = variables_and_values.setdefault(expr.left.id, set())
rhs = expr.comparators[0]
assert isinstance(rhs, (ast.Str, ast.Num))
var_values.add(rhs.n if isinstance(rhs, ast.Num) else rhs.s)
示例10: evaluate_node
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def evaluate_node(self, node):
if isinstance(node, ast.BinOp):
return self.operators[type(node.op)](self.evaluate_node(node.left),
self.evaluate_node(node.right))
elif isinstance(node, ast.UnaryOp):
return self.operators[type(node.op)](self.evaluate_node(node.operand))
elif isinstance(node, ast.Compare):
to_string = isinstance(node.comparators[0], ast.Str)
return self.operators[type(node.ops[0])](self.evaluate_attribute_node(node.left, to_string),
self.evaluate_node(node.comparators[0]))
elif isinstance(node, ast.BoolOp):
func = all if isinstance(node.op, ast.And) else any
return func(self.evaluate_node(value) for value in node.values)
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.Attribute):
return self.evaluate_attribute_node(node)
elif isinstance(node, ast.Num):
return node.n
else:
logger.error("Error during parsing")
示例11: validate_condition_node
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def validate_condition_node(self, node):
if isinstance(node, ast.UnaryOp):
if type(node.op) not in self.op_cond:
self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)
self.validate_condition_node(node.operand)
elif isinstance(node, ast.Compare):
if not (len(node.ops) == 1 and len(node.comparators) == 1):
self.raise_syntax_error("", node.lineno, node.col_offset)
if type(node.ops[0]) not in self.op_cond:
self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)
self.validate_compare_nodes(node.left, node.comparators[0])
elif isinstance(node, ast.BoolOp):
for node in node.values:
self.validate_condition_node(node)
else:
self.raise_syntax_error("", node.lineno, node.col_offset)
示例12: translate_compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def translate_compare(self, exp):
if len(exp) < 3:
raise MochiSyntaxError(exp, self.filename)
op_symbol = exp[0]
op_name = op_symbol.name
left, rights = exp[1], exp[2:]
ops = [op_ast_map[op_name]] * len(rights)
pre, left_value = self.translate(left, False)
right_values = []
for right in rights:
right_pre, right_value = self.translate(right, False)
pre = pre + right_pre
right_values.append(right_value)
return pre, ast.Compare(ops=ops,
left=left_value,
comparators=right_values,
lineno=op_symbol.lineno,
col_offset=0)
示例13: visitSubExpr
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def visitSubExpr (self, node, child):
def getPriority (exprNode):
if type (exprNode) in (ast.BinOp, ast.BoolOp):
return self.operators [type (exprNode.op)][1]
elif type (exprNode) == ast.Compare:
return self.operators [type (exprNode.ops [0])][1] # All ops have same priority
elif type (exprNode) == ast.Yield:
return -1000000
else:
return 1000000 # No need for parenthesis
if getPriority (child) <= getPriority (node):
self.emit ('(')
self.visit (child)
self.emit (')')
else:
self.visit (child)
示例14: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def visit_Compare(self, cmp: ast.Compare) -> VisitExprReturnT:
result_actions = []
left, left_actions = self.visit_expr(cmp.left)
result_actions.extend(left_actions)
comparators = []
for comparator in cmp.comparators:
comparator, comparator_actions = self.visit_expr(comparator)
result_actions.extend(comparator_actions)
comparators.append(comparator)
cmp_flattened = ast.Compare(left=left, ops=cmp.ops, comparators=comparators)
result_id = self.next_symbol_id()
assign_node = assign(result_id, cmp_flattened)
return load(result_id), result_actions + [assign_node]
示例15: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Compare [as 别名]
def visit_Compare(self, node: ast.Compare) -> None:
"""
Ensures that compares are written correctly.
Raises:
ConstantCompareViolation
UselessCompareViolation
UselessLenCompareViolation
HeterogenousCompareViolation
ReversedComplexCompareViolation
"""
self._check_literal_compare(node)
self._check_useless_compare(node)
self._check_unpythonic_compare(node)
self._check_heterogenous_operators(node)
self._check_reversed_complex_compare(node)
self.generic_visit(node)