How to use astunparse - 10 common examples

To help you get started, we’ve selected a few astunparse 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 inglesp / async-requests / generate_tests.py View on Github external
def visit_Expr(self, node):
        self.generic_visit(node)
        try:
            if node.value.func.attr in methods_to_yield_from:
                expr = astunparse.unparse(node)
                new_source = expr_template.format(expr=expr)
                new_node = ast.parse(new_source)
                return new_node
            else:
                return node
        except AttributeError:
            return node
github Blazemeter / taurus / tests / modules / selenium / test_selenium_builder.py View on Github external
]}]}}})

        self.obj.prepare()
        with open(self.obj.script) as fds:
            content = fds.read()

        target_lines = [
            "var_loc_keys=self.loc_mng.get_locator([{'name':'btn1',}])",
            "self.driver.find_element(var_loc_keys[0],var_loc_keys[1]).click()",
            "var_loc_keys=self.loc_mng.get_locator([{'id':'Id_123',}])",
            "self.driver.find_element(var_loc_keys[0],var_loc_keys[1]).clear()",
            "self.driver.find_element(var_loc_keys[0],var_loc_keys[1]).send_keys('London')"
        ]

        for idx in range(len(target_lines)):
            target_lines[idx] = astunparse.unparse(ast.parse(target_lines[idx]))
            self.assertIn(TestSeleniumScriptGeneration.clear_spaces(target_lines[idx]),
                          TestSeleniumScriptGeneration.clear_spaces(content),
                          msg="\n\n%s. %s" % (idx, target_lines[idx]))
github pixiedust / pixiegateway / pixiegateway / notebookMgr.py View on Github external
def warmup_code(self):
        if self._warmup_code is not None:
            return self._warmup_code
        if not self.is_valid:
            raise Exception("Trying to access warmup_code but not a valid pixieapp notebook")
        if self.symbols is not None and self.raw_warmup_code != "":
            rewrite = RewriteGlobals(self.symbols, self.namespace)
            new_root = rewrite.visit(ast_parse(self.raw_warmup_code))
            self._warmup_code = astunparse.unparse(new_root)
            app_log.debug("New warmup code: %s", self._warmup_code)
        else:
            self._warmup_code = ""
        return self._warmup_code
github quarkslab / sspam / sspam / simplifier.py View on Github external
node.value = self.simplify(node.value, self.nbits)
                copyvalue = deepcopy(node.value)
                # discard if NotToInv increased the size
                if len(unparse(copyvalue)) >= len(unparse(old_value)):
                    node.value = deepcopy(old_value)
                    copyvalue = deepcopy(node.value)
                copyvalue = Flattening().visit(copyvalue)
                old_value = Flattening().visit(old_value)
            if DEBUG:
                print "-"*80
        # final arithmetic simplification to clean output of matching
        node.value = arithm_simpl.run(node.value, self.nbits)
        asttools.GetConstMod(self.nbits).visit(node.value)
        if DEBUG:
            print "arithm simpl: "
            print unparse(node.value)
            print ""
            print "-"*80
        return node
github OpenMDAO / OpenMDAO / openmdao / devtools / dataflow.py View on Github external
# print("edges:", list(vis.graph.edges()))
                ppmap = get_matching_push_map(node) if check_stacks else {}

                un = unused(vis)
                changed = bool(un)
                import astunparse
                to_remove = set()
                # print("\nunused:")
                for n, s in un:
                    # print(n, astunparse.unparse(s))
                    to_remove.add(s)
                    if check_stacks and s in ppmap:
                        push = ppmap[s]
                        if push is None:
                            raise RuntimeError("No matching push for '%s'" %
                                               astunparse.unparse(s).strip())
                        else:
                            # print("matching push:", astunparse.unparse(ppmap[s]))
                            to_remove.add(ppmap[s])
                rem = Remover(to_remove)
                rem.visit(node)
                print("\n\nremoved:")
                # print(astunparse.unparse(node))

    return topnode
github psychopy / psychopy / psychopy / experiment / py2js.py View on Github external
namesJS['rand'] = 'Math.random'
namesJS['random'] = 'Math.random'


