Python ast.Pow() Examples

The following are 16 code examples of ast.Pow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: helper.py    From YAPyPy with MIT License 6 votes vote down vote up
def augassign_rewrite(it: Tokenizer):
    return {
        '+=': ast.Add,
        '-=': ast.Sub,
        '*=': ast.Mult,
        '/=': ast.Div,
        '//=': ast.FloorDiv,
        '@=': ast.MatMult,
        '%=': ast.Mod,
        '&=': ast.BitAnd,
        '|=': ast.BitOr,
        '^=': ast.BitXor,
        '<<=': ast.LShift,
        '>>=': ast.RShift,
        '**=': ast.Pow,
    }[it.value] 
Example #2
Source File: test_transformers.py    From mutatest with MIT License 5 votes vote down vote up
def test_MutateAST_visit_binop_37(binop_file):
    """Read only test to ensure locations are aggregated."""
    tree = Genome(binop_file).ast

    # Py 3.7 vs. Py 3.8
    end_lineno = None if sys.version_info < (3, 8) else 6
    end_col_offset = None if sys.version_info < (3, 8) else 17

    test_idx = LocIndex(
        ast_class="BinOp",
        lineno=6,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    test_mutation = ast.Pow

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=test_idx, mutation=test_mutation).visit(testing_tree)

    # revisit in read-only mode to gather the locations of the new nodes
    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    # four locations from the binary operations in binop_file
    assert len(mast.locs) == 4

    # locs is an unordered set, cycle through to thd target and check the mutation
    for loc in mast.locs:
        if (
            loc.lineno == 6
            and loc.col_offset == 11
            and loc.end_lineno == end_lineno
            and loc.end_col_offset == end_col_offset
        ):
            assert loc.op_type == test_mutation 
Example #3
Source File: FileFormat.py    From qiew with GNU General Public License v2.0 5 votes vote down vote up
def onReturnPressed(self):

        expr = str(self.ui.lineEdit.text())


        import ast
        import operator as op
        # supported operators
        operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
                     ast.Div: op.floordiv, ast.Pow: op.pow, ast.USub: op.neg}

        def eval_expr(expr):
            return eval_(ast.parse(expr, mode='eval').body)

        def eval_(node):
            if isinstance(node, ast.Num):
                return node.n
            elif isinstance(node, ast.BinOp):
                return operators[type(node.op)](eval_(node.left), eval_(node.right))
            elif isinstance(node, ast.UnaryOp):
                return operators[type(node.op)](eval_(node.operand))
            elif isinstance(node, object):
                # handle constants
                k = str(node.id).upper()
                if k in self.konstants:
                    return self.konstants[k](k)
                else:
                    raise TypeError(node)
            else:
                raise TypeError(node)

        try:
            result = eval_expr(expr)
        except Exception as e:
            self.ui.label.setText('error.')
            return
        

        self.ui.label.setText('{0} ({1})'.format(hex(result), result))

        self.onResult(result) 
Example #4
Source File: core.py    From ibis with Apache License 2.0 5 votes vote down vote up
def visit_Pow(self, node):
        assert False, 'should never reach Pow' 
Example #5
Source File: core.py    From ibis with Apache License 2.0 5 votes vote down vote up
def visit_BinOp(self, node):
        left, op, right = node.left, node.op, node.right

        if isinstance(op, ast.Pow):
            return 'Math.pow({}, {})'.format(
                self.visit(left), self.visit(right)
            )
        elif isinstance(op, ast.FloorDiv):
            return 'Math.floor({} / {})'.format(
                self.visit(left), self.visit(right)
            )
        return '({} {} {})'.format(
            self.visit(left), self.visit(op), self.visit(right)
        ) 
Example #6
Source File: BehavioralRTLIRGenL2Pass.py    From pymtl3 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__( s, component ):
    super().__init__( component )
    s.loop_var_env = set()
    s.tmp_var_env = set()

    # opmap maps an ast operator to its RTLIR counterpart.
    s.opmap = {
      # Bool operators
      # Note: we do not support boolean operators because Python does
      # not allow overloading And and Or operators. Using them in
      # expressions might lead to inconsistent semantics.
      # ast.And    : bir.And(),       ast.Or     : bir.Or(),
      # Unary operators
      # Note: ast.Not is disallowed because it is a boolean operator
      # ast.Not    : bir.Not(),
      ast.Invert : bir.Invert(),
      ast.UAdd   : bir.UAdd(),      ast.USub   : bir.USub(),
      # Binary operators
      ast.Add    : bir.Add(),       ast.Sub    : bir.Sub(),
      ast.Mult   : bir.Mult(),      ast.Div    : bir.Div(),
      ast.Mod    : bir.Mod(),       ast.Pow    : bir.Pow(),
      ast.LShift : bir.ShiftLeft(), ast.RShift : bir.ShiftRightLogic(),
      ast.BitOr  : bir.BitOr(),     ast.BitAnd : bir.BitAnd(),
      ast.BitXor : bir.BitXor(),
      # Compare bir.bir.operators
      ast.Eq     : bir.Eq(),        ast.NotEq  : bir.NotEq(),
      ast.Lt     : bir.Lt(),        ast.LtE    : bir.LtE(),
      ast.Gt     : bir.Gt(),        ast.GtE    : bir.GtE()
    }

  # Override 
