How to use the gast.Index function in gast

To help you get started, we’ve selected a few gast examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github zylo117 / tensorflow-gpu-macosx / tensorflow / contrib / autograph / pyct / qual_names.py View on Github external
def visit_Subscript(self, node):
    node = self.generic_visit(node)
    s = node.slice
    if not isinstance(s, gast.Index):
      # TODO(mdan): Support range and multi-dimensional indices.
      # Continuing silently because some demos use these.
      return node
    if isinstance(s.value, gast.Num):
      subscript = QN(NumberLiteral(s.value.n))
    elif isinstance(s.value, gast.Str):
      subscript = QN(StringLiteral(s.value.s))
    else:
      subscript = anno.getanno(node.slice.value, anno.Basic.QN)
    if anno.hasanno(node.value, anno.Basic.QN):
      anno.setanno(node, anno.Basic.QN,
                   QN(anno.getanno(node.value, anno.Basic.QN),
                      subscript=subscript))
    return node
github martinRenou / ipycanvas / ipycanvas / animation.py View on Github external
def visit_Subscript(self, node):
        """Turn a Python Subscript node into JavaScript code."""
        value = self.visit(node.value)

        if isinstance(node.slice, ast.Index):
            return '{value}[{index}]'.format(
                value=value,
                index=self.visit(node.slice.value)
            )

        raise Py2JSSyntaxError('Unsupported {} node'.format(node.slice.__class__.__name__))
github serge-sans-paille / pythran / pythran / tables.py View on Github external
return_alias=lambda args: {
                ast.Subscript(args[0],
                              ast.Index(args[1]),
                              ast.Load())
            }.union({args[2]} if len(args) == 3 else set())
        ),
github zylo117 / tensorflow-gpu-macosx / tensorflow / contrib / autograph / pyct / qual_names.py View on Github external
def ast(self):
    # The caller must adjust the context appropriately.
    if self.has_subscript():
      return gast.Subscript(self.parent.ast(), gast.Index(self.qn[-1].ast()),
                            None)
    if self.has_attr():
      return gast.Attribute(self.parent.ast(), self.qn[-1], None)

    base = self.qn[0]
    if isinstance(base, str):
      return gast.Name(base, None, None)
    elif isinstance(base, StringLiteral):
      return gast.Str(base.value)
    elif isinstance(base, NumberLiteral):
      return gast.Num(base.value)
    else:
      assert False, ('the constructor should prevent types other than '
                     'str, StringLiteral and NumberLiteral')
github google / tangent / tangent / template.py View on Github external
def visit_Subscript(self, node):
    if isinstance(node.value, (gast.Name, gast.Num)) and node.value.id == 'd':
      if (not isinstance(node.slice, gast.Index) or
          not isinstance(node.slice.value,
                         (gast.Subscript, gast.Name, gast.Str))):
        # This happens when the gradient of a constant is taken
        if self.replace_grad == Replace.TANGENT:
          new_node = gast.Num(0)
        else:
          new_node = gast.Name(id='_', ctx=None, annotation=None)
          self.remove(new_node)
      elif (self.replace_grad in (Replace.FULL, Replace.TANGENT) or
            isinstance(node.ctx, gast.Load)):
        new_node = create.create_grad(node.slice.value, self.namer,
                                      self.tangent)
      elif isinstance(node.ctx, gast.Store):
        new_node = create.create_temp_grad(node.slice.value, self.namer,
                                           self.tangent)
      else:
github pfnet-research / chainer-compiler / ch2o / ch2o / chainer2onnx.py View on Github external
if isinstance(self, gast.Slice):
            assert self.step is None

            def f(x, v):
                if x is None:
                    return Value(v).to_tensor(env)
                x = eval_ast(x, env)
                if istensor(x):
                    return x
                else:
                    return x.to_tensor(env)
            lower = unsqueeze(f(self.lower, 0))
            # TODO(satos) その場しのぎっぽいのでどうにかする(けどこれどうにもならないですよね...?)
            upper = unsqueeze(f(self.upper, int_max))
            squeeze = [False]
        elif isinstance(self, gast.Index):
            idx = eval_ast(self.value, env)
            if isinstance(idx.value, tuple):  # ここにTupleが来うる
                # TODO(satos) もっとうまくやったほうがいいかも
                vs = [gast.Index(gast.NameConstant(value=v)) for v in idx.value]
                lower, upper, squeeze = slice2list(gast.ExtSlice(dims=vs))
            elif not idx.is_py:
                lower = unsqueeze(idx.value)
                ot = totensor(1, env)
                upper = env.calc(
                    "Add",
                    inputs=[idx.to_tensor(env).name, ot.name],
                )
                upper = unsqueeze(upper)
                squeeze = [True]
            else:
                lower = unsqueeze(totensor(idx.value, env))
