本文整理汇总了Python中ast.Expr方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Expr方法的具体用法?Python ast.Expr怎么用?Python ast.Expr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Expr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visit_FunctionDef
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def visit_FunctionDef(self, node):
self.writeDoc(node)
w = node.body[-1]
y = w.body[0]
if isinstance(y, ast.Expr):
y = y.value
assert isinstance(y, ast.Yield)
self.writeAlwaysHeader()
self.writeDeclarations()
# assert isinstance(w.body, astNode.Stmt)
for stmt in w.body[1:]:
self.writeline()
self.visit(stmt)
self.dedent()
self.writeline()
self.write("end")
self.writeline(2)
示例2: visit_While
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def visit_While(self, node):
node.breakLabel = _Label("BREAK")
node.loopLabel = _Label("LOOP")
self.labelStack.append(node.breakLabel)
self.labelStack.append(node.loopLabel)
self.visit(node.test)
self.refStack.push()
for n in node.body:
self.visit(n)
self.refStack.pop()
y = node.body[0]
if isinstance(y, ast.Expr):
y = y.value
if node.test.obj == True and \
isinstance(y, ast.Yield) and \
not self.tree.hasYield > 1 and \
not isinstance(self.getObj(y.value), delay):
node.kind = _kind.ALWAYS
self.tree.senslist = y.senslist
self.require(node, not node.orelse, "while-else not supported")
self.labelStack.pop()
self.labelStack.pop()
示例3: visit_FunctionDef
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def visit_FunctionDef(self, node):
self.refStack.push()
for n in node.body:
self.visit(n)
self.tree.kind = _kind.SIMPLE_ALWAYS_COMB
for n in node.body:
if isinstance(n, ast.Expr) and isinstance(n.value, ast.Str):
continue # skip doc strings
if isinstance(n, ast.Assign) and \
isinstance(n.targets[0], ast.Attribute) and \
self.getKind(n.targets[0].value) != _kind.REG:
pass
else:
self.tree.kind = _kind.ALWAYS_COMB
return
# rom access is expanded into a case statement in addition
# to any always_comb that contains a list of signals
# if self.tree.hasRom or self.tree.hasLos:
if self.tree.hasRom:
self.tree.kind = _kind.ALWAYS_COMB
self.refStack.pop()
示例4: compile_expression
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def compile_expression(exp):
cached = cache.get(exp)
if cached is not None:
return cached
_exp = ast.parse(exp)
nodes = [node for node in ast.walk(_exp)]
if len(nodes) < 2 or not isinstance(nodes[1], ast.Expr):
raise ExpressionError("%s is not Expression" % exp)
for node in nodes:
if isinstance(node, ast.Call):
raise ExpressionError("Call method is forbidden")
if isinstance(node, ast.Lambda):
raise ExpressionError("Lambda is strongly forbidden")
result = compile(exp, '<string>', mode='eval')
cache[exp] = result
return result
示例5: expr_stmt_rewrite
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def expr_stmt_rewrite(lhs, ann, aug, aug_exp, rhs: t.Optional[list]):
if rhs:
as_store(lhs)
*init, end = rhs
for each in init:
as_store(each)
return ast.Assign([lhs, *init], end)
if ann:
as_store(lhs)
anno, value = ann
return ast.AnnAssign(lhs, anno, value, 1)
if aug_exp:
as_store(lhs)
return ast.AugAssign(lhs, aug(), aug_exp)
# NO AS STORE HERE!
return ast.Expr(lhs)
示例6: expression_stmt_to_ir2
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def expression_stmt_to_ir2(stmt: ast.Expr, compilation_context: CompilationContext, next_stmt_line: int):
expr = expression_ast_to_ir2(stmt.value,
compilation_context,
in_match_pattern=False,
check_var_reference=lambda ast_node: None,
match_lambda_argument_names=set(),
current_stmt_line=stmt.lineno)
lhs_var_name = next(compilation_context.identifier_generator)
compilation_context.add_symbol(name=lhs_var_name,
expr_type=expr.expr_type,
definition_ast_node=stmt,
is_only_partially_defined=False,
is_function_that_may_throw=isinstance(expr.expr_type, ir2.FunctionType))
return ir2.Assignment(lhs=ir2.VarReference(expr_type=expr.expr_type,
name=lhs_var_name,
is_global_function=False,
is_function_that_may_throw=isinstance(expr.expr_type, ir2.FunctionType)),
rhs=expr,
source_branch=SourceBranch(compilation_context.filename,
stmt.lineno,
next_stmt_line))
示例7: test_dump
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
self.assertEqual(ast.dump(node),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
"args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
"keywords=[], starargs=None, kwargs=None))])"
)
self.assertEqual(ast.dump(node, annotate_fields=False),
"Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
"Str('and cheese')], [], None, None))])"
)
self.assertEqual(ast.dump(node, include_attributes=True),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
"lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
"lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
"col_offset=11)], keywords=[], starargs=None, kwargs=None, "
"lineno=1, col_offset=0), lineno=1, col_offset=0)])"
)
示例8: make_annotation
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def make_annotation(node=None, buffer='outside', content=None, cell_type='code', lineno=None):
"""Return a ast.Expr that looks like
```
__cell__('make-cell', [content, buffer, cell_type])
```
"""
content = astor.to_source(node).strip() if node else content
lineno = str(node.lineno) if hasattr(node, 'lineno') else str(-1) if not lineno else str(lineno)
call = ast.Call(
func=ast.Name(id='__cell__', ctx=ast.Load()),
args=[
ast.Str(s=content),
ast.Str(s=f'{buffer}'),
ast.Str(s=cell_type),
ast.Str(s=lineno),
],
keywords=[]
)
return ast.Expr(call)
示例9: checksum
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def checksum(self):
"""Produce an md5 for the contents of this rule.
This logic applies to expressions within the function only. It does not take
into account: the function name, docstring, comments, or decorator arguments
"""
if not self._checksum:
try:
code = inspect.getsource(self.func)
root = ast.parse(code)
md5 = hashlib.md5() # nosec
for expression in root.body[0].body:
# This check is necessary to ensure changes to the docstring
# are allowed without altering the checksum
if not isinstance(expression, ast.Expr):
md5.update(ast.dump(expression).encode('utf-8'))
self._checksum = md5.hexdigest()
except (TypeError, IndentationError, IndexError):
LOGGER.exception('Could not checksum rule function')
self._checksum = self.CHECKSUM_UNKNOWN
return self._checksum
示例10: _memberAccessChainWithLocImpl
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def _memberAccessChainWithLocImpl(pyAstNode):
''' Return a pair containing the access chain list and the root node.'''
if isinstance(pyAstNode, ast.Name):
return ([pyAstNode.id], pyAstNode)
if isinstance(pyAstNode, ast.Expr):
return _memberAccessChainWithLocImpl(pyAstNode.value)
if isinstance(pyAstNode, ast.Attribute):
# expr.attr: Attribute(expr value, identifier attr, expr_context context)
(prefix, root) = _memberAccessChainWithLocImpl(pyAstNode.value)
if len(prefix) == 0:
return ([], None) # return empty list for unexpected node-type
prefix.append(pyAstNode.attr)
return (prefix, root)
return ([], None) # return empty list for unexpected node-type
示例11: CheckedEval
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def CheckedEval(file_contents):
"""Return the eval of a gyp file.
The gyp file is restricted to dictionaries and lists only, and
repeated keys are not allowed.
Note that this is slower than eval() is.
"""
syntax_tree = ast.parse(file_contents)
assert isinstance(syntax_tree, ast.Module)
c1 = syntax_tree.body
assert len(c1) == 1
c2 = c1[0]
assert isinstance(c2, ast.Expr)
return CheckNode(c2.value, [])
示例12: parse_setup
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def parse_setup():
print("[1/8] | Parsing setup.py file")
with open('setup.py', 'r') as f:
file_contents = f.read()
treeobj = ast.parse(file_contents, 'setup.py')
setup_expression = None
for element in treeobj.body:
if isinstance(element, ast.Expr) and element.value.func.id == "setup":
setup_expression = element
if not setup_expression:
print("No setup() found in setup.py")
sys.exit(1)
return file_contents, setup_expression
示例13: test_dump
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def test_dump(self):
node = ast.parse('spam(eggs, "and cheese")')
self.assertEqual(ast.dump(node),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
"args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
"keywords=[]))])"
)
self.assertEqual(ast.dump(node, annotate_fields=False),
"Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
"Str('and cheese')], []))])"
)
self.assertEqual(ast.dump(node, include_attributes=True),
"Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
"lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
"lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
"col_offset=11)], keywords=[], "
"lineno=1, col_offset=0), lineno=1, col_offset=0)])"
)
示例14: test_try
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def test_try(self):
p = ast.Pass()
t = ast.Try([], [], [], [p])
self.stmt(t, "empty body on Try")
t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
self.stmt(t, "must have Load context")
t = ast.Try([p], [], [], [])
self.stmt(t, "Try has neither except handlers nor finalbody")
t = ast.Try([p], [], [p], [p])
self.stmt(t, "Try has orelse but no except handlers")
t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
self.stmt(t, "empty body on ExceptHandler")
e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
self.stmt(ast.Try([p], e, [], []), "must have Load context")
e = [ast.ExceptHandler(None, "x", [p])]
t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
self.stmt(t, "must have Load context")
t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
self.stmt(t, "must have Load context")
示例15: _parse_local_package_name
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Expr [as 别名]
def _parse_local_package_name(path):
"""Tokenize setup.py and walk the syntax tree to find the package name"""
try:
with open(os.path.join(path, "setup.py")) as f:
tree = ast.parse(f.read())
setup_kwargs = [
expr.value.keywords
for expr in tree.body
if isinstance(expr, ast.Expr)
and isinstance(expr.value, ast.Call)
and expr.value.func.id == "setup"
][0]
value = [kw.value for kw in setup_kwargs if kw.arg == "name"][0]
return value.s
except (IndexError, AttributeError, IOError, OSError):
raise PipError(
"Directory %r is not installable. "
"Could not parse package name from 'setup.py'." % path
)