本文整理汇总了Python中ast.copy_location函数的典型用法代码示例。如果您正苦于以下问题:Python copy_location函数的具体用法?Python copy_location怎么用?Python copy_location使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了copy_location函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: visit_Assert
def visit_Assert(self, node): # pylint: disable=invalid-name, no-self-use
"""Visit Assert
Convert BinOp asserts into unittest's assert equals
"""
args = [node.test]
assertion = 'assertTrue'
if isinstance(node.test, ast.Compare) and len(node.test.ops) == 1:
args = [node.test.left, node.test.comparators[0]]
assertion = {
ast.Eq: 'assertEqual',
ast.NotEq: 'assertNotEqual',
ast.Lt: 'assertLess',
ast.LtE: 'assertLessEqual',
ast.Gt: 'assertGreater',
ast.GtE: 'assertGreaterEqual',
ast.Is: 'assertIs',
ast.IsNot: 'assertIsNot',
ast.In: 'assertIn',
ast.NotIn: 'assertNotIn',
}[node.test.ops[0].__class__]
if node.msg:
args.append(node.msg)
return ast.copy_location(ast.Expr(ast.copy_location(call(
ast.copy_location(ast.Attribute(
ast.Name('self', ast.Load()),
assertion, ast.Load()
), node),
args
), node)), node)
开发者ID:JoaoFelipe,项目名称:ipython-unittest,代码行数:29,代码来源:magics.py
示例2: visit_Name
def visit_Name(self, old_node):
node = nodes.Name(old_node.id, old_node.ctx)
ast.copy_location(node, old_node)
# Set some defaults
node.cf_maybe_null = True
node.cf_is_null = False
node.allow_null = False
node.name = node.id
if isinstance(node.ctx, ast.Param):
var = self.symtab[node.name]
var.is_arg = True
self.flow.mark_assignment(node, None, var, assignment=None)
elif isinstance(node.ctx, ast.Load):
var = self.symtab.lookup(node.name)
if var:
# Local variable
self.flow.mark_reference(node, var)
# Set position of assignment of this definition
if isinstance(node.ctx, (ast.Param, ast.Store)):
var = self.symtab[node.name]
if var.lineno == -1:
var.lineno = getattr(node, "lineno", 0)
var.col_offset = getattr(node, "col_offset", 0)
return node
开发者ID:KanzhiWu,项目名称:numba,代码行数:28,代码来源:control_flow.py
示例3: visit_BinOp
def visit_BinOp(self, node):
node = self.generic_visit(node)
if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num):
value = eval(compile(ast.copy_location(ast.Expression(body=node), node), '', 'eval'))
return ast.copy_location(ast.Num(n=value), node)
else:
return node
开发者ID:ml-lab,项目名称:TerpreT,代码行数:7,代码来源:unroller.py
示例4: test_load_const
def test_load_const(self):
consts = [None,
True, False,
124,
2.0,
3j,
"unicode",
b'bytes',
(1, 2, 3)]
code = '\n'.join(map(repr, consts))
code += '\n...'
code_consts = [const for const in consts
if (not isinstance(const, (str, int, float, complex))
or isinstance(const, bool))]
code_consts.append(Ellipsis)
# the compiler adds a final "LOAD_CONST None"
code_consts.append(None)
tree = ast.parse(code)
self.assertEqual(self.get_load_const(tree), code_consts)
# Replace expression nodes with constants
for expr_node, const in zip(tree.body, consts):
assert isinstance(expr_node, ast.Expr)
new_node = ast.Constant(value=const)
ast.copy_location(new_node, expr_node.value)
expr_node.value = new_node
self.assertEqual(self.get_load_const(tree), code_consts)
开发者ID:mancoast,项目名称:cpython,代码行数:31,代码来源:test_ast.py
示例5: prepare
def prepare(self):
for i in self.children:
i.prepare()
# Compile the keywords.
keyword_values = { }
keyword_keys = [ ]
keyword_exprs = [ ]
for k, expr in self.keyword:
node = py_compile(expr, 'eval', ast_node=True)
if is_constant(node):
keyword_values[k] = py_eval_bytecode(compile_expr(node))
else:
keyword_keys.append(ast.Str(s=k))
keyword_exprs.append(node)
if keyword_values:
self.keyword_values = keyword_values
else:
self.keyword_values = None
if keyword_keys:
node = ast.Dict(keys=keyword_keys, values=keyword_exprs)
ast.copy_location(node, keyword_exprs[0])
self.keyword_exprs = compile_expr(node)
else:
self.keyword_exprs = None
开发者ID:duanemoody,项目名称:renpy,代码行数:32,代码来源:slast.py
示例6: test_ast_2
def test_ast_2(self):
self.ns['FOOBAR'] = ''
expr = ast.Expression()
expr.body = ast.parse('FOO+BAR').body[0].value
ast.copy_location(expr, expr.body)
self.ns['FOOBAR'] = Expression(expr)
self.assertEqual(self.ns['FOOBAR'].get(), 'foobar')
开发者ID:XD-embedded,项目名称:xd-build-core,代码行数:7,代码来源:data_expr_test.py
示例7: visit_If
def visit_If(self, node):
exit_block = self.flow.exit_block(label='exit_if', pos=node)
# Condition
cond_block = self.flow.nextblock(self.flow.block, label='if_cond',
is_expr=True, pos=node.test)
node.test = self.visit(node.test)
# Body
if_block = self.flow.nextblock(label='if_body', pos=node.body[0])
self.visitlist(node.body)
if self.flow.block:
self.flow.block.add_child(exit_block)
# Else clause
if node.orelse:
else_block = self.flow.nextblock(cond_block,
label='else_body',
pos=node.orelse[0])
self.visitlist(node.orelse)
if self.flow.block:
self.flow.block.add_child(exit_block)
else:
cond_block.add_child(exit_block)
else_block = None
new_node = nodes.build_if(cond_block=cond_block, test=node.test,
if_block=if_block, body=node.body,
else_block=else_block, orelse=node.orelse,
exit_block=exit_block)
ast.copy_location(new_node, node)
return self.exit_block(exit_block, new_node)
开发者ID:ASPP,项目名称:numba,代码行数:32,代码来源:control_flow.py
示例8: visit_Name
def visit_Name(self, node):
new_node = ast.Name(
self._visit(node.id),
self._visit(node.ctx),
)
ast.copy_location(new_node, node)
return new_node
开发者ID:nofnofnof,项目名称:CNNForFakePapersDetection,代码行数:7,代码来源:ast2.py
示例9: visit_FunctionDef
def visit_FunctionDef(self, node):
if node.name.startswith('test'):
statements = [stmt for stmt in node.body
if isinstance(stmt, ast.Assign) or
isinstance(stmt, ast.Expr)
]
self.statements += statements
self.tracking[node.name] = None
body = node.body
new_stmts = []
for _node in node.body:
new_stmts.append(createNode(node.name, _node))
new_node_body = []
for i in xrange(0, len(new_stmts)):
new_node = new_stmts[i]
old_node = body[i]
if isinstance(new_node, list):
for _new_node in new_node:
ast.copy_location(_new_node, old_node)
new_node_body.append(_new_node)
new_node_body.append(old_node)
elif isinstance(new_node, ast.TryExcept):
ast.copy_location(new_node, old_node)
new_node_body.append(new_node)
new_node_body.append(old_node)
else:
new_node_body.append(new_node)
node.body = new_node_body
ast.fix_missing_locations(node)
return node
ast.fix_missing_locations(node)
return node
开发者ID:yeukhon,项目名称:testcapture,代码行数:35,代码来源:dump.py
示例10: __visit_FunctionDef
def __visit_FunctionDef(self, node):
new_node = ast.FunctionDef(args=self.visit_arguments(node.args),
body=self._visit_list(node.body),
decorator_list=self._visit_list(node.decorator_list),
name=node.name)
ast.copy_location(new_node, node)
return new_node
开发者ID:ASPP,项目名称:numba,代码行数:7,代码来源:astsix.py
示例11: visit_BinOp
def visit_BinOp(self, node: ast.BinOp):
node = self.generic_visit(node)
if self._is_numeric_pow(node):
left, right = node.left, node.right
degree = ( right.n if isinstance(right, ast.Num)
else -right.operand.n if isinstance(right.op, ast.USub)
else right.operand.n )
degree = int(degree)
if abs(degree) == 0:
node = ast.copy_location(ast.Num(n = 1), node)
elif abs(degree) == 1:
node = node.left
elif 2 <= abs(degree) <= self.MAX_DEGREE:
for _ in range(1, abs(degree)):
new_node = ast.BinOp\
( left = left
, op = ast.Mult()
, right = copy(node.left)
)
left = new_node = ast.copy_location(new_node, node)
node = new_node
else:
return node
if degree < 0:
new_node = ast.BinOp\
( left = ast.Num(n = 1)
, op = ast.Div()
, right = node
)
node = ast.copy_location(new_node, node)
return node
开发者ID:Amper,项目名称:opyum,代码行数:31,代码来源:pow_to_mult.py
示例12: visit_Name
def visit_Name(self, node):
if self.randomize():
if node.id == 'forall':
return ast.copy_location(_ast.Name(id='exists'), node)
elif node.id == 'exists':
return ast.copy_location(_ast.Name(id='forall'), node)
return node
开发者ID:hiranya911,项目名称:rest-coder,代码行数:7,代码来源:predicate_parser.py
示例13: visit_If
def visit_If(self, node):
node = self.generic_visit(node)
if (node.orelse
and len(node.orelse) == 1
and isinstance(node.orelse[0], ast.Pass)
):
node.orelse = []
if (len(node.body) == 1
and isinstance(node.body[0], ast.Pass)
):
if node.orelse:
node_test = ast.UnaryOp(op=ast.Not(), operand=node.test)
if (len(node.orelse) == 1
and isinstance(node.orelse[0], ast.If)
):
node_test = ast.BoolOp\
( op = ast.And()
, values = [node_test, node.orelse[0].test]
)
node.test = ast.copy_location(node_test, node.orelse[0].test)
node.body = node.orelse[0].body
node.orelse = node.orelse[0].orelse
else:
node.test = ast.copy_location(node_test, node.test)
node.body = node.orelse
node.orelse = []
else:
node = None
return node
开发者ID:Amper,项目名称:opyum,代码行数:29,代码来源:dead_code_elimination.py
示例14: test_load_const
def test_load_const(self):
consts = [None,
True, False,
124,
2.0,
3j,
"unicode",
b'bytes',
(1, 2, 3)]
code = '\n'.join(['x={!r}'.format(const) for const in consts])
code += '\nx = ...'
consts.extend((Ellipsis, None))
tree = ast.parse(code)
self.assertEqual(self.get_load_const(tree),
consts)
# Replace expression nodes with constants
for assign, const in zip(tree.body, consts):
assert isinstance(assign, ast.Assign), ast.dump(assign)
new_node = ast.Constant(value=const)
ast.copy_location(new_node, assign.value)
assign.value = new_node
self.assertEqual(self.get_load_const(tree),
consts)
开发者ID:3lnc,项目名称:cpython,代码行数:27,代码来源:test_ast.py
示例15: visit_Assign
def visit_Assign(self, node):
if isinstance(node.value, ast.Subscript) and isinstance(node.value.value, ast.Call):
subscr = node.value
call = subscr.value
if len(node.targets) > 1:
error.error('Cannot use multiple assignment in array declaration.', node)
variable_name = node.targets[0].id
value_type = call.func.id
declaration_args = call.args
# Get the indices being accessed.
shape = slice_node_to_tuple_of_numbers(subscr.slice)
new_assigns = []
for indices in itertools.product(*[range(n) for n in shape]):
index_name = flattened_array_name(variable_name, indices)
new_index_name_node = ast.copy_location(ast.Name(index_name, ast.Store()), node)
new_value_type_node = ast.copy_location(ast.Name(value_type, ast.Load()), node)
new_declaration_args = [copy.deepcopy(arg) for arg in declaration_args]
new_call_node = ast.copy_location(ast.Call(new_value_type_node, new_declaration_args, [], None, None), node)
new_assign = ast.Assign([new_index_name_node], new_call_node)
new_assign = ast.copy_location(new_assign, node)
new_assigns.append(new_assign)
return new_assigns
else:
return node
开发者ID:ml-lab,项目名称:TerpreT,代码行数:28,代码来源:unroller.py
示例16: CALL
def CALL(self, tree):
is_demandload = is_demandload_regex = False
if isinstance(tree.func, _ast.Attribute):
if not isinstance(tree.func.value, _ast.Name):
# this means it's a multilevel lookup;
# pkgcore.ebuild.ebuild_src.some_func
# ignore it; it *could* miss a direct
# snakeoil.demandload.demandload, but
# I don't care, bad form of access imo.
return self.handleChildren(tree)
src = self.scope.get(tree.func.value.id)
if getattr(src, 'is_demandload_module', False):
if tree.func.attr == 'demandload':
is_demandload = True
elif tree.func.attr == 'demand_compile_regexp':
is_demandload_regex = True
elif hasattr(tree.func, 'id'):
is_demandload = getattr(self.scope.get(tree.func.id), 'is_demandload_func', False)
is_demandload_regex = getattr(self.scope.get(tree.func.id), 'is_demandload_regex', False)
if is_demandload_regex:
# should do validation here.
if len(tree.args) < 3:
self.report(BadDemandloadRegexCall, tree.lineno)
elif tree.args[1].__class__.__name__.upper() not in ("STR", "UNICODE"):
self.report(BadDemandloadRegexCall, tree.lineno, "name argument isn't string nor unicode")
elif tree.args[2].__class__.__name__.upper() not in ("STR", "UNICODE"):
self.report(BadDemandloadRegexCall, tree.lineno, "regex argument isn't string nor unicode")
else:
code = "%s = re.compile(%r)\n" % (tree.args[1].s, tree.args[2].s)
fakenode = _ast.copy_location(compile(code, self.filename, "exec", _ast.PyCF_ONLY_AST).body[0],
tree)
self.addBinding(tree.lineno, _checker.Assignment(tree.args[1].s, fakenode))
if is_demandload:
if len(tree.args) < 2:
self.report(BadDemandloadCall, tree.lineno)
return self.handleChildren(tree)
for chunk in tree.args[1:]:
chunk_cls = chunk.__class__.__name__
if chunk_cls.upper() not in ('STR', 'UNICODE'):
self.report(BadDemandloadCall, chunk.lineno,
"invoked with non string/unicode arg: %r" % (chunk_cls,))
continue
s = chunk.s
try:
targets = list(parse_demandload([s]))
except ValueError, ve:
self.report(BadDemandloadCall, chunk.lineno, ve)
continue
for src, asname in targets:
fakenode = _ast.copy_location(compile("import %s as %s\n" % (src, asname),
self.filename, "exec", _ast.PyCF_ONLY_AST).body[0],
chunk)
self.addBinding(chunk.lineno,
DemandloadImportation(asname, fakenode))
开发者ID:chutz,项目名称:snakeoil,代码行数:59,代码来源:pyflakes_extension.py
示例17: search_def_methods
def search_def_methods(self, class_node):
for node in class_node.body:
if isinstance(node, ast.FunctionDef):
if self.is_test_method(node.name):
newnode = ast.arguments(args=[], vararg=None, kwarg=None, defaults=[])
ast.copy_location(newnode, node.args)
node.args = newnode
self.methods_to_run.append(node)
开发者ID:tcdl-univ,项目名称:astmanipulation,代码行数:8,代码来源:astPyTest.py
示例18: visit_With
def visit_With(self, node):
new_node = ast.With(
self._visit(node.items[0].context_expr),
self._visit(node.items[0].optional_vars),
self._visit(node.body)
)
ast.copy_location(new_node, node)
return new_node
开发者ID:nofnofnof,项目名称:CNNForFakePapersDetection,代码行数:8,代码来源:ast2.py
示例19: visit_Expr
def visit_Expr(self, node):
""" When capturing a call to include, we must grab it here, so we can replace the whole Expr(Call('include')).
"""
if type(node.value) is Call:
call = node.value
if type(call.func) is Name and call.func.id == 'include':
if len(call.args) < 1:
raise FormatError("include requires at least a filename as an argument.")
root = None
# if the original call to include had an additional argument
# use that argument as the root
# print('call',ast.dump(call))
if len(call.args) > 1:
root = call.args[1].s
# or if there was a root= kwarg provided, use that
elif len(call.keywords) > 0:
for k in call.keywords:
if k.arg == "root":
root = k.value.s
if root is None:
# if we didn't get one from the call to include
# look for one that was given as an argument to the template() call
root = self.root
if type(root) is str:
root = root.split(os.path.sep)
# the first argument to include() is the filename
template_name = call.args[0].s
# get the ast tree that comes from this included file
check, fundef = include_ast(template_name, root)
# each include produces the code to execute, plus some code to check for freshness
# this code absolutely must run first, because we can't restart the generator once it has already yielded
self.preamble.append(check)
if fundef is None:
raise FormatError("include_ast returned None")
# return a copy of the the cached ast tree, because it will be further modified to fit with the including template
fundef = copy.deepcopy(fundef)
_yieldall(fundef.body)
for expr in fundef.body:
self.visit(expr)
return fundef.body
elif type(node.value) is Yield:
y = node.value
if type(y.value) == Str:
if self.stripWhitespace:
s = strip_whitespace(y.value.s)
if len(s) == 0:
return None # dont even compile in the Expr(Yield) if it was only yielding white space
else:
y.value.s = s
elif type(y.value) == Call:
call = y.value
if type(call.func) is Name:
if self.seenFuncs.get(call.func.id, False) is not False: # was defined locally
# replace the Call with one to ''.join(Call)
y.value = _call(Attribute(value=Str(s=''), attr='join', ctx=Load()), [y.value])
ast.copy_location(y.value, node)
self.generic_visit(node)
return node
开发者ID:pcdinh,项目名称:suba,代码行数:58,代码来源:suba.py
示例20: visit_TryExcept
def visit_TryExcept(self, node):
new_node = gast.Try(
self._visit(node.body),
self._visit(node.handlers),
self._visit(node.orelse),
[] # finalbody
)
ast.copy_location(new_node, node)
return new_node
开发者ID:nofnofnof,项目名称:CNNForFakePapersDetection,代码行数:9,代码来源:ast2.py
注:本文中的ast.copy_location函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论