class TupleTransformer(ast.NodeTransformer):
    """ An ast subclass that walks the abstract syntax tree and
    allows modification of nodes.

    This class transforms a tuple to a list.

    :returns node
    """
    def visit_Tuple(self, node):
        return ast.List(node.elts, node.ctx)

class Unparser(astunparse.Unparser):
    """astunparser had buried the future_imports option underneath its init()
    so we need to override that method and change it."""

    def __init__(self, tree, file):
        """Unparser(tree, file=sys.stdout) -> None.
         Print the source for tree to file."""
        self.f = file
        self.future_imports = ['unicode_literals']
        self._indent = 0
        self.dispatch(tree)
        self.f.flush()


def unparse(tree):
    v = StringIO()
    Unparser(tree, file=v)
github SEL-Columbia / networkplanner / utilities / analyze_model_vars.py View on Github external
return "{}.{}".format(module_name, var_name)
        else:
            return var_name
            
    var_info['name'] = get_full_var_name(ast_cls.name, module_name)
    dependencies = set()
    
    cls_dict = member_dict(ast_cls)
    if 'units' in cls_dict:
        var_info['units'] = cls_dict['units']
    if 'default' in cls_dict:
        var_info['default'] = cls_dict['default']

    if 'aggregate' in cls_dict:
        fun_def = cls_dict['aggregate']
        var_info['fun_src'] = astunparse.unparse(fun_def)
        var_info['type'] = "AGGREGATE"
        dependencies = dependencies.union(
                           set([get_full_var_name(v, module_name) 
                                for v in get_dependencies_from_fun(fun_def)]))

    if 'compute' in cls_dict:
        fun_def = cls_dict['compute']
        var_info['fun_src'] = astunparse.unparse(fun_def)
        dependencies = dependencies.union(
                           set([get_full_var_name(v, module_name) 
                                for v in get_dependencies_from_fun(fun_def)]))

        if ast.dump(fun_def).find("interpolate") > 0:
            var_info['type'] = "CURVE_INTERPOLATE"
        else:
            for i in range(len(fun_def.body)):
github marcoeilers / nagini / src / nagini_translation / main.py View on Github external
print('Verification took ' + duration + ' seconds.')
    except (TypeException, InvalidProgramException, UnsupportedException) as e:
        print("Translation failed")
        if isinstance(e, (InvalidProgramException, UnsupportedException)):
            if isinstance(e, InvalidProgramException):
                issue = 'Invalid program: '
                if e.message:
                    issue += e.message
                else:
                    issue += e.code
            else:
                issue = 'Not supported: '
                if e.args[0]:
                    issue += e.args[0]
                else:
                    issue += astunparse.unparse(e.node)
            line = str(e.node.lineno)
            col = str(e.node.col_offset)
            print(issue + ' (' + python_file + '@' + line + '.' + col + ')')
        if isinstance(e, TypeException):
            for msg in e.messages:
                parts = TYPE_ERROR_MATCHER.match(msg)
                if parts:
                    parts = parts.groupdict()
                    file = parts['file']
                    if file == '__main__':
                        file = python_file
                    msg = parts['msg']
                    line = parts['line']
                    print('Type error: ' + msg + ' (' + file + '@' + line + '.0)')
                else:
                    print(msg)
github spcl / dace / dace / frontend / python / astutils.py View on Github external
def unparse(node):
    """ Unparses an AST node to a Python string, chomping trailing newline. """
    if node is None:
        return None
    return astunparse.unparse(node).strip()
github marcoeilers / nagini / src / nagini_translation / lib / util.py View on Github external
def pprint(node) -> str:
    """
    Pretty prints a Python AST node. When given a string, just returns it.
    """
    if not node:
        raise ValueError(node)
    if isinstance(node, str):
        return node
    if isinstance(node, ast.FunctionDef):
        # Mainly for debugging, whenever this happens it's almost certainly
        # wrong.
        raise ValueError(node)
    res = astunparse.unparse(node)
    res = res.replace('\n', '')
    return res

astunparse

An AST unparser for Python

BSD-2-Clause
Latest version published 5 years ago

Package Health Score

67 / 100
Full package analysis