How to use the gast.Constant function in gast

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 serge-sans-paille / pythran / pythran / optimizations / modindex.py View on Github external
range_ = alias
            else:
                break

        if range_ is None:
            return self.generic_visit(node)

        # everything is setup for the transformation!
        new_id = node.left.id + '_m'
        i = 0
        while new_id in self.identifiers:
            new_id = '{}_m{}'.format(node.left.id, i)
            i += 1

        rargs = range_.args.args
        lower = rargs[0] if len(rargs) > 1 else ast.Constant(0, None)
        header = ast.Assign([ast.Name(new_id, ast.Store(), None, None)],
                            ast.BinOp(
                                ast.BinOp(deepcopy(lower),
                                          ast.Sub(),
                                          ast.Constant(1, None)),
                                ast.Mod(),
                                deepcopy(node.right)))
        incr = ast.BinOp(ast.Name(new_id, ast.Load(), None, None),
                         ast.Add(),
                         ast.Constant(1, None))
        step = ast.Assign([ast.Name(new_id, ast.Store(), None, None)],
                          ast.IfExp(
                              ast.Compare(incr,
                                          [ast.Eq()], [deepcopy(node.right)]),
                              ast.Constant(0, None),
                              deepcopy(incr)))
github serge-sans-paille / pythran / pythran / optimizations / square.py View on Github external
import numpy as __pythran_import_numpy
    __pythran_import_numpy.square(a)
    >>> node = ast.parse('__pythran_import_numpy.power(a,2)')
    >>> pm = passmanager.PassManager("test")
    >>> _, node = pm.apply(Square, node)
    >>> print(pm.dump(backend.Python, node))
    import numpy as __pythran_import_numpy
    __pythran_import_numpy.square(a)
    """

    POW_PATTERN = ast.BinOp(AST_any(), ast.Pow(), ast.Constant(2, None))
    POWER_PATTERN = ast.Call(
        ast.Attribute(ast.Name(mangle('numpy'), ast.Load(), None, None),
                      'power',
                      ast.Load()),
        [AST_any(), ast.Constant(2, None)],
        [])

    def __init__(self):
        Transformation.__init__(self)

    def replace(self, value):
        self.update = self.need_import = True
        module_name = ast.Name(mangle('numpy'), ast.Load(), None, None)
        return ast.Call(ast.Attribute(module_name, 'square', ast.Load()),
                        [value], [])

    def visit_Module(self, node):
        self.need_import = False
        self.generic_visit(node)
        if self.need_import:
            import_alias = ast.alias(name='numpy', asname=mangle('numpy'))
github serge-sans-paille / pythran / pythran / optimizations / inline_builtins.py View on Github external
def make_array_index(self, base, size, index):
        if isinstance(base, ast.Constant):
            return ast.Constant(base.value, None)
        if size == 1:
            return deepcopy(base.elts[0])
        return base.elts[index]
github serge-sans-paille / pythran / pythran / transformations / normalize_is_none.py View on Github external
def is_none(expr):
    # py3
    if isinstance(expr, ast.Constant) and expr.value is None:
        return True

    # py2
    if not isinstance(expr, ast.Attribute):
        return False

    return expr.attr == "None"
github serge-sans-paille / pythran / pythran / optimizations / pattern_transform.py View on Github external
def sub():
        return ast.BinOp(left=Placeholder(0), op=ast.Pow(),
                         right=ast.Constant(2, None))
github serge-sans-paille / pythran / pythran / transformations / remove_named_arguments.py View on Github external
def handle_special_calls(func_alias, node):
    if func_alias is MODULES['numpy']['arange']:
        if len(node.args) == 1:
            node.args.insert(0, ast.Constant(0, None))
github serge-sans-paille / pythran / pythran / optimizations / constant_folding.py View on Github external
if not isinstance(node.value, ast.Subscript):
            return node
        if not isinstance(node.value.slice, ast.Slice):
            return node
        if not isinstance(node.slice, ast.Index):
            return node

        if not isnum(node.slice.value):
            return node

        slice_ = node.value.slice
        index = node.slice
        node = node.value

        node.slice = index
        lower = slice_.lower or ast.Constant(0, None)
        step = slice_.step or ast.Constant(1, None)
        node.slice.value = ast.BinOp(lower,
                                     ast.Add(),
                                     ast.BinOp(index.value,
                                               ast.Mult(),
                                               step))
        self.update = True
        return node
github serge-sans-paille / pythran / pythran / optimizations / pattern_transform.py View on Github external
    @staticmethod
    def sub():
        return ast.Call(
            func=ast.Attribute(value=ast.Name(id=mangle('numpy'),
                                              ctx=ast.Load(),
                                              annotation=None,
                                              type_comment=None),
                               attr="sqrt", ctx=ast.Load()),
            args=[Placeholder(0)], keywords=[])

    extra_imports = [ast.Import([ast.alias('numpy', mangle('numpy'))])]


class CbrtPattern(Pattern):
    # X ** .33333 => numpy.cbrt(X)
    pattern = ast.BinOp(Placeholder(0), ast.Pow(), ast.Constant(1./3., None))

    @staticmethod
    def sub():
        return ast.Call(
            func=ast.Attribute(value=ast.Name(id=mangle('numpy'),
                                              ctx=ast.Load(),
                                              annotation=None,
                                              type_comment=None),
                               attr="cbrt", ctx=ast.Load()),
            args=[Placeholder(0)], keywords=[])

    extra_imports = [ast.Import([ast.alias('numpy', mangle('numpy'))])]


class TuplePattern(Pattern):
    # __builtin__.tuple([X, ..., Z]) => (X, ..., Z)
github serge-sans-paille / pythran / pythran / transformations / normalize_tuples.py View on Github external
lambda x, y: ast.Subscript(
                                x,
                                ast.Index(ast.Constant(y, None)),
                                ast.Load()),
                            state,
github pfnet-research / chainer-compiler / chainer_compiler / ch2o / chainer2onnx.py View on Github external
return None

    elif isinstance(nast, gast.Name):
        try:
            return env.get_var(nast.id)
        except NameError as ne:
            if nast.id in dir(env.module):
                return getattr(env.module, nast.id)
            elif nast.id in dir(builtins):
                return getattr(builtins, nast.id)
            raise
    elif isinstance(nast, gast.Constant):
        return nast.value
    elif isinstance(nast, gast.Expr):
        return eval_ast(nast.value, env)
    elif isinstance(nast, gast.Constant) and isinstance(nast.value, str):
        return nast.value
    elif isinstance(nast, gast.Tuple):
        return tuple(map(lambda x: eval_ast(x, env), nast.elts))
    elif isinstance(nast, gast.List):
        return eval_list(nast, env)

    elif isinstance(nast, gast.Return):
        raise ValueReturn(eval_ast(nast.value, env))

    elif isinstance(nast, gast.Assert):
        # TODO(hamaji): Emit an assertion?
        return None

    # TODO(hamaji): Implement `with`.
    # elif isinstance(nast, gast.With):
    #     sys.stderr.write(

gast

Python AST that abstracts the underlying Python version

BSD-3-Clause
Latest version published 4 months ago

Package Health Score

78 / 100
Full package analysis