How to use pythran - 10 common examples

To help you get started, we’ve selected a few pythran 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 serge-sans-paille / pythran / pythran / range.py View on Github external
Combiner for Floor divide operation.

    >>> import gast as ast
    >>> combine(Range(-1, 5), Range(3, 8), ast.FloorDiv())
    Range(low=-1, high=1)
    >>> combine(Range(-1, 5), Range(-5, -4), ast.FloorDiv())
    Range(low=-2, high=0)
    >>> combine(Range(-1, 5), Range(-5, 3), ast.FloorDiv())
    Range(low=-inf, high=inf)
    """
    if range2.low <= 0 and range2.high >= 0:
        return UNKNOWN_RANGE
    if 0 in range2:
        return UNKNOWN_RANGE
    res = [v1 // v2 for v1, v2 in itertools.product(range1, range2)]
    return Range(numpy.min(res), numpy.max(res))
github serge-sans-paille / pythran / pythran / transformations / normalize_static_if.py View on Github external
if flag == LOOP_BREAK:
                ret_val.func.attr = "StaticIfBreak"
            else:
                ret_val.func.attr = "StaticIfCont"
        else:
            new_node.value.elts[0].n = flag
        return new_node

    def visit_Break(self, node):
        return self.patch_Control(node, LOOP_BREAK)

    def visit_Continue(self, node):
        return self.patch_Control(node, LOOP_CONT)


class NormalizeStaticIf(Transformation):

    def __init__(self):
        super(NormalizeStaticIf, self).__init__(StaticExpressions, Ancestors,
                                                DefUseChains)

    def visit_Module(self, node):
        self.new_functions = []
        self.funcs = []
        self.generic_visit(node)
        node.body.extend(self.new_functions)
        return node

    def escaping_ids(self, scope_stmt, stmts):
        'gather sets of identifiers defined in stmts and used out of it'
        assigned_ids = self.gather(IsAssigned, self.make_fake(stmts))
        escaping = set()
github serge-sans-paille / pythran / pythran / optimizations / pattern_transform.py View on Github external
def sub():
        return ast.Call(func=ast.Attribute(
            ast.Attribute(
                ast.Name('__builtin__', ast.Load(), None, None),
                'str',
                ast.Load()),
            'join', ast.Load()),
            args=[ast.Constant(Placeholder(1), None),
                  ast.Tuple([Placeholder(0), Placeholder(2)], ast.Load())],
            keywords=[])


know_pattern = [x for x in globals().values() if hasattr(x, "pattern")]


class PlaceholderReplace(Transformation):

    """ Helper class to replace the placeholder once value is collected. """

    def __init__(self, placeholders):
        """ Store placeholders value collected. """
        self.placeholders = placeholders
        super(PlaceholderReplace, self).__init__()

    def visit(self, node):
        """ Replace the placeholder if it is one or continue. """
        if isinstance(node, Placeholder):
            return self.placeholders[node.id]
        else:
            return super(PlaceholderReplace, self).visit(node)
github serge-sans-paille / pythran / pythran / optimizations / constant_folding.py View on Github external
dummy_module = ast.Module([s for s in node.body
                                   if not isinstance(s, ast.Import)],
                                  [])
        eval(compile(ast.gast_to_ast(dummy_module),
                     '', 'exec'),
             self.env)

        super(ConstantFolding, self).prepare(node)

    def skip(self, node):
        return node

    visit_Constant = visit_Name = skip

    visit_List = visit_Set = Transformation.generic_visit
    visit_Dict = visit_Tuple = Transformation.generic_visit

    def visit_Index(self, node):
        value = self.visit(node.value)
        if value is not node.value:
            return ast.Index(value)
        else:
            return node

    def generic_visit(self, node):
        if isinstance(node, ast.expr) and node in self.constant_expressions:
            fake_node = ast.Expression(node)
            code = compile(ast.gast_to_ast(fake_node),
                           '', 'eval')
            try:
                value = eval(code, self.env)
                new_node = to_ast(value)
github serge-sans-paille / pythran / pythran / analyses / lazyness_analysis.py View on Github external
md.visit(self, node)
        # augassigned variable can't be lazy
        self.visit(node.value)
        if isinstance(node.target, ast.Name):
            # variable is modified so other variables that use it dies
            self.modify(node.target.id)
            # and this variable can't be lazy
            self.result[node.target.id] = LazynessAnalysis.INF
        elif isinstance(node.target, ast.Subscript) or isattr(node.target):
            var_name = get_variable(node.target)
            # variable is modified so other variables that use it dies
            self.modify(var_name.id)
            # and this variable can't be lazy
            self.result[var_name.id] = LazynessAnalysis.INF
        else:
            raise PythranSyntaxError("AugAssign to unknown node", node)
github serge-sans-paille / pythran / pythran / run.py View on Github external
pyonly=args.optimize_only,
                                        **compile_flags(args))

    except IOError as e:
        logger.critical("I've got a bad feeling about this...\n"
                        "E: " + str(e))
        sys.exit(1)
    except ValueError as e:
        logger.critical("Chair to keyboard interface error\n"
                        "E: " + str(e))
        sys.exit(1)
    except pythran.types.tog.PythranTypeError as e:
        logger.critical("You shall not pass!\n"
                        "E: " + str(e))
        sys.exit(1)
    except pythran.syntax.PythranSyntaxError as e:
        logger.critical("I am in trouble. Your input file does not seem "
                        "to match Pythran's constraints...\n"
                        "E: " + str(e))
        sys.exit(1)
    except CompileError as e:
        logger.critical("Cover me Jack. Jack? Jaaaaack!!!!\n"
                        "E: " + str(e))
        sys.exit(1)
    except NotImplementedError:
        logger.critical("MAYDAY, MAYDAY, MAYDAY; pythran compiler; "
                        "code area out of control\n"
                        "E: not implemented feature needed, "
                        "bash the developers")
        raise  # Why ? we may instead display the stacktrace and exit?
    except EnvironmentError as e:
        logger.critical("By Jove! Your environment does not seem "
github serge-sans-paille / pythran / pythran / syntax.py View on Github external
def visit_Print(self, node):
        self.generic_visit(node)
        if node.dest:
            raise PythranSyntaxError(
                "Printing to a specific stream not supported", node.dest)
github serge-sans-paille / pythran / pythran / toolchain.py View on Github external
arguments_names = HasArgument(function_name).visit(ir)
            arguments = [n for n, _ in
                         zip(arguments_names, arguments_types)]
            name_fmt = pythran_ward + "{0}::{1}::type{2}"
            args_list = ", ".join(arguments_types)
            specialized_fname = name_fmt.format(module_name,
                                                internal_func_name,
                                                "<{0}>".format(args_list)
                                                if arguments_names else "")
            result_type = "typename %s::result_type" % specialized_fname
            docstring = spec_to_string(function_name, signature)
            mod.add_capsule(
                FunctionBody(
                    FunctionDeclaration(
                        Value(result_type, function_name),
                        [Value(t, a)
                         for t, a in zip(arguments_types, arguments)]),
                    Block([ReturnStatement("{0}()({1})".format(
                        warded(module_name, internal_func_name),
                        ', '.join(arguments)))])
                ),
                function_name,
                docstring
            )

    return mod, error_checker
github serge-sans-paille / pythran / pythran / toolchain.py View on Github external
sigid)
                arguments_types = [pytype_to_ctype(t) for t in signature]
                arguments_names = HasArgument(function_name).visit(ir)
                arguments = [n for n, _ in
                             zip(arguments_names, arguments_types)]
                name_fmt = pythran_ward + "{0}::{1}::type{2}"
                args_list = ", ".join(arguments_types)
                specialized_fname = name_fmt.format(module_name,
                                                    internal_func_name,
                                                    "<{0}>".format(args_list)
                                                    if arguments_names else "")
                result_type = "typename %s::result_type" % specialized_fname
                mod.add_pyfunction(
                    FunctionBody(
                        FunctionDeclaration(
                            Value(
                                result_type,
                                numbered_function_name),
                            [Value(t + '&&', a)
                             for t, a in zip(arguments_types, arguments)]),
                        Block([Statement("""
                            PyThreadState *_save = PyEval_SaveThread();
                            try {{
                                auto res = {0}()({1});
                                PyEval_RestoreThread(_save);
                                return res;
                            }}
                            catch(...) {{
                                PyEval_RestoreThread(_save);
                                throw;
                            }}
                            """.format(warded(module_name,
github serge-sans-paille / pythran / pythran / toolchain.py View on Github external
arguments_types = [pytype_to_ctype(t) for t in signature]
            arguments_names = HasArgument(function_name).visit(ir)
            arguments = [n for n, _ in
                         zip(arguments_names, arguments_types)]
            name_fmt = pythran_ward + "{0}::{1}::type{2}"
            args_list = ", ".join(arguments_types)
            specialized_fname = name_fmt.format(module_name,
                                                internal_func_name,
                                                "<{0}>".format(args_list)
                                                if arguments_names else "")
            result_type = "typename %s::result_type" % specialized_fname
            docstring = spec_to_string(function_name, signature)
            mod.add_capsule(
                FunctionBody(
                    FunctionDeclaration(
                        Value(result_type, function_name),
                        [Value(t, a)
                         for t, a in zip(arguments_types, arguments)]),
                    Block([ReturnStatement("{0}()({1})".format(
                        warded(module_name, internal_func_name),
                        ', '.join(arguments)))])
                ),
                function_name,
                docstring
            )

    return mod, error_checker