Python ast.Index() Examples

The following are 30 code examples of ast.Index(). 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: py2php.py    From yaraspell with GNU General Public License v3.0 6 votes vote down vote up
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(')') 
Example #2
Source File: expression.py    From hadrian with Apache License 2.0 6 votes vote down vote up
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: topython.py    From pyrser with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: test_ast.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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: lookuptable_connector.py    From ABXpy with MIT License 6 votes vote down vote up
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 
Example #7
Source File: parser.py    From myia with MIT License 6 votes vote down vote up
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 
Example #8
Source File: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #9
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: hgawk_test.py    From histogrammar-python with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: ast2.py    From gast with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #12
Source File: _343.py    From codetransformer with GNU General Public License v2.0 6 votes vote down vote up
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
        ]
    ) 
Example #13
Source File: commonast.py    From pscript with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _convert_Index(self, n):
        return Index(self._convert(n.value)) 
Example #14
Source File: onelinerizer.py    From onelinerizer with MIT License 5 votes vote down vote up
def slice_repr(self, slice):
        if type(slice) is ast.Ellipsis:
            return T('Ellipsis')
        elif type(slice) is ast.Slice:
            return T('slice({}, {}, {})').format(
                'None' if slice.lower is None else self.visit(slice.lower),
                'None' if slice.upper is None else self.visit(slice.upper),
                'None' if slice.step is None else self.visit(slice.step))
        elif type(slice) is ast.ExtSlice:
            return T('({})').format(T(', ').join(map(self.slice_repr, slice.dims)) +
                                    ','*(len(slice.dims) == 1))
        elif type(slice) is ast.Index:
            return self.visit(slice.value)
        else:
            raise NotImplementedError('Case not caught: %s' % str(type(slice))) 
Example #15
Source File: gen.py    From ChromeController with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #16
Source File: translation.py    From mochi with MIT License 5 votes vote down vote up
def _translate_get_index(self, exp):
        pre = []
        target_pre, target_value = self.translate(exp[1], False)
        pre.extend(target_pre)
        index_pre, index_value = self.translate(exp[2], False)
        pre.extend(index_pre)
        return pre, ast.Subscript(value=target_value,
                                  slice=ast.Index(value=index_value),
                                  ctx=ast.Load(),
                                  lineno=exp[0].lineno,
                                  col_offset=0) 
Example #17
Source File: flatten.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Index(self, index: ast.Index) -> VisitSliceReturnT:
        value_flattened, value_actions = self.visit_expr(index.value)
        return ast.Index(value=value_flattened), value_actions 
Example #18
Source File: subscripts.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _check_float_key(self, node: ast.Subscript) -> None:
        is_float_key = (
            isinstance(node.slice, ast.Index) and
            self._is_float_key(node.slice)
        )

        if is_float_key:
            self.add_violation(best_practices.FloatKeyViolation(node)) 
Example #19
Source File: setup_info.py    From requirementslib with MIT License 5 votes vote down vote up
def unparse_Subscript(self, item):
        unparsed = self.unparse(item.value)
        if isinstance(item.slice, ast.Index):
            try:
                unparsed = unparsed[self.unparse(item.slice.value)]
            except (KeyError, TypeError):
                # not everything can be looked up before runtime
                unparsed = item
        return unparsed 
Example #20
Source File: slices.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def is_same_slice(
    iterable: str,
    target: str,
    node: ast.Subscript,
) -> bool:
    """Used to tell when slice is identical to some pair of name/index."""
    return (
        source.node_to_string(node.value) == iterable and
        isinstance(node.slice, ast.Index) and  # mypy is unhappy
        source.node_to_string(node.slice.value) == target
    ) 
Example #21
Source File: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def p_target_subscription(t):
    '''target : primary LSQUARE expression RSQUARE'''
    index = ast.Index(make_sub_one(t, 3))
    index.lineno = t.lineno(3)
    index.col_offset = -1  # XXX
    subscription = ast.Subscript(t[1], index, ast.Store())
    subscription.lineno = t.lineno(1)
    subscription.col_offset = -1  # XXX
    t[0] = [subscription] 
Example #22
Source File: py_converter.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def create_match_check(self, pattern: Pattern, data):
        """Given an ADT match pattern and a (Python) expression pointing to
        an ADT value, this generates a Python expression that checks if the
        ADT value matches the given pattern (returning True or False)."""

        # wildcard or var match everything
        if isinstance(pattern, (relay.PatternWildcard, relay.PatternVar)):
            return NameConstant(True)

        conds = []

        if isinstance(pattern, relay.PatternConstructor):
            # constructor patterns check whether the constructors match
            # and also the matches of any nested patterns

            # equiv: (arg.tag == patern_constructor.tag)
            conds.append(ast.Compare(ast.Attribute(data, 'tag', Load()),
                                     [ast.Eq()],
                                     [ast.Num(pattern.constructor.tag)]))

        assert isinstance(pattern, (relay.PatternConstructor, relay.PatternTuple))
        # now check for any nested patterns
        for i in range(len(pattern.patterns)):
            nested_pat = pattern.patterns[i]
            # can safely skip var or wildcard patterns: they will
            # never cause a check to fail
            if not isinstance(nested_pat, relay.PatternConstructor):
                continue

            # index into the value corresponding to the subpattern
            field_index = ast.Subscript(ast.Attribute(data, 'fields', Load()),
                                        ast.Index(Num(i)), Load())
            conds.append(self.create_match_check(nested_pat, field_index))

        # if we do not need to check nested pattern, just return the single check
        if len(conds) == 1:
            return conds[0]
        # otherwise AND together any nested checks
        return ast.BoolOp(ast.And(), conds) 
