本文整理汇总了Python中ast.Index方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Index方法的具体用法?Python ast.Index怎么用?Python ast.Index使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.Index方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _unfold
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [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: visit_Hook
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [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)
示例3: test_subscript
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [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")
示例4: make_location
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def make_location(self, node) -> Location:
"""Create a Location from an AST node."""
if isinstance(node, (list, tuple)):
if len(node) == 0:
return None
node0 = node[0]
node1 = node[-1]
else:
node0 = node
node1 = node
if hasattr(node0, "lineno") and hasattr(node0, "col_offset"):
li1, col1 = node0.first_token.start
li2, col2 = node1.last_token.end
li1 += self.line_offset - 1
li2 += self.line_offset - 1
col1 += self.col_offset
col2 += self.col_offset
return Location(self.filename, li1, col1, li2, col2, node)
else:
# Some nodes like Index carry no location information, but
# we basically just pass through them.
return None # pragma: no cover
示例5: visit_Index
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def visit_Index(self, node):
new_value = self._visit(node.value)
if isinstance(new_value, ast.Ellipsis):
new_node = new_value
elif isinstance(new_value, ast.Tuple):
if any(isinstance(elt, ast.Ellipsis) for elt in new_value.elts):
new_elts = [elt if isinstance(elt, (ast.Ellipsis, ast.Slice))
else ast.Index(elt)
for elt in new_value.elts]
new_node = ast.ExtSlice(new_elts)
else:
new_node = ast.Index(new_value)
else:
new_node = ast.Index(new_value)
ast.copy_location(new_node, node)
return new_node
示例6: normalize_tuple_slice
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def normalize_tuple_slice(node):
"""
Normalize an ast.Tuple node representing the internals of a slice.
Returns the node wrapped in an ast.Index.
Returns an ExtSlice node built from the tuple elements if there are any
slices.
"""
if not any(isinstance(elt, ast.Slice) for elt in node.elts):
return ast.Index(value=node)
return ast.ExtSlice(
[
# Wrap non-Slice nodes in Index nodes.
elt if isinstance(elt, ast.Slice) else ast.Index(value=elt)
for elt in node.elts
]
)
示例7: dollarToArg
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [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
示例8: p_subscription
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [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
示例9: check_Subscript
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def check_Subscript(self, node, func_name):
error = ValueError(
'Call to function %s defined in an auxiliary h5 file is not '
'correct in script: %s' % (func_name, self.script))
if not(isinstance(node.slice, ast.Index) and
isinstance(node.ctx, ast.Load)):
raise error
if not(isinstance(node.slice.value, ast.Tuple) and
isinstance(node.slice.value.ctx, ast.Load)):
raise error
# output column must appear explicitly as strings
if not(all([isinstance(e, ast.Str) for e in node.slice.value.elts])):
raise error
示例10: _Subscript
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def _Subscript(self, t):
if isinstance(t.slice, ast.Index):
#self.dispatch(t.value)
#self.write("[")
#self.dispatch(t.slice)
#self.write("]")
self.write('pyphp_subscript(')
self.dispatch(t.value)
self.write(', ')
self.dispatch(t.slice)
self.write(')')
elif isinstance(t.slice, ast.Slice):
self.write('array_slice(')
self.dispatch(t.value)
self.write(', ')
self.dispatch(t.slice)
self.write(')')
示例11: visit_Index
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def visit_Index(self, node: ast.Index) -> None:
# actual slicing
print(f"Index: {node}")
print(ast.dump(node))
示例12: visit_Subscript
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def visit_Subscript(self, node):
"""Subscript nodes are anything which is __[__]. We only want to match __[x]
here so where the [x] is a regular Index expression (not an elipsis or
slice). We only handle cases where x is a constant, or a resolvable variable
lookup (so a variable lookup, index, etc.)."""
node = self.generic_visit(node)
if (isinstance(node.slice, ast.Index) and
self._is_valid_resolved(node.value)):
sliceVal = MISSING
sliceRepr = ''
if self._is_valid_resolved(node.slice.value):
# (a[b])[c]
# will include `a[b]` in the extras.
self.extras.append(node.slice.value)
sliceVal = node.slice.value.value
sliceRepr = node.slice.value.representation
elif isinstance(node.slice.value, ast.Num):
sliceVal = node.slice.value.n
sliceRepr = repr(sliceVal)
elif isinstance(node.slice.value, ast.Str):
sliceVal = node.slice.value.s
sliceRepr = repr(sliceVal)
if sliceVal is not MISSING:
try:
node = _resolved(
'%s[%s]' % (node.value.representation, sliceRepr),
node.value.value[sliceVal])
except KeyError:
rslvd = node.value
if not isinstance(rslvd.value, dict):
raise
node = _resolved(rslvd.representation+".keys()",
sorted(rslvd.value.keys()),
valid=False)
return node
示例13: type_declaration_ast_to_ir2_expression_type
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def type_declaration_ast_to_ir2_expression_type(ast_node: ast.AST, compilation_context: CompilationContext):
if isinstance(ast_node, ast.Name) and isinstance(ast_node.ctx, ast.Load):
if ast_node.id == 'bool':
return ir2.BoolType()
elif ast_node.id == 'int':
return ir2.IntType()
elif ast_node.id == 'Type':
return ir2.TypeType()
else:
lookup_result = compilation_context.get_type_symbol_definition(ast_node.id)
if lookup_result:
return lookup_result.symbol.expr_type
else:
raise CompilationError(compilation_context, ast_node, 'Unsupported (or undefined) type: ' + ast_node.id)
if (isinstance(ast_node, ast.Subscript)
and isinstance(ast_node.value, ast.Name)
and isinstance(ast_node.value.ctx, ast.Load)
and isinstance(ast_node.ctx, ast.Load)
and isinstance(ast_node.slice, ast.Index)):
if ast_node.value.id == 'List':
return ir2.ListType(type_declaration_ast_to_ir2_expression_type(ast_node.slice.value, compilation_context))
if ast_node.value.id == 'Set':
return ir2.SetType(type_declaration_ast_to_ir2_expression_type(ast_node.slice.value, compilation_context))
elif (ast_node.value.id == 'Callable'
and isinstance(ast_node.slice.value, ast.Tuple)
and len(ast_node.slice.value.elts) == 2
and isinstance(ast_node.slice.value.elts[0], ast.List)
and isinstance(ast_node.slice.value.elts[0].ctx, ast.Load)
and all(isinstance(elem, ast.Name) and isinstance(elem.ctx, ast.Load)
for elem in ast_node.slice.value.elts[0].elts)):
return ir2.FunctionType(
argtypes=tuple(type_declaration_ast_to_ir2_expression_type(arg_type_decl, compilation_context)
for arg_type_decl in ast_node.slice.value.elts[0].elts),
argnames=None,
returns=type_declaration_ast_to_ir2_expression_type(ast_node.slice.value.elts[1], compilation_context))
raise CompilationError(compilation_context, ast_node, 'Unsupported type declaration.')
# Checks if the statement is of the form:
# self.some_field = <expr>
示例14: _unparse
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def _unparse(node: ast.expr) -> str:
if isinstance(node, ast.Name):
return node.id
elif isinstance(node, ast.Attribute):
return ''.join((_unparse(node.value), '.', node.attr))
elif isinstance(node, ast.Call):
return '{}()'.format(_unparse(node.func))
elif isinstance(node, ast.Subscript):
if sys.version_info >= (3, 9): # pragma: no cover (py39+)
# https://github.com/python/typeshed/pull/3950
node_slice: ast.expr = node.slice # type: ignore
elif isinstance(node.slice, ast.Index): # pragma: no cover (<py39)
node_slice = node.slice.value
else:
raise AssertionError(f'expected Slice: {ast.dump(node)}')
if isinstance(node_slice, ast.Tuple):
if len(node_slice.elts) == 1:
slice_s = f'{_unparse(node_slice.elts[0])},'
else:
slice_s = ', '.join(_unparse(elt) for elt in node_slice.elts)
else:
slice_s = _unparse(node_slice)
return '{}[{}]'.format(_unparse(node.value), slice_s)
elif isinstance(node, ast.Str):
return repr(node.s)
elif isinstance(node, ast.Ellipsis):
return '...'
elif isinstance(node, ast.List):
return '[{}]'.format(', '.join(_unparse(elt) for elt in node.elts))
elif isinstance(node, ast.NameConstant):
return repr(node.value)
else:
raise NotImplementedError(ast.dump(node))
示例15: visit_Subscript
# 需要导入模块: import ast [as 别名]
# 或者: from ast import Index [as 别名]
def visit_Subscript( s, node ):
obj = s.const_extractor.enter( node )
ret = s.handle_constant( node, obj )
if ret:
return ret
value = s.visit( node.value )
if isinstance( node.slice, ast.Slice ):
if node.slice.step is not None:
raise PyMTLSyntaxError( s.blk, node,
'Slice with steps is not supported!' )
lower, upper = s.visit( node.slice )
ret = bir.Slice( value, lower, upper )
ret.ast = node
return ret
# signal[ index ]
# index might be a slice object!
if isinstance( node.slice, ast.Index ):
idx = s.visit( node.slice )
# If we have a static slice object then use it
if isinstance( idx, bir.FreeVar ) and isinstance( idx.obj, slice ):
slice_obj = idx.obj
if slice_obj.step is not None:
raise PyMTLSyntaxError( s.blk, node,
'Slice with steps is not supported!' )
assert isinstance( slice_obj.start, int ) and \
isinstance( slice_obj.stop, int ), \
f"start and stop of slice object {slice_obj} must be integers!"
ret = bir.Slice( value,
bir.Number(slice_obj.start), bir.Number(slice_obj.stop) )
# Else this is a real index
else:
ret = bir.Index( value, idx )
ret.ast = node
return ret
raise PyMTLSyntaxError( s.blk, node,
'Illegal subscript ' + node + ' encountered!' )