How to use gast - 10 common examples

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 tensorflow / tensorflow / tensorflow / python / autograph / pyct / testing / codegen.py View on Github external
"""Generate an If node."""
    test = self.generate_Compare()

    # Generate true branch statements
    body = self.sample_node_list(
        low=1,
        high=N_CONTROLFLOW_STATEMENTS // 2,
        generator=self.generate_statement)

    # Generate false branch statements
    orelse = self.sample_node_list(
        low=1,
        high=N_CONTROLFLOW_STATEMENTS // 2,
        generator=self.generate_statement)

    node = gast.If(test, body, orelse)
    return node
github serge-sans-paille / beniget / tests / definitions.py View on Github external
def checkLocals(self, code, ref):
        node = ast.parse(code)
        c = StrictDefUseChains()
        c.visit(node)
        functions = [n for n in node.body if isinstance(n, ast.FunctionDef)]
        assert len(functions) == 1, "only one top-level function per test case"
        f = functions[0]
        self.assertEqual(c.dump_definitions(f), ref)
github serge-sans-paille / beniget / tests / chains.py View on Github external
def check_unbound_identifier_message(self, code, expected_messages, filename=None):
        node = ast.parse(code)
        c = beniget.DefUseChains(filename)
        with captured_output() as (out, err):
            c.visit(node)
        produced_messages = out.getvalue().strip().split("\n")

        self.assertEqual(len(expected_messages), len(produced_messages))
        for expected, produced in zip(expected_messages, produced_messages):
            self.assertIn(expected, produced, "actual message contains expected message")
github tensorflow / tensorflow / tensorflow / python / autograph / pyct / testing / codegen.py View on Github external
def generate_Assign(self):
    """Generate an Assign node."""
    # Generate left-hand side
    target_node = self.generate_Name(gast.Store())
    # Generate right-hand side
    value_node = self.generate_expression()
    # Put it all together
    node = gast.Assign(targets=[target_node], value=value_node)
    return node
github tensorflow / tensorflow / tensorflow / python / autograph / pyct / testing / codegen.py View on Github external
        low=2, high=10, generator=lambda: self.generate_Name(gast.Param()))
    args = gast.arguments(arg_vars, None, [], [], None, [])
github google / tangent / tests / test_template.py View on Github external
def test_statement_replace():
  def f(body):
    body

  body = [gast.Expr(value=gast.Name(id=var, ctx=gast.Load(), annotation=None))
          for var in 'xy']
  new_body = template.replace(f, body=body)
  assert len(new_body) == 2
  assert isinstance(new_body[0], gast.Expr)
  compile_.compile_function(_wrap(new_body))
github google / tangent / tests / test_template.py View on Github external
def test_statement_replace():
  def f(body):
    body

  body = [gast.Expr(value=gast.Name(id=var, ctx=gast.Load(), annotation=None))
          for var in 'xy']
  new_body = template.replace(f, body=body)
  assert len(new_body) == 2
  assert isinstance(new_body[0], gast.Expr)
  compile_.compile_function(_wrap(new_body))
github serge-sans-paille / pythran / pythran / optimizations / comprehension_patterns.py View on Github external
if node in self.optimizable_comprehension:
            self.update = True
            self.generic_visit(node)

            iters = [self.make_Iterator(gen) for gen in node.generators]
            variables = [ast.Name(gen.target.id, ast.Param(), None, None)
                         for gen in node.generators]

            # If dim = 1, product is useless
            if len(iters) == 1:
                iterAST = iters[0]
                varAST = ast.arguments([variables[0]], [], None, [], [], None, [])
            else:
                self.use_itertools = True
                prodName = ast.Attribute(
                    value=ast.Name(id=mangle('itertools'),
                                   ctx=ast.Load(),
                                   annotation=None, type_comment=None),
                    attr='product', ctx=ast.Load())

                varid = variables[0].id  # retarget this id, it's free
                renamings = {v.id: (i,) for i, v in enumerate(variables)}
                node.elt = ConvertToTuple(varid, renamings).visit(node.elt)
                iterAST = ast.Call(prodName, iters, [])
                varAST = ast.arguments([ast.Name(varid, ast.Param(), None, None)],
                                       [], None, [], [], None, [])

            ldBodymap = node.elt
            ldmap = ast.Lambda(varAST, ldBodymap)

            return make_attr(ldmap, iterAST)
github zylo117 / tensorflow-gpu-macosx / tensorflow / contrib / autograph / converters / decorators.py View on Github external
def visit_FunctionDef(self, node):
    self.generic_visit(node)
    kept_decorators = []
    for dec in node.decorator_list:
      if isinstance(dec, gast.Call):
        dec_func = dec.func
      else:
        dec_func = dec

      # Special cases.
      # TODO(mdan): Is there any way we can treat these more generically?
      # We may want to forego using decorators altogether if we can't
      # properly support them.
      if isinstance(dec_func, gast.Name) and dec_func.id in ('classmethod',):
        # Assumption: decorators are only visible in the AST when converting
        # a function inline (via another decorator).
        # In that case, the converted function is no longer part of the
        # original object that it was declared into.
        # This is currently verified by tests.
        continue

      if not anno.hasanno(dec_func, 'live_val'):
        raise ValueError(
            'Could not resolve decorator: %s' % pretty_printer.fmt(dec_func))

      dec_value = anno.getanno(dec_func, 'live_val')
      if dec_value not in self.remove_decorators:
        kept_decorators.append((dec, dec_value))

    for _, dec_value in kept_decorators:
github tensorflow / tensorflow / tensorflow / contrib / autograph / pyct / ast_util.py View on Github external
def _process(self, node):
    qn = anno.getanno(node, anno.Basic.QN)
    if qn in self.name_map:
      return gast.Name(str(self.name_map[qn]), node.ctx, None)
    return self.generic_visit(node)