本文整理汇总了Python中ast.Name方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Name方法的具体用法?Python ast.Name怎么用?Python ast.Name使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Name方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: version
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def version():
path = 'pypika/__init__.py'
with open(path, 'r') as file:
t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST)
for node in (n for n in t.body if isinstance(n, ast.Assign)):
if len(node.targets) == 1:
name = node.targets[0]
if isinstance(name, ast.Name) and \
name.id in ('__version__', '__version_info__', 'VERSION'):
v = node.value
if isinstance(v, ast.Str):
return v.s
if isinstance(v, ast.Tuple):
r = []
for e in v.elts:
if isinstance(e, ast.Str):
r.append(e.s)
elif isinstance(e, ast.Num):
r.append(str(e.n))
return '.'.join(r)
示例2: visit_If
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def visit_If(self, node):
node.ignore = False
if not node.orelse:
test = node.test
if isinstance(test, ast.Name):
if test.id == '__debug__':
node.ignore = True
return # skip
self.generic_visit(node)
# add fields that match old compiler package
tests = [(node.test, node.body)]
else_ = []
self.flattenIf(node.orelse, tests, else_, node.body[0].col_offset)
node.tests = tests
node.else_ = else_
示例3: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def visit_Compare(self, node):
node.obj = bool()
for n in [node.left] + node.comparators:
self.visit(n)
op, arg = node.ops[0], node.comparators[0]
# # node.expr.target = self.getObj(arg)
# # arg.target = self.getObj(node.expr)
# detect specialized case for the test
if isinstance(op, ast.Eq) and isinstance(node.left, ast.Name):
# check wether it can be a case
val = arg.obj
if isinstance(val, bool):
val = int(val) # cast bool to int first
if isinstance(val, (EnumItemType, int)):
node.case = (node.left, val)
# check whether it can be part of an edge check
n = node.left.id
if n in self.tree.sigdict:
sig = self.tree.sigdict[n]
v = self.getValue(arg)
if v is not None:
if v == 0:
node.edge = sig.negedge
elif v == 1:
node.edge = sig.posedge
示例4: _unfold
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def _unfold(x, path, state):
if isinstance(x, ast.Attribute):
path.insert(0, {"string": x.attr})
return _unfold(x.value, path, state)
elif isinstance(x, ast.Subscript) and isinstance(x.slice, ast.Index):
path.insert(0, _expression(x.slice.value, state))
return _unfold(x.value, path, state)
else:
if isinstance(x, ast.Name) and x.id in state["cells"]:
return _form(state, x.lineno, OrderedDict([("cell", x.id), ("path", path)]))
elif isinstance(x, ast.Name) and x.id in state["pools"]:
return _form(state, x.lineno, OrderedDict([("pool", x.id), ("path", path)]))
else:
return _form(state, x.lineno, OrderedDict([("attr", _expression(x, state)), ("path", path)]))
示例5: pre_Assign
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def pre_Assign(self):
value = self.cur_node.value
for target in self.cur_node.targets:
# ignore Subscripts for now
if isinstance(target, _ast.Name):
if target.id == '_target_model':
assert(isinstance(value, _ast.Call))
# done in three separate phases for safety with stringly-typed arguments
StateSpaceLabelWalker(value.args[0])
LabelWalker(value.args[1])
ExpressionWalker(value.args[2])
else:
LabelWalker(value)
# Build dependencies from the rhs
# We don't consider the function name a dependency so bypass that
critical_ast = value.args if isinstance(value, _ast.Call) else value
value._dependencies = DependencyWalker(critical_ast).dependencies
self.upgrades[target.id] = value
return False
# Build variables for filling in the template
示例6: _apply_imports_to_unparsed_expression
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def _apply_imports_to_unparsed_expression(exp_ast, imports):
"""Attempts to evaluate the code equivalent of `exp_ast`, with `imports`
as available symbols. If it's successful, it returns the evaluated object.
Otherwise this returns the unparsed code for `exp_ast`.
Args:
* exp_ast (Union[ast.Name, ast.Attribute, ast.Call]) - The expression to
evaluate.
* imports (Dict[str, object]) - The symbols to include during the evaluation
of `exp_ast`.
Returns the evaluation of `exp_ast` if it can successfully evaluate with
`imports`. Otherwise this returns the source-code representation of exp_ast as
a string.
"""
assert isinstance(exp_ast, (ast.Name, ast.Attribute, ast.Call)), type(exp_ast)
unparsed = _unparse(exp_ast).strip()
try:
return eval(unparsed, {'__builtins__': None}, imports)
except (NameError, AttributeError):
return unparsed
示例7: visit_Expr
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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
示例8: convert_to_value
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def convert_to_value(item):
if isinstance(item, ast.Str):
return item.s
elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
return item.s
elif isinstance(item, ast.Tuple):
return tuple(convert_to_value(i) for i in item.elts)
elif isinstance(item, ast.Num):
return item.n
elif isinstance(item, ast.Name):
result = VariableKey(item=item)
constants_lookup = {
'True': True,
'False': False,
'None': None,
}
return constants_lookup.get(
result.name,
result,
)
elif (not PY2) and isinstance(item, ast.NameConstant):
# None, True, False are nameconstants in python3, but names in 2
return item.value
else:
return UnhandledKeyType()
示例9: NAME
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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,))
示例10: visit_Call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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)
示例11: visit_Attribute
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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__))
示例12: visit_Attribute
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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__))
示例13: visit
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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)
示例14: test_noflattening
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [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)
示例15: _get_value_from_ast
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Name [as 别名]
def _get_value_from_ast(self, obj):
"""
Return the value of the ast object.
"""
if isinstance(obj, ast.Num):
return obj.n
elif isinstance(obj, ast.Str):
return obj.s
elif isinstance(obj, ast.List):
return [self._get_value_from_ast(e) for e in obj.elts]
elif isinstance(obj, ast.Tuple):
return tuple([self._get_value_from_ast(e) for e in obj.elts])
# None, True and False are NameConstants in Py3.4 and above.
elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
return obj.value
# For python versions below 3.4
elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
return string_to_constant[obj.id]
# Probably passed a variable name.
# Or passed a single word without wrapping it in quotes as an argument
# ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
raise NameError("name '%s' is not defined" % obj.id)