本文整理汇总了Python中ast.Subscript方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Subscript方法的具体用法?Python ast.Subscript怎么用?Python ast.Subscript使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Subscript方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _unfold
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [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)]))
示例2: format_executing_node_exception
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def format_executing_node_exception(self, event):
try:
assert not NO_ASTTOKENS
node = Source.executing(event.frame).node
assert node
description = {
ast.Call: 'calling',
ast.Subscript: 'subscripting',
ast.Attribute: 'getting attribute',
ast.Compare: 'comparing',
}.get(type(node), 'evaluating')
source = event.source.get_text_with_indentation(node)
plain_prefix = u'!!! When {}: '.format(description)
prefix = u'{c.red}{}{c.reset}'.format(plain_prefix, c=self.c)
return indented_lines(
prefix,
source,
plain_prefix=plain_prefix
)
except Exception:
return []
示例3: visit_Hook
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [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)
示例4: visit_Assign
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def visit_Assign(self, node):
# Only supports assignment of (a single) local variable
assert len(node.targets) == 1, \
'can only assign one variable at a time'
self.visit(node.value)
target = node.targets[0]
if isinstance(target, ast.Subscript):
# array[offset] = value
self.visit(target.slice.value)
self.asm.instr('popq', '%rax')
self.asm.instr('popq', '%rbx')
local_offset = self.local_offset(target.value.id)
self.asm.instr('movq', '{}(%rbp)'.format(local_offset), '%rdx')
self.asm.instr('movq', '%rbx', '(%rdx,%rax,8)')
else:
# variable = value
offset = self.local_offset(node.targets[0].id)
self.asm.instr('popq', '{}(%rbp)'.format(offset))
示例5: visit_Call
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def visit_Call(self, node):
def visit_func(node):
if type(node) == ast.Name:
return node.id
elif type(node) == ast.Attribute:
# Recursion on series of calls to attributes.
func_name = visit_func(node.value)
func_name += "." + node.attr
return func_name
elif type(node) == ast.Str:
return node.s
elif type(node) == ast.Subscript:
return node.value.id
func = node.func
func_name = visit_func(func)
self.current_block.func_calls.append(func_name)
示例6: visit_Assign
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def visit_Assign(self, node):
try:
(target,) = node.targets
except ValueError:
raise NotImplementedError(
'Only single assignment supported for now'
)
if not isinstance(target, (ast.Name, ast.Subscript, ast.Attribute)):
raise NotImplementedError(
'Only index, attribute, and variable name assigment '
'supported, got {}'.format(type(target).__name__)
)
is_name = isinstance(target, ast.Name)
compiled_target = self.visit(target)
if not is_name or (
self.current_class is not None
and compiled_target.startswith('this.')
):
self.scope[compiled_target] = compiled_target
return '{} = {}'.format(
self.scope[compiled_target], self.visit(node.value)
)
示例7: test_subscript
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def test_subscript(self):
sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
ast.Load())
self.expr(sub, "must have Load context")
x = ast.Name("x", ast.Load())
sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
ast.Load())
self.expr(sub, "must have Load context")
s = ast.Name("x", ast.Store())
for args in (s, None, None), (None, s, None), (None, None, s):
sl = ast.Slice(*args)
self.expr(ast.Subscript(x, sl, ast.Load()),
"must have Load context")
sl = ast.ExtSlice([])
self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
sl = ast.ExtSlice([ast.Index(s)])
self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
示例8: visit_Attribute
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def visit_Attribute( self, node ):
self.generic_visit( node )
if isinstance( node._object, _SignalSlice ):
if node._object.slice.step:
raise VerilogTranslationError(
'Slices with steps ([start:stop:step]) are not translatable!\n',
node.lineno
)
new_node = ast.Subscript( node.value,
ast.Slice( ast.Num( node._object.slice.start ),
ast.Num( node._object.slice.stop ),
None ),
None,
)
new_node._object = node._object
return ast.copy_location( new_node, node )
return node
#-------------------------------------------------------------------------
# InferTemporaryTypes
#-------------------------------------------------------------------------
示例9: visit_AnnAssign
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def visit_AnnAssign(self, node):
self.__add_user_def_node(node.target)
self.__add_name_res_assign_node(node)
self.generic_visit(node)
self.__annotations = True
self.__var_annotations = True
self.__vvprint("variable annotations require 3.6+")
if hasattr(node, "annotation"):
ann = node.annotation
if (isinstance(ann, ast.Name) and ann.id == "Final") or \
(isinstance(ann, ast.Subscript) and hasattr(ann.value, "id") and
ann.value.id == "Final"):
self.__final_annotations = True
self.__vvprint("final variable annotations require 3.8+")
elif (isinstance(ann, ast.Name) and ann.id == "Literal") or \
(isinstance(ann, ast.Subscript) and hasattr(ann.value, "id") and
ann.value.id == "Literal"):
self.__literal_annotations = True
self.__vvprint("literal variable annotations require 3.8+")
示例10: boolop
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def boolop(self, block, node, var=None):
#Get the type of operation
if isinstance(node.op, ast.And):
op = Operator.bool_and
elif isinstance(node.op, ast.Or):
op = Operator.bool_or
else:
raise Exception('Unexpected BoolOp (%s)'%(node.op.__class__))
#Chain operations together
left = self.expression(block, node.values[0])
for node_value in node.values[1:]:
right = self.expression(block, node_value)
operation = BinaryOperation(left, op, right)
if node_value == node.values[-1] and var is not None:
#The last operation in the chain should be assigned to this variable
temp_var = var
else:
#Create a temporary variable to store the intermediate result
temp_var = self.add_variable(None, is_mask=True)
assignment = Assignment(temp_var, operation)
block.add(assignment)
left = temp_var
return temp_var
#Parses an array element (AST Subscript)
示例11: ctx_to_store
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def ctx_to_store(obj, store=ast.Store):
if isinstance(obj, list):
for i, x in enumerate(obj):
obj[i] = ctx_to_store(x, store)
return obj
elif isinstance(obj, (ast.Attribute, ast.Subscript)):
obj.ctx = store()
return obj
elif isinstance(obj, ast.AST):
for attrib in obj._fields:
value = getattr(obj, attrib)
if isinstance(value, ast.Load):
setattr(obj, attrib, store())
elif isinstance(value, ast.Param):
setattr(obj, attrib, store())
elif isinstance(value, list):
for i, x in enumerate(value):
value[i] = ctx_to_store(x, store)
elif isinstance(value, ast.AST):
setattr(obj, attrib, ctx_to_store(value, store))
return obj
else:
return obj
示例12: unpack_trailer
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def unpack_trailer(atom, power_star):
out = atom
for trailer in power_star:
if isinstance(trailer, ast.Call):
trailer.func = out
inherit_lineno(trailer, out)
out = trailer
elif isinstance(trailer, ast.Attribute):
trailer.value = out
inherit_lineno(trailer, out, alt=False)
if hasattr(out, "alt"):
trailer.alt = out.alt
out = trailer
elif isinstance(trailer, ast.Subscript):
trailer.value = out
inherit_lineno(trailer, out)
out = trailer
else:
assert False
return out
# file_input: (NEWLINE | stmt)* ENDMARKER
示例13: dollarToArg
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def dollarToArg(node):
if isinstance(node, grammar.DollarNumber):
out = ast.Subscript(ast.Name("$args", ast.Load()), ast.Index(ast.Num(node.n - 1)), ast.Load())
# ASTs need to have line numbers to be compilable by Python
out.lineno, out.col_offset = node.lineno, node.col_offset
out.value.lineno, out.value.col_offset = node.lineno, node.col_offset
out.value.ctx.lineno, out.value.ctx.col_offset = node.lineno, node.col_offset
out.slice.lineno, out.slice.col_offset = node.lineno, node.col_offset
out.slice.value.lineno, out.slice.value.col_offset = node.lineno, node.col_offset
out.ctx.lineno, out.ctx.col_offset = node.lineno, node.col_offset
return out
elif isinstance(node, ast.AST):
for field in node._fields:
setattr(node, field, dollarToArg(getattr(node, field)))
return node
elif isinstance(node, list):
for i, x in enumerate(node):
node[i] = dollarToArg(x)
return node
else:
return node
示例14: p_subscription
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def p_subscription(t):
'''subscription : primary LSQUARE expression RSQUARE'''
#index = ast.Index(make_sub_one(t, 2))
#index.lineno = t.lineno(2)
#index.col_offset = -1 # XXX
index = t[3]
func = ast.Name('____subscript', ast.Load())
func.lineno = t.lineno(1)
func.col_offset = -1 # XXX
t[0] = ast.Call(func, [t[1], index], [], None, None)
t[0].lineno = t.lineno(1)
t[0].col_offset = -1 # XXX
#t[0] = ast.Subscript(t[-1], index, ast.Load())
#t[0].lineno = t.lineno(-1)
#t[0].col_offset = -1 # XXX
示例15: delete_code
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Subscript [as 别名]
def delete_code(self, target):
if type(target) is ast.Attribute:
return [T('delattr({}, {!r})').format(self.visit(target.value), target.attr)]
elif type(target) is ast.Subscript:
if type(target.slice) is ast.Slice and target.slice.step is None:
return [T("(lambda o, **t: type('translator', (), {{t[m]: "
"staticmethod(object.__getattribute__(d[m], '__get__'"
")(o, type(o))) for d in [object.__getattribute__("
"type(o), '__dict__')] for m in t if m in d}})())({},"
" __delitem__='__getitem__', __delslice__="
"'__getslice__', __len__='__len__')[{}]").format(
self.visit(target.value),
self.visit(target.slice))]
else:
return [T("{__operator}.delitem({}, {})").format(
self.visit(target.value),
self.slice_repr(target.slice))]
elif type(target) is ast.Name:
return [self.delete_var(target.id)]
elif type(target) in (ast.List, ast.Tuple):
return [c for elt in target.elts for c in self.delete_code(elt)]
else:
raise NotImplementedError('Case not caught: %s' % str(type(target)))