How to use the astunparse.unparse function in astunparse

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 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
github OpenMDAO / OpenMDAO / openmdao / utils / ad_autograd.py View on Github external
srclines[0] = srclines[0].lstrip()
    src = ''.join(srclines)

    if mode == 'rev':
        # mapping to rename variables within the compute method
        to_replace, pnames, onames, rnames = _get_arg_replacement_map(comp)
        ast2 = ast.parse(src)

        # combine all mappings
        mapping = to_replace.copy()
        src_ast = transform_ast_names(ast2, mapping)
    else:
        src_ast = ast.parse(src)

    # make sure indenting is 4
    src = astunparse.unparse(src_ast)

    params = list(signature(compute_method).parameters)

    # add section of code to create a boxed version of the input dict from the input array
    pre_lines = [
        "    import openmdao.utils.mod_wrapper as mod_wrapper",
        "    np = mod_wrapper.np",
        "    numpy = np",
    ]

    vecnames = ['_invec_', '_outvec_', '_residvec_']
    self_vnames = ['self._inputs_autograd', 'self._outputs_autograd', 'self._resids_autograd']
    vecs = [comp._inputs, comp._outputs, comp._vectors['residual']['nonlinear']]
    groups = [(i, pname, vecnames[i], self_vnames[i], vecs[i]) for i, pname in enumerate(params)]

    input_id = 0

astunparse

An AST unparser for Python

BSD-2-Clause
Latest version published 5 years ago

Package Health Score

67 / 100
Full package analysis