當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.Subscript方法代碼示例

本文整理匯總了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)])) 
開發者ID:modelop,項目名稱:hadrian,代碼行數:18,代碼來源:expression.py

示例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 [] 
開發者ID:alexmojaki,項目名稱:snoop,代碼行數:24,代碼來源:formatting.py

示例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) 
開發者ID:LionelAuroux,項目名稱:pyrser,代碼行數:20,代碼來源:topython.py

示例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)) 
開發者ID:benhoyt,項目名稱:pyast64,代碼行數:20,代碼來源:pyast64.py

示例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) 
開發者ID:coetaur0,項目名稱:staticfg,代碼行數:19,代碼來源:builder.py

示例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)
        ) 
開發者ID:ibis-project,項目名稱:ibis,代碼行數:26,代碼來源:core.py

示例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") 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:19,代碼來源:test_ast.py

示例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
#------------------------------------------------------------------------- 
開發者ID:cornell-brg,項目名稱:pymtl,代碼行數:23,代碼來源:visitors.py

示例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+") 
開發者ID:netromdk,項目名稱:vermin,代碼行數:21,代碼來源:source_visitor.py

示例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) 
開發者ID:undefx,項目名稱:vecpy,代碼行數:27,代碼來源:parser.py

示例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 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:25,代碼來源:hgawk_grammar.py

示例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 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:25,代碼來源:hgawk_grammar.py

示例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 
開發者ID:histogrammar,項目名稱:histogrammar-python,代碼行數:23,代碼來源:hgawk_test.py

示例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 
開發者ID:yaksok,項目名稱:yaksok,代碼行數:20,代碼來源:yacc.py

示例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))) 
開發者ID:csvoss,項目名稱:onelinerizer,代碼行數:25,代碼來源:onelinerizer.py


注:本文中的ast.Subscript方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。