本文整理汇总了Python中ast.In方法的典型用法代码示例。如果您正苦于以下问题:Python ast.In方法的具体用法?Python ast.In怎么用?Python ast.In使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.In方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_MutateAST_visit_compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [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
示例2: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [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
示例3: comp_op_rewrite
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [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]()
示例4: test_decode_source
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def test_decode_source(self):
def check(source, encoding, exception=None, matches=True):
encoded = source.encode(encoding)
if exception:
with self.assertRaises(exception):
Source.decode_source(encoded)
else:
decoded = Source.decode_source(encoded)
if matches:
self.assertEqual(decoded, source)
else:
self.assertNotEqual(decoded, source)
check(u'# coding=utf8\né', 'utf8')
check(u'# coding=gbk\né', 'gbk')
check(u'# coding=utf8\né', 'gbk', exception=UnicodeDecodeError)
check(u'# coding=gbk\né', 'utf8', matches=False)
# In Python 3 the default encoding is assumed to be UTF8
if PY3:
check(u'é', 'utf8')
check(u'é', 'gbk', exception=SyntaxError)
示例5: visit_Assert
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [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
示例6: compare_expected_locs
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [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
####################################################################################################
示例7: _process_frame
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def _process_frame(cls, frame, ignore_set, with_vars, additional_varmap=None):
"""This processes a stack frame into an expect_tests.CheckFrame, which
includes file name, line number, function name (of the function containing
the frame), the parsed statement at that line, and the relevant local
variables/subexpressions (if with_vars is True).
In addition to transforming the expression with _checkTransformer, this
will:
* omit subexpressions which resolve to callable()'s
* omit the overall step ordered dictionary
* transform all subexpression values using render_user_value().
"""
nodes = cls._get_statements_for_frame(frame)
raw_frame, filename, lineno, func_name, _, _ = frame
varmap = None
if with_vars:
varmap = dict(additional_varmap or {})
xfrmr = _checkTransformer(raw_frame.f_locals, raw_frame.f_globals)
xfrmd = xfrmr.visit(ast.Module(copy.deepcopy(nodes)))
for n in itertools.chain(ast.walk(xfrmd), xfrmr.extras):
if isinstance(n, _resolved):
val = n.value
if isinstance(val, ast.AST):
continue
if n.representation in ('True', 'False', 'None'):
continue
if callable(val) or id(val) in ignore_set:
continue
if n.representation not in varmap:
varmap[n.representation] = render_user_value(val)
return CheckFrame(
filename,
lineno,
func_name,
'; '.join(astunparse.unparse(n).strip() for n in nodes),
varmap
)
示例8: translate_In
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def translate_In(self, op):
return ast.Eq() if isinstance(op, ast.In) else op
示例9: push_format_context
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def push_format_context(self):
"""Create a new formatting context.
The format context is used for when an explanation wants to
have a variable value formatted in the assertion message. In
this case the value required can be added using
.explanation_param(). Finally .pop_format_context() is used
to format a string of %-formatted values as added by
.explanation_param().
"""
self.explanation_specifiers = {}
self.stack.append(self.explanation_specifiers)
示例10: visit_Name
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def visit_Name(self, name):
# Display the repr of the name if it's a local variable or
# _should_repr_global_name() thinks it's acceptable.
locs = ast.Call(self.builtin("locals"), [], [])
inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
dorepr = self.helper("_should_repr_global_name", name)
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
return name, self.explanation_param(expr)
示例11: compare_ast_to_ir2
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def compare_ast_to_ir2(ast_node: ast.Compare,
compilation_context: CompilationContext,
in_match_pattern: bool,
check_var_reference: Callable[[ast.Name], None],
match_lambda_argument_names: Set[str],
current_stmt_line: int):
if len(ast_node.ops) != 1 or len(ast_node.comparators) != 1:
raise CompilationError(compilation_context, ast_node, 'Comparison not supported.') # pragma: no cover
if in_match_pattern:
raise CompilationError(compilation_context, ast_node,
'Comparisons are not allowed in match patterns')
lhs = ast_node.left
op = ast_node.ops[0]
rhs = ast_node.comparators[0]
if isinstance(op, ast.Eq):
return eq_ast_to_ir2(lhs, rhs, compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
elif isinstance(op, ast.NotEq):
return not_eq_ast_to_ir2(lhs, rhs, compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
elif isinstance(op, ast.In):
return in_ast_to_ir2(lhs, rhs, compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
elif isinstance(op, ast.Lt):
return int_comparison_ast_to_ir2(lhs, rhs, '<', compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
elif isinstance(op, ast.LtE):
return int_comparison_ast_to_ir2(lhs, rhs, '<=', compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
elif isinstance(op, ast.Gt):
return int_comparison_ast_to_ir2(lhs, rhs, '>', compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
elif isinstance(op, ast.GtE):
return int_comparison_ast_to_ir2(lhs, rhs, '>=', compilation_context, in_match_pattern, check_var_reference, current_stmt_line)
else:
raise CompilationError(compilation_context, ast_node, 'Comparison not supported.') # pragma: no cover
示例12: invert
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [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
示例13: push_format_context
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def push_format_context(self) -> None:
"""Create a new formatting context.
The format context is used for when an explanation wants to
have a variable value formatted in the assertion message. In
this case the value required can be added using
.explanation_param(). Finally .pop_format_context() is used
to format a string of %-formatted values as added by
.explanation_param().
"""
self.explanation_specifiers = {} # type: Dict[str, ast.expr]
self.stack.append(self.explanation_specifiers)
示例14: visit_Name
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def visit_Name(self, name: ast.Name) -> Tuple[ast.Name, str]:
# Display the repr of the name if it's a local variable or
# _should_repr_global_name() thinks it's acceptable.
locs = ast.Call(self.builtin("locals"), [], [])
inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
dorepr = self.helper("_should_repr_global_name", name)
test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
return name, self.explanation_param(expr)
示例15: test_compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import In [as 别名]
def test_compare(self):
left = ast.Name("x", ast.Load())
comp = ast.Compare(left, [ast.In()], [])
self.expr(comp, "no comparators")
comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
self.expr(comp, "different number of comparators and operands")
comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
self.expr(comp, "non-numeric", exc=TypeError)
comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
self.expr(comp, "non-numeric", exc=TypeError)