本文整理汇总了Python中ast.Load方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Load方法的具体用法?Python ast.Load怎么用?Python ast.Load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visit_Expr
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Expr(self, node):
newnode = ast.copy_location(ast.Expr(
value = ast.Call(
func = ast.Attribute(
value = ast.Name(id='__swirlypy_recorder__',
ctx=ast.Load()),
attr="record",
ctx=ast.Load()),
args=[node.value],
keywords=[],
starargs=None,
kwargs=None
)
),
node)
ast.fix_missing_locations(newnode)
return newnode
示例2: NAME
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def NAME(self, node):
"""
Handle occurrence of Name (which can be a load/store/delete access.)
"""
# Locate the name in locals / function / globals scopes.
if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
self.handleNodeLoad(node)
if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
and isinstance(node.parent, ast.Call)):
# we are doing locals() call in current scope
self.scope.usesLocals = True
elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
self.handleNodeStore(node)
elif isinstance(node.ctx, ast.Del):
self.handleNodeDelete(node)
else:
# must be a Param context -- this only happens for names in function
# arguments, but these aren't dispatched through here
raise RuntimeError("Got impossible expression context: %r" % (node.ctx,))
示例3: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def __init__(
self,
keys: t.List[ast.expr],
values: t.List[ast.expr],
ctx: t.Union[ast.Store, ast.Load],
lineno=None,
col_offset=None,
):
super().__init__()
self.keys = keys
self.values = values
self.ctx = ctx
if lineno:
self.lineno = lineno
if col_offset:
self.col_offset = col_offset
示例4: visit_Attribute
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Attribute(self, node, **kwargs):
attr = node.attr
value = node.value
ctx = node.ctx.__class__
if ctx == ast.Load:
# resolve the value
resolved = self.visit(value)
# try to get the value to see if we are another expression
try:
resolved = resolved.value
except (AttributeError):
pass
try:
return self.term_type(getattr(resolved, attr), self.env)
except AttributeError:
# something like datetime.datetime where scope is overridden
if isinstance(value, ast.Name) and value.id == attr:
return resolved
raise ValueError("Invalid Attribute context {name}"
.format(name=ctx.__name__))
示例5: visit_Attribute
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Attribute(self, node, **kwargs):
attr = node.attr
value = node.value
ctx = node.ctx
if isinstance(ctx, ast.Load):
# resolve the value
resolved = self.visit(value).value
try:
v = getattr(resolved, attr)
name = self.env.add_tmp(v)
return self.term_type(name, self.env)
except AttributeError:
# something like datetime.datetime where scope is overridden
if isinstance(value, ast.Name) and value.id == attr:
return resolved
raise ValueError("Invalid Attribute context {name}"
.format(name=ctx.__name__))
示例6: visit
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit(self, node) -> Any:
if isinstance(node, ast.Name):
if isinstance(node.ctx, ast.Load):
self.loaded.add(node.id)
elif isinstance(node.ctx, ast.Store):
self.stored.add(node.id)
elif isinstance(node, ast.Return):
self.has_return = True
# We must keep track of importer name in order to avoid considering as variable
# names:
elif isinstance(node, ast.Import):
self.imported.update([ n.name for n in node.names])
elif isinstance(node, ast.ImportFrom):
self.imported.update([ n.name for n in node.names])
self.generic_visit(node)
示例7: test_noflattening
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def test_noflattening(self):
'Tests where nothing should be flattened'
corresp = [(["a + b", "b + a"],
ast.BinOp(ast.Name('a', ast.Load()),
ast.Add(),
ast.Name('b', ast.Load()))),
(["c*d", "d*c"],
ast.BinOp(ast.Name('c', ast.Load()),
ast.Mult(),
ast.Name('d', ast.Load()))),
(["a + c*d", "d*c + a"],
ast.BinOp(ast.Name('a', ast.Load()), ast.Add(),
ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(),
ast.Name('d', ast.Load()))))]
for refstring, result in corresp:
self.generic_flattening(refstring, result)
示例8: visit_BinOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_BinOp(self, node):
'Replace bitwise operation with function call'
self.generic_visit(node)
if isinstance(node.op, ast.BitAnd):
return ast.Call(ast.Name('mand', ast.Load()),
[node.left, node.right], [], None, None)
if isinstance(node.op, ast.BitOr):
return ast.Call(ast.Name('mor', ast.Load()),
[node.left, node.right], [], None, None)
if isinstance(node.op, ast.BitXor):
return ast.Call(ast.Name('mxor', ast.Load()),
[node.left, node.right], [], None, None)
if isinstance(node.op, ast.LShift):
return ast.Call(ast.Name('mlshift', ast.Load()),
[node.left, node.right], [], None, None)
if isinstance(node.op, ast.RShift):
return ast.Call(ast.Name('mrshift', ast.Load()),
[node.left, node.right], [], None, None)
return node
示例9: pop_format_context
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def pop_format_context(self, expl_expr):
"""Format the %-formatted string with current format context.
The expl_expr should be an ast.Str instance constructed from
the %-placeholders created by .explanation_param(). This will
add the required code to format said string to .expl_stmts and
return the ast.Name instance of the formatted string.
"""
current = self.stack.pop()
if self.stack:
self.explanation_specifiers = self.stack[-1]
keys = [ast.Str(key) for key in current.keys()]
format_dict = ast.Dict(keys, list(current.values()))
form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
name = "@py_format" + str(next(self.variable_counter))
if self.enable_assertion_pass_hook:
self.format_variables.append(name)
self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
return ast.Name(name, ast.Load())
示例10: test_dump
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [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)])"
)
示例11: test_attributes
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def test_attributes(self):
# assert True, "bad"
assert0 = ast.Assert()
self.assertFalse(hasattr(assert0, 'lineno'))
self.assertFalse(hasattr(assert0, 'col_offset'))
assert1 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'))
self.assertFalse(hasattr(assert1, 'lineno'))
self.assertFalse(hasattr(assert1, 'col_offset'))
try:
tmp=assert1.lineno
except Exception as e:
self.assertTrue(isinstance(e,AttributeError))
try:
tmp=assert1.col_offset
except Exception as e:
self.assertTrue(isinstance(e,AttributeError))
assert2 = ast.Assert(ast.Name('True', ast.Load()), ast.Str('bad'),2,3)
self.assertEqual(assert2.lineno,2)
self.assertEqual(assert2.col_offset,3)
示例12: __exit_scope
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def __exit_scope(self) -> ast.stmt:
"""Create the appropriate scope exiting statement.
The documentation only shows one level and always uses
'return False' in examples.
'raise AltFalse()' within a try.
'break' within a loop.
'return False' otherwise.
"""
if self.in_optional:
return ast.Pass()
if self.in_try:
return ast.Raise(
ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
None)
if self.in_loop:
return ast.Break()
return ast.Return(ast.Name('False', ast.Load()))
#TODO(bps): find a better name to describe what this does
示例13: visit_Hook
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Hook(self, node: parsing.Hook) -> ast.expr:
"""Generates python code calling a hook.
self.evalHook('hookname', self.ruleNodes[-1])
"""
return ast.Call(
ast.Attribute(
ast.Name('self', ast.Load()), 'evalHook', ast.Load()),
[
ast.Str(node.name),
ast.Subscript(
ast.Attribute(
ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()),
ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))),
ast.Load())],
[],
None,
None)
示例14: visit_Rep0N
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]:
"""Generates python code for a clause repeated 0 or more times.
#If all clauses can be inlined
while clause:
pass
while True:
<code for the clause>
"""
cl_ast = self.visit(node.pt)
if isinstance(cl_ast, ast.expr):
return [ast.While(cl_ast, [ast.Pass()], [])]
self.in_loop += 1
clause = self._clause(self.visit(node.pt))
self.in_loop -= 1
return [ast.While(ast.Name('True', ast.Load()), clause, [])]
示例15: visit_Attribute
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Load [as 别名]
def visit_Attribute(self, node, **kwargs):
attr = node.attr
value = node.value
ctx = node.ctx.__class__
if ctx == ast.Load:
# resolve the value
resolved = self.visit(value)
# try to get the value to see if we are another expression
try:
resolved = resolved.value
except (AttributeError):
pass
try:
return self.term_type(getattr(resolved, attr), self.env)
except AttributeError:
# something like datetime.datetime where scope is overriden
if isinstance(value, ast.Name) and value.id == attr:
return resolved
raise ValueError("Invalid Attribute context {0}".format(ctx.__name__))