Example #23
Source File: test_horizon.py    From reconbf with Apache License 2.0 5 votes vote down vote up
def _parse_config(conf_content):

    conf_ast = ast.parse(conf_content)
    config = {}

    for statement in conf_ast.body:
        if not isinstance(statement, ast.Assign):
            # ignore complicated statements
            continue

        target = statement.targets[0]
        if isinstance(target, ast.Name):
            name = target.id
        elif (isinstance(target, ast.Subscript) and
              isinstance(target.value, ast.Name) and
              isinstance(target.slice, ast.Index) and
              isinstance(target.slice.value, ast.Str)):
            # cheat a bit since this name is illegal for variable
            name = "%s[%s]" % (target.value.id, target.slice.value.s)
        else:
            logger.warning('cannot parse assignment at line %i',
                           statement.lineno)
            continue

        try:
            config[name] = _resolve_constant(statement.value)
        except NotConstant:
            logger.warning('value assigned to %s in horizon config could not '
                           'be parsed as a constant', name)
            continue

    return config 
Example #24
Source File: py_converter.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def visit_tuple_getitem(self, tgi: Expr):
        tup, tup_defs = self.visit(tgi.tuple_value)
        ret = ast.Subscript(tup, ast.Index(Num(tgi.index)), Load())
        return (ret, tup_defs) 
Example #25
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_subscript_2(p):
    '''subscript : test'''
    #                 1
    p[0] = ast.Index(p[1], rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(p[0], p[1]) 
Example #26
Source File: converter.py    From Airtight with MIT License 5 votes vote down vote up
def convert_subscript(self, value, slice, ctx, context):
        if isinstance(slice, ast.Index):
            return hm_ast.Multi_Apply(
                hm_ast.Ident('a' + self.OPERATOR_MAGIC_FUNCTIONS[type(slice)]), [
                self.convert_node(value, context),
                self.convert_node(slice.value)])
        else:
            return hm_ast.Multi_Apply(
                hm_ast.Ident('a' + self.OPERATOR_MAGIC_FUNCTIONS[type(slice)]), [
                self.convert_node(value, context),
                self.convert_node(slice.lower) if slice.lower else hm_ast.anInteger(0),
                self.convert_node(slice.upper) if slice.upper else hm_ast.Multi_Apply(
                    self.OPERATOR_MAGIC_FUNCTIONS[ast.Sub], [
                    hm_ast.Apply(hm_ast.Ident('len'), self.convert_node(value, context)),
                    hm_ast.anInteger(1)])]) 
Example #27
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_subscriptlist_4(p):
    '''subscriptlist : subscript subscriptlist_star COMMA'''
    #                          1                  2     3
    args = [p[1]] + p[2]
    if all(isinstance(x, ast.Index) for x in args):
        tup = ast.Tuple([x.value for x in args], ast.Load(), rule=inspect.currentframe().f_code.co_name, paren=False)
        inherit_lineno(tup, args[0].value)
        p[0] = ast.Index(tup, rule=inspect.currentframe().f_code.co_name)
        inherit_lineno(p[0], tup)
    else:
        p[0] = ast.ExtSlice(args, rule=inspect.currentframe().f_code.co_name)
        inherit_lineno(p[0], p[1]) 
Example #28
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_subscriptlist_3(p):
    '''subscriptlist : subscript subscriptlist_star'''
    #                          1                  2
    args = [p[1]] + p[2]
    if all(isinstance(x, ast.Index) for x in args):
        tup = ast.Tuple([x.value for x in args], ast.Load(), rule=inspect.currentframe().f_code.co_name, paren=False)
        inherit_lineno(tup, args[0].value)
        p[0] = ast.Index(tup, rule=inspect.currentframe().f_code.co_name)
        inherit_lineno(p[0], tup)
    else:
        p[0] = ast.ExtSlice(args, rule=inspect.currentframe().f_code.co_name)
        inherit_lineno(p[0], p[1]) 
Example #29
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_subscriptlist_2(p):
    '''subscriptlist : subscript COMMA'''
    #                          1     2
    if isinstance(p[1], ast.Index):
        tup = ast.Tuple([p[1].value], ast.Load(), rule=inspect.currentframe().f_code.co_name, paren=False)
        inherit_lineno(tup, p[1].value)
        p[0] = ast.Index(tup, rule=inspect.currentframe().f_code.co_name)
        inherit_lineno(p[0], tup)
    else:
        p[0] = ast.ExtSlice([p[1]], rule=inspect.currentframe().f_code.co_name)
        inherit_lineno(p[0], p[1]) 
Example #30
Source File: subscripts.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def _is_float_key(self, node: ast.Index) -> bool:
        real_node = operators.unwrap_unary_node(node.value)
        return (
            isinstance(real_node, ast.Num) and
            isinstance(real_node.n, float)
        )