Example #7
Source File: _recompute.py    From icontract with MIT License 5 votes vote down vote up
def visit_BinOp(self, node: ast.BinOp) -> Any:
        """Recursively visit the left and right operand, respectively, and apply the operation on the results."""
        # pylint: disable=too-many-branches
        left = self.visit(node=node.left)
        right = self.visit(node=node.right)

        if isinstance(node.op, ast.Add):
            result = left + right
        elif isinstance(node.op, ast.Sub):
            result = left - right
        elif isinstance(node.op, ast.Mult):
            result = left * right
        elif isinstance(node.op, ast.Div):
            result = left / right
        elif isinstance(node.op, ast.FloorDiv):
            result = left // right
        elif isinstance(node.op, ast.Mod):
            result = left % right
        elif isinstance(node.op, ast.Pow):
            result = left**right
        elif isinstance(node.op, ast.LShift):
            result = left << right
        elif isinstance(node.op, ast.RShift):
            result = left >> right
        elif isinstance(node.op, ast.BitOr):
            result = left | right
        elif isinstance(node.op, ast.BitXor):
            result = left ^ right
        elif isinstance(node.op, ast.BitAnd):
            result = left & right
        elif isinstance(node.op, ast.MatMult):
            result = left @ right
        else:
            raise NotImplementedError("Unhandled op of {}: {}".format(node, node.op))

        self.recomputed_values[node] = result
        return result 
Example #8
Source File: parser.py    From vecpy with MIT License 5 votes vote down vote up
def binop(self, block, node, var=None):
    if var is None:
      var = self.add_variable(None)
    left = self.expression(block, node.left)
    right = self.expression(block, node.right)
    if isinstance(node.op, ast.Add):
      op = Operator.add
    elif isinstance(node.op, ast.Sub):
      op = Operator.subtract
    elif isinstance(node.op, ast.Mult):
      op = Operator.multiply
    elif isinstance(node.op, ast.Div):
      op = Operator.divide
    elif isinstance(node.op, ast.FloorDiv):
      op = Operator.divide_int
    elif isinstance(node.op, ast.Mod):
      op = Operator.mod
    elif isinstance(node.op, ast.Pow):
      op = Operator.pow
    elif isinstance(node.op, ast.BitAnd):
      op = Operator.bit_and
    elif isinstance(node.op, ast.BitOr):
      op = Operator.bit_or
    elif isinstance(node.op, ast.BitXor):
      op = Operator.bit_xor
    elif isinstance(node.op, ast.LShift):
      op = Operator.shift_left
    elif isinstance(node.op, ast.RShift):
      op = Operator.shift_right
    else:
      raise Exception('Unexpected BinOp (%s)'%(node.op.__class__))
    operation = BinaryOperation(left, op, right)
    assignment = Assignment(var, operation)
    block.add(assignment)
    return var

  #Parses a unary uperation (AST UnaryOp) 
Example #9
Source File: executing.py    From executing with MIT License 5 votes vote down vote up
def matching_nodes(self, exprs):
        for i, expr in enumerate(exprs):
            setter = get_setter(expr)
            replacement = ast.BinOp(
                left=expr,
                op=ast.Pow(),
                right=ast.Str(s=sentinel),
            )
            ast.fix_missing_locations(replacement)
            setter(replacement)
            try:
                instructions = self.compile_instructions()
            except SyntaxError:
                continue
            finally:
                setter(expr)
            indices = [
                i
                for i, instruction in enumerate(instructions)
                if instruction.argval == sentinel
            ]
            if not indices:
                continue
            arg_index = only(indices) - 1
            while instructions[arg_index].opname == 'EXTENDED_ARG':
                arg_index -= 1

            if instructions[arg_index].offset == self.frame.f_lasti:
                yield expr 
