Python ast.Subscript() Examples
The following are 30
code examples of ast.Subscript().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ast
, or try the search function
.
Example #1
Source File: parser.py From vecpy with MIT License | 6 votes |
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)
Example #2
Source File: expression.py From hadrian with Apache License 2.0 | 6 votes |
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)]))
Example #3
Source File: onelinerizer.py From onelinerizer with MIT License | 6 votes |
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)))
Example #4
Source File: yacc.py From yaksok with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #5
Source File: test_ast.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
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")
Example #6
Source File: topython.py From pyrser with GNU General Public License v3.0 | 6 votes |
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)
Example #7
Source File: formatting.py From snoop with MIT License | 6 votes |
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 []
Example #8
Source File: notebook.py From Gofer-Grader with BSD 3-Clause "New" or "Revised" License | 6 votes |
def find_check_assignment(tree): """Given an AST for a source, check for variable redefinition of `check` Returns True if such a definition is found, False otherwise.""" for stmt in ast.walk(tree): if not isinstance(stmt, ast.Assign): continue # check id for tuple target target_names = [] for target in stmt.targets: if isinstance(target, tuple): target_names += [t.id for t in target] elif isinstance(target, ast.Tuple) or isinstance(target, ast.List): target_names += [t.id for t in target.elts] elif isinstance(target, ast.Subscript): target_names.append(target.value.id) else: target_names.append(target.id) if 'check' in target_names: return True return False
Example #9
Source File: hgawk_test.py From histogrammar-python with Apache License 2.0 | 6 votes |
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
Example #10
Source File: pyast64.py From pyast64 with MIT License | 6 votes |
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))
Example #11
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 6 votes |
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
Example #12
Source File: core.py From ibis with Apache License 2.0 | 6 votes |
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) )
Example #13
Source File: source_visitor.py From vermin with MIT License | 6 votes |
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+")
Example #14
Source File: translation.py From mochi with MIT License | 6 votes |
def _translate_get_slice(self, lineno, target, start=None, stop=None, step=None): pre = [] target_pre, target_value = self.translate(target, False) pre.extend(target_pre) start_pre, start_value = self.translate(start, False) if start is not None else ((), None) pre.extend(start_pre) stop_pre, stop_value = self.translate(stop, False) if stop is not None else ((), None) pre.extend(stop_pre) step_pre, step_value = self.translate(step, False) if step is not None else ((), None) pre.extend(step_pre) return pre, ast.Subscript(value=target_value, slice=ast.Slice(lower=start_value, upper=stop_value, step=step_value), ctx=ast.Load(), lineno=lineno, col_offset=0)
Example #15
Source File: visitors.py From pymtl with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #-------------------------------------------------------------------------
Example #16
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 6 votes |
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")
Example #17
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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")
Example #18
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 6 votes |
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
Example #19
Source File: builder.py From staticfg with Apache License 2.0 | 6 votes |
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)
Example #20
Source File: parser.py From vecpy with MIT License | 5 votes |
def expression(self, block, expr, var=None): if isinstance(expr, ast.Num): var = self.add_literal(expr.n) elif isinstance(expr, ast.Name): var = self.kernel.get_variable(expr.id) if var is None: raise Exception('Undefined Variable (%s)'%(expr.id)) if var.is_fuse: raise Exception('Fuse variables are write-only') if var.is_arg: var.is_input = True elif isinstance(expr, ast.BinOp): var = self.binop(block, expr, var) elif isinstance(expr, ast.UnaryOp): var = self.unaryop(block, expr) elif isinstance(expr, ast.Call): var = self.call(block, expr, var) elif isinstance(expr, ast.Attribute): var = self.attribute(block, expr) elif isinstance(expr, ast.Compare): var = self.compare(block, expr) elif isinstance(expr, ast.BoolOp): var = self.boolop(block, expr) elif isinstance(expr, ast.Subscript): (var, assignment) = self.subscript(block, expr) block.add(assignment) else: Parser._dump(expr, 'Unexpected Expression') raise Exception('Unexpected Expression (%s)'%(expr.__class__)) return var #Generates a new block mask
Example #21
Source File: parallel.py From XQuant with MIT License | 5 votes |
def is_valid_assignment(self, node): if not (type(node) is ast.Assign and self.is_concurrent_call(node.value)): return False if len(node.targets) != 1: raise ValueError("并发不支持多个赋值对象") if not type(node.targets[0]) is ast.Subscript: raise ValueError("并发只支持可索引对象") return True
Example #22
Source File: _devtools.py From mutatest with MIT License | 5 votes |
def visit_Subscript(self, node: ast.Subscript) -> None: # iterable indexing, has Slice operations print(f"Subscript: {node}") print(ast.dump(node)) self.generic_visit(node) # IN DEVELOPMENT ################################################################################################ # FUTURE DEVELOPMENT ################################################################################################
Example #23
Source File: parallel.py From XQuant with MIT License | 5 votes |
def top_level_name(node): if type(node) is ast.Name: return node.id elif type(node) is ast.Subscript or type(node) is ast.Attribute: return SchedulerRewriter.top_level_name(node.value) return None
Example #24
Source File: utils.py From executing with MIT License | 5 votes |
def __getitem__(self, item): node = self.get_node(ast.Subscript) self.check(node.value, self) self.check(subscript_item(node), item) return self
Example #25
Source File: python_util.py From guildai with Apache License 2.0 | 5 votes |
def _func_name(self, func): if isinstance(func, ast.Name): return func.id elif isinstance(func, ast.Attribute): return func.attr elif isinstance(func, ast.Call): return self._func_name(func.func) elif isinstance(func, ast.Subscript): return None else: raise AssertionError(func)
Example #26
Source File: test_main.py From executing with MIT License | 5 votes |
def is_literal(node): if isinstance(node, ast.UnaryOp): return is_literal(node.operand) if isinstance(node, ast.BinOp): return is_literal(node.left) and is_literal(node.right) if isinstance(node, ast.Compare): return all(map(is_literal, [node.left] + node.comparators)) if isinstance(node, ast.Subscript) and is_literal(node.value): if isinstance(node.slice, ast.Slice): return all( x is None or is_literal(x) for x in [ node.slice.lower, node.slice.upper, node.slice.step, ] ) else: return is_literal(subscript_item(node)) try: ast.literal_eval(node) return True except ValueError: return False
Example #27
Source File: tests.py From executing with MIT License | 5 votes |
def __getitem__(self, item): node = self.get_node(ast.Subscript) self.check(node.value, self) self.check(node.slice.value, item) return self
Example #28
Source File: gen.py From ChromeController with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __build_conditional_arg_check(self, argname, argtype): target_value = ast.Subscript( value=ast.Name(id='kwargs', ctx=ast.Load()), slice=ast.Index(ast.Str(s=argname)), ctx=ast.Load() ) presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()), args = [target_value, argtype], keywords = [], lineno = self.__get_line()) # Assumes that argtype is a ast.Tuple of ast.Name items types = [t.id for t in argtype.elts] check_message = ast.BinOp( left = ast.Str(s='Optional argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)), op = ast.Mod(), right = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[target_value], keywords=[]), lineno = self.__get_line()) assert_check = ast.Assert( test = presence_check, msg = check_message, lineno = self.__get_line()) check_body = [assert_check] check = ast.Compare(left=ast.Str(s=argname, ctx=ast.Load()), ops=[ast.In()], comparators=[ast.Name(id='kwargs', ctx=ast.Load())]) new_ret = ast.If( test = check, body = check_body, orelse = [], lineno = self.__get_line()) return new_ret
Example #29
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_trailer_3(p): '''trailer : LSQB subscriptlist RSQB''' # 1 2 3 p[0] = ast.Subscript(None, p[2], ast.Load(), rule=inspect.currentframe().f_code.co_name)
Example #30
Source File: definitions.py From vkbottle with MIT License | 5 votes |
def assign(d: ast.Assign): left = d.targets left_ = [] for target in left: if target.__class__ == ast.Name: left_.append(find(target)) elif target.__class__ == ast.Subscript: pass right = find(d.value) return "var " + ",".join(f"{target}={right}" for target in left_) + ";"