本文整理汇总了Python中ast.Expression方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Expression方法的具体用法?Python ast.Expression怎么用?Python ast.Expression使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Expression方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generic_visit
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def generic_visit(self, node):
if self.last_node is not None and hasattr(node, 'col_offset'):
enode = ast.Expression(self.last_node)
lambda_code = compile(enode, '<unused>', 'eval')
lines = self.lines[self.last_node.lineno-1:node.lineno]
lines[-1] = lines[-1][:node.col_offset]
lines[0] = lines[0][self.last_node.col_offset:]
lambda_body_text = ' '.join(l.rstrip(' \t\\').strip() for l in lines)
while lambda_body_text:
try:
code = compile(lambda_body_text, '<unused>', 'eval')
if len(code.co_code) == len(lambda_code.co_code):
break
except SyntaxError:
pass
lambda_body_text = lambda_body_text[:-1]
self.lambdas.append((lambda_code, lambda_body_text.strip()))
self.last_node = None
super().generic_visit(node)
示例2: generic_visit
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def generic_visit(self, node):
# Fallback when we don't have a special implementation.
if _is_ast_expr(node):
mod = ast.Expression(node)
co = self._compile(mod)
try:
result = self.frame.eval(co)
except Exception:
raise Failure()
explanation = self.frame.repr(result)
return explanation, result
elif _is_ast_stmt(node):
mod = ast.Module([node])
co = self._compile(mod, "exec")
try:
self.frame.exec_(co)
except Exception:
raise Failure()
return None, None
else:
raise AssertionError("can't handle %s" %(node,))
示例3: visit_Call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def visit_Call(self, node, return_task=False):
sub_node = node.func
while not isinstance(sub_node, ast.Name):
sub_node = sub_node.value
py_object = eval(compile(ast.Expression(sub_node), "", "eval"), self._globals)
if py_object == CalmTask or isinstance(py_object, EntityType):
task = eval(compile(ast.Expression(node), "", "eval"), self._globals)
if task is not None and isinstance(task, TaskType):
if self.target is not None and not task.target_any_local_reference:
task.target_any_local_reference = self.target
if return_task:
return task
self.task_list.append(task)
self.all_tasks.append(task)
return
return self.generic_visit(node)
示例4: visit_With
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def visit_With(self, node):
parallel_tasks = []
if len(node.items) > 1:
raise ValueError(
"Only a single context is supported in 'with' statements inside the action."
)
context = eval(
compile(ast.Expression(node.items[0].context_expr), "", "eval"),
self._globals,
)
if context.__calm_type__ == "parallel":
for statement in node.body:
if not isinstance(statement.value, ast.Call):
raise ValueError(
"Only calls to 'CalmTask' methods supported inside parallel context."
)
task = self.visit_Call(statement.value, return_task=True)
if task:
parallel_tasks.append(task)
self.all_tasks.append(task)
self.task_list.append(parallel_tasks)
else:
raise ValueError(
"Unsupported context used in 'with' statement inside the action."
)
示例5: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def __init__(self, patt_ast, target_ast, rep_ast, nbits=0):
'Pattern ast should have as root: BinOp, BoolOp, UnaryOp or Call'
if isinstance(patt_ast, ast.Module):
self.patt_ast = patt_ast.body[0].value
elif isinstance(patt_ast, ast.Expression):
self.patt_ast = patt_ast.body
else:
self.patt_ast = patt_ast
if isinstance(rep_ast, ast.Module):
self.rep_ast = deepcopy(rep_ast.body[0].value)
elif isinstance(rep_ast, ast.Expression):
self.rep_ast = deepcopy(rep_ast.body)
else:
self.rep_ast = deepcopy(rep_ast)
if not nbits:
getsize = asttools.GetSize()
getsize.visit(target_ast)
if getsize.result:
self.nbits = getsize.result
# default bitsize is 8
else:
self.nbits = 8
else:
self.nbits = nbits
示例6: visit_BinOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def visit_BinOp(self, node):
'If node is a constant expression, replace it with its evaluated value'
if node in self.constexpr:
# evaluation
fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
ast.Num(self.mod)))
ast.fix_missing_locations(fake_node)
code = compile(fake_node, '<constant folding>', 'eval')
obj_env = globals().copy()
exec code in obj_env
value = eval(code, obj_env)
new_node = ast.Num(value)
return new_node
else:
return self.generic_visit(node)
示例7: visit_BoolOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def visit_BoolOp(self, node):
'A custom BoolOp can be used in flattened AST'
if type(node.op) not in (ast.Add, ast.Mult,
ast.BitXor, ast.BitAnd, ast.BitOr):
return self.generic_visit(node)
# get constant parts of node:
list_cste = [child for child in node.values
if isinstance(child, ast.Num)]
if len(list_cste) < 2:
return self.generic_visit(node)
rest_values = [n for n in node.values if n not in list_cste]
fake_node = Unflattening().visit(ast.BoolOp(node.op, list_cste))
fake_node = ast.Expression(fake_node)
ast.fix_missing_locations(fake_node)
code = compile(fake_node, '<constant folding>', 'eval')
obj_env = globals().copy()
exec code in obj_env
value = eval(code, obj_env)
new_node = ast.Num(value)
rest_values.append(new_node)
return ast.BoolOp(node.op, rest_values)
示例8: visit_UnaryOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def visit_UnaryOp(self, node):
'Same idea as visit_BinOp'
if node in self.constexpr:
# evaluation
fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
ast.Num(self.mod)))
ast.fix_missing_locations(fake_node)
code = compile(fake_node, '<constant folding>', 'eval')
obj_env = globals().copy()
exec code in obj_env
value = eval(code, obj_env)
new_node = ast.Num(value)
return new_node
else:
return self.generic_visit(node)
示例9: test_increment_lineno
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def test_increment_lineno(self):
src = ast.parse('1 + 1', mode='eval')
self.assertEqual(ast.increment_lineno(src, n=3), src)
self.assertEqual(ast.dump(src, include_attributes=True),
'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
'col_offset=0))'
)
# issue10869: do not increment lineno of root twice
src = ast.parse('1 + 1', mode='eval')
self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
self.assertEqual(ast.dump(src, include_attributes=True),
'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
'col_offset=0))'
)
示例10: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def __init__(self, source: Union[str, ast.Expression], partial_binding: bool = False):
"""Create new evaluator.
Args:
source: Expression of equation to evaluate.
partial_binding: Allow partial bind of parameters.
Raises:
PulseError: When invalid string is specified.
"""
self._partial_binding = partial_binding
self._locals_dict = {}
self._params = set()
if isinstance(source, ast.Expression):
self._tree = source
else:
try:
self._tree = ast.parse(source, mode='eval')
except SyntaxError:
raise PulseError('%s is invalid expression.' % source)
# parse parameters
self.visit(self._tree)
示例11: _arithmeticEval
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def _arithmeticEval(s):
"""
A safe eval supporting basic arithmetic operations.
:param s: expression to evaluate
:return: value
"""
node = ast.parse(s, mode='eval')
def _eval(node):
if isinstance(node, ast.Expression):
return _eval(node.body)
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.BinOp):
return _binOps[type(node.op)](_eval(node.left), _eval(node.right))
else:
raise Exception('Unsupported type {}'.format(node))
return _eval(node.body)
示例12: eval_code
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def eval_code(code, ns):
"""
Runs a string of code, the last part of which may be an expression.
"""
# handle mis-indented input from multi-line strings
code = dedent(code)
mod = ast.parse(code)
if len(mod.body) == 0:
return None
if isinstance(mod.body[-1], ast.Expr):
expr = ast.Expression(mod.body[-1].value)
del mod.body[-1]
else:
expr = None
if len(mod.body):
exec(compile(mod, "<exec>", mode="exec"), ns, ns)
if expr is not None:
return eval(compile(expr, "<eval>", mode="eval"), ns, ns)
else:
return None
示例13: parse_log_line
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def parse_log_line(line):
split_pos = line.rfind(" at ")
assert split_pos > 0
left = line[0:split_pos]
right = line[split_pos + 4 :].strip()
tree = ast.parse(left, mode="eval")
assert isinstance(tree, ast.Expression)
assert isinstance(tree.body, ast.Call)
attributes = {
"event_kind": tree.body.func.id,
"event_time": strptime(right, "%Y-%m-%dT%H:%M:%S.%f"),
}
for kw in tree.body.keywords:
attributes[kw.arg] = ast.literal_eval(kw.value)
return attributes
示例14: get_value_of_param
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def get_value_of_param(name, param_list, extra_dict={}):
tree = ast.parse(f'__null_func__({param_list})')
# x.func can be an attribute (e.g. a.b()) and do not have id
kwargs = [
x for x in ast.walk(tree)
if x.__class__.__name__ == 'keyword' and x.arg == name
]
if not kwargs:
return []
try:
return [ast.literal_eval(kwargs[0].value)]
except Exception:
return [
eval(
compile(
ast.Expression(body=kwargs[0].value),
filename='<string>',
mode="eval"), extra_dict)
]
示例15: getVal
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expression [as 别名]
def getVal(self, node):
expr = ast.Expression()
expr.body = node
expr.lineno = node.lineno
expr.col_offset = node.col_offset
c = compile(expr, '<string>', 'eval')
val = eval(c, self.tree.symdict, self.tree.vardict)
# val = eval(_unparse(node), self.tree.symdict, self.tree.vardict)
return val