github pfnet-research / chainer-compiler / ch2o / ch2o / chainer2onnx.py View on Github external
if x is None:
                    return Value(v).to_tensor(env)
                x = eval_ast(x, env)
                if istensor(x):
                    return x
                else:
                    return x.to_tensor(env)
            lower = unsqueeze(f(self.lower, 0))
            # TODO(satos) その場しのぎっぽいのでどうにかする(けどこれどうにもならないですよね...?)
            upper = unsqueeze(f(self.upper, int_max))
            squeeze = [False]
        elif isinstance(self, gast.Index):
            idx = eval_ast(self.value, env)
            if isinstance(idx.value, tuple):  # ここにTupleが来うる
                # TODO(satos) もっとうまくやったほうがいいかも
                vs = [gast.Index(gast.NameConstant(value=v)) for v in idx.value]
                lower, upper, squeeze = slice2list(gast.ExtSlice(dims=vs))
            elif not idx.is_py:
                lower = unsqueeze(idx.value)
                ot = totensor(1, env)
                upper = env.calc(
                    "Add",
                    inputs=[idx.to_tensor(env).name, ot.name],
                )
                upper = unsqueeze(upper)
                squeeze = [True]
            else:
                lower = unsqueeze(totensor(idx.value, env))
                upper_value = idx.value + 1 if idx.value != -1 else int_max
                upper = unsqueeze(totensor(upper_value, env))
                squeeze = [True]
        elif isinstance(self, gast.ExtSlice):
github serge-sans-paille / pythran / pythran / analyses / aliases.py View on Github external
def parametrize(exp):
                # constant(?) or global -> no change
                if isinstance(exp, (ast.Index, Intrinsic, ast.FunctionDef)):
                    return lambda _: {exp}
                elif isinstance(exp, ContainerOf):
                    pcontainee = parametrize(exp.containee)
                    index = exp.index
                    return lambda args: {
                        ContainerOf(pc, index)
                        for pc in pcontainee(args)
                    }
                elif isinstance(exp, ast.Name):
                    try:
                        w = node.args.args.index(exp)

                        def return_alias(args):
                            if w < len(args):
                                return {args[w]}
                            else:
github serge-sans-paille / pythran / pythran / types / tog.py View on Github external
)
        new_value_type = TypeVariable()
        for value in node.values:
            value_type = analyse(value, env, non_generic)
            try:
                unify(new_value_type, value_type)
            except InferenceError:
                raise PythranTypeError(
                    "Incompatible dict value type `{}` and `{}`".format(
                        new_value_type, value_type),
                    node
                )
        return Dict(new_key_type, new_value_type)
    elif isinstance(node, gast.Tuple):
        return Tuple([analyse(elt, env, non_generic) for elt in node.elts])
    elif isinstance(node, gast.Index):
        return analyse(node.value, env, non_generic)
    elif isinstance(node, gast.Slice):
        def unify_int_or_none(t, name):
            try:
                unify(t, Integer())
            except InferenceError:
                try:
                    unify(t, NoneType)
                except InferenceError:
                    raise PythranTypeError(
                        "Invalid slice {} type `{}`, expecting int or None"
                        .format(name, t)
                    )
        if node.lower:
            lower_type = analyse(node.lower, env, non_generic)
            unify_int_or_none(lower_type, 'lower bound')

gast

Python AST that abstracts the underlying Python version

BSD-3-Clause
Latest version published 4 months ago

Package Health Score

78 / 100
Full package analysis