# 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.

serge-sans-paille / pythran / pythran / range.py View on Github
``````Combiner for Floor divide operation.

&gt;&gt;&gt; import gast as ast
&gt;&gt;&gt; combine(Range(-1, 5), Range(3, 8), ast.FloorDiv())
Range(low=-1, high=1)
&gt;&gt;&gt; combine(Range(-1, 5), Range(-5, -4), ast.FloorDiv())
Range(low=-2, high=0)
&gt;&gt;&gt; combine(Range(-1, 5), Range(-5, 3), ast.FloorDiv())
Range(low=-inf, high=inf)
"""
if range2.low &lt;= 0 and range2.high &gt;= 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))
``````
serge-sans-paille / pythran / pythran / transformations / normalize_static_if.py View on Github
``````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()``````
serge-sans-paille / pythran / pythran / optimizations / pattern_transform.py View on Github
``````def sub():
return ast.Call(func=ast.Attribute(
ast.Attribute(
'str',
args=[ast.Constant(Placeholder(1), None),
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)``````
serge-sans-paille / pythran / pythran / optimizations / constant_folding.py View on Github
``````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)``````
serge-sans-paille / pythran / pythran / analyses / lazyness_analysis.py View on Github
``````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)``````
serge-sans-paille / pythran / pythran / run.py View on Github
``````pyonly=args.optimize_only,
**compile_flags(args))

except IOError as e:
"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 "``````
serge-sans-paille / pythran / pythran / syntax.py View on Github
``````def visit_Print(self, node):
self.generic_visit(node)
if node.dest:
raise PythranSyntaxError(
"Printing to a specific stream not supported", node.dest)``````
serge-sans-paille / pythran / pythran / toolchain.py View on Github
``````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,
"&lt;{0}&gt;".format(args_list)
if arguments_names else "")
result_type = "typename %s::result_type" % specialized_fname
docstring = spec_to_string(function_name, signature)
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``````
serge-sans-paille / pythran / pythran / toolchain.py View on Github
``````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,
"&lt;{0}&gt;".format(args_list)
if arguments_names else "")
result_type = "typename %s::result_type" % specialized_fname
FunctionBody(
FunctionDeclaration(
Value(
result_type,
numbered_function_name),
[Value(t + '&amp;&amp;', a)
for t, a in zip(arguments_types, arguments)]),
Block([Statement("""
try {{
auto res = {0}()({1});
return res;
}}
catch(...) {{
throw;
}}
""".format(warded(module_name,``````
serge-sans-paille / pythran / pythran / toolchain.py View on Github
``````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,
"&lt;{0}&gt;".format(args_list)
if arguments_names else "")
result_type = "typename %s::result_type" % specialized_fname
docstring = spec_to_string(function_name, signature)
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``````

## pythran

Ahead of Time compiler for numeric kernels

BSD-3-Clause