Example #10
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_augassign_11(p):
    '''augassign : DOUBLESTAREQUAL'''
    #                            1
    p[0] = ast.Pow(rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #11
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_power_2(p):
    '''power : atom DOUBLESTAR factor'''
    #             1          2      3
    p[0] = ast.BinOp(p[1], ast.Pow(rule=inspect.currentframe().f_code.co_name, **p[2][1]), p[3], rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(p[0], p[1]) 
Example #12
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_power_4(p):
    '''power : atom power_star DOUBLESTAR factor'''
    #             1          2          3      4
    p[0] = ast.BinOp(unpack_trailer(p[1], p[2]), ast.Pow(rule=inspect.currentframe().f_code.co_name, **p[3][1]), p[4], rule=inspect.currentframe().f_code.co_name)
    inherit_lineno(p[0], p[1]) 
Example #13
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def pow_operator(d: ast.Pow):
    return "**" 
Example #14
Source File: clike.py    From pyrs with MIT License 5 votes vote down vote up
def visit_BinOp(self, node):
        if isinstance(node.op, ast.Pow):
            return "{0}.pow({1})".format(self.visit(node.left),
                                               self.visit(node.right))

        return " ".join([self.visit(node.left),
                         self.visit(node.op),
                         self.visit(node.right)]) 
Example #15
Source File: gtoken.py    From py-googletrans with MIT License 4 votes vote down vote up
def _update(self):
        """update tkk
        """
        # we don't need to update the base TKK value when it is still valid
        now = math.floor(int(time.time() * 1000) / 3600000.0)
        if self.tkk and int(self.tkk.split('.')[0]) == now:
            return

        r = self.client.get(self.host)

        raw_tkk = self.RE_TKK.search(r.text)
        if raw_tkk:
            self.tkk = raw_tkk.group(1)
            return

        # this will be the same as python code after stripping out a reserved word 'var'
        code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
        # unescape special ascii characters such like a \x3d(=)
        code = code.encode().decode('unicode-escape')

        if code:
            tree = ast.parse(code)
            visit_return = False
            operator = '+'
            n, keys = 0, dict(a=0, b=0)
            for node in ast.walk(tree):
                if isinstance(node, ast.Assign):
                    name = node.targets[0].id
                    if name in keys:
                        if isinstance(node.value, ast.Num):
                            keys[name] = node.value.n
                        # the value can sometimes be negative
                        elif isinstance(node.value, ast.UnaryOp) and \
                                isinstance(node.value.op, ast.USub):  # pragma: nocover
                            keys[name] = -node.value.operand.n
                elif isinstance(node, ast.Return):
                    # parameters should be set after this point
                    visit_return = True
                elif visit_return and isinstance(node, ast.Num):
                    n = node.n
                elif visit_return and n > 0:
                    # the default operator is '+' but implement some more for
                    # all possible scenarios
                    if isinstance(node, ast.Add):  # pragma: nocover
                        pass
                    elif isinstance(node, ast.Sub):  # pragma: nocover
                        operator = '-'
                    elif isinstance(node, ast.Mult):  # pragma: nocover
                        operator = '*'
                    elif isinstance(node, ast.Pow):  # pragma: nocover
                        operator = '**'
                    elif isinstance(node, ast.BitXor):  # pragma: nocover
                        operator = '^'
            # a safety way to avoid Exceptions
            clause = compile('{1}{0}{2}'.format(
                operator, keys['a'], keys['b']), '', 'eval')
            value = eval(clause, dict(__builtin__={}))
            result = '{}.{}'.format(n, value)

            self.tkk = result 
Example #16
Source File: compiler.py    From Transcrypt with Apache License 2.0 4 votes vote down vote up
def visit_BinOp (self, node):
        if type (node.op) == ast.FloorDiv:
            if self.allowOperatorOverloading:
                self.emit ('__floordiv__ (')
                self.visitSubExpr (node, node.left)
                self.emit (', ')
                self.visitSubExpr (node, node.right)
                self.emit (')')
            else:
                self.emit ('Math.floor (')
                self.visitSubExpr (node, node.left)
                self.emit (' / ')
                self.visitSubExpr (node, node.right)
                self.emit (')')
        elif (
            type (node.op) in (ast.Pow, ast.MatMult) or
            (type (node.op) == ast.Mod and (self.allowOperatorOverloading or not self.allowJavaScriptMod)) or
            (type (node.op) in (
                ast.Mult, ast.Div, ast.Add, ast.Sub,
                ast.LShift, ast.RShift, ast.BitOr, ast.BitXor, ast.BitAnd
            ) and self.allowOperatorOverloading)
        ):
            self.emit ('{} ('.format (self.filterId (
                # Non-overloaded
                ('__floordiv__' if self.allowOperatorOverloading else 'Math.floor') if type (node.op) == ast.FloorDiv else
                ('__pow__' if self.allowOperatorOverloading else 'Math.pow') if type (node.op) == ast.Pow else
                '__matmul__' if type (node.op) == ast.MatMult else
                ('__jsmod__' if self.allowJavaScriptMod else '__mod__') if type (node.op) == ast.Mod else

                # Overloaded arithmetic
                '__mul__' if type (node.op) == ast.Mult else
                '__truediv__' if type (node.op) == ast.Div else
                '__add__' if type (node.op) == ast.Add else
                '__sub__' if type (node.op) == ast.Sub else

                # Overloaded bitwise
                '__lshift__' if type (node.op) == ast.LShift else
                '__rshift__' if type (node.op) == ast.RShift else
                '__or__' if type (node.op) == ast.BitOr else
                '__xor__' if type (node.op) == ast.BitXor else
                '__and__' if type (node.op) == ast.BitAnd else

                'Never here'
            )))
            self.visit (node.left)
            self.emit (', ')
            self.visit (node.right)
            self.emit (')')
        else:
            self.visitSubExpr (node, node.left)
            self.emit (' {} '.format (self.operators [type (node.op)][0]))
            self.visitSubExpr (node, node.right)