Python ast.Div() Examples

The following are 21 code examples of ast.Div(). 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: test_transformers.py    From mutatest with MIT License 6 votes vote down vote up
def test_MutateAST_visit_augassign(augassign_file, augassign_expected_locs):
    """Test mutation for AugAssign: +=, -=, /=, *=."""
    tree = Genome(augassign_file).ast
    test_mutation = "AugAssign_Div"

    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=augassign_expected_locs[0], mutation=test_mutation).visit(
        testing_tree
    )

    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    assert len(mast.locs) == 4

    for loc in mast.locs:
        # spot check on mutation from Add tp Div
        if loc.lineno == 1 and loc.col_offset == 4:
            assert loc.op_type == test_mutation

        # spot check on not-mutated location still being Mult
        if loc.lineno == 5 and loc.col_offset == 4:
            assert loc.op_type == "AugAssign_Mult" 
Example #2
Source File: helper.py    From YAPyPy with MIT License 6 votes vote down vote up
def term_rewrite(head, tail):
    if tail:
        for op, each in tail:
            head = ast.BinOp(
                head,
                {
                    '*': ast.Mult,
                    '@': ast.MatMult,
                    '%': ast.Mod,
                    '//': ast.FloorDiv,
                    '/': ast.Div
                }[op.value](),
                each,
                **loc @ op,
            )
    return head 
Example #3
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 #4
Source File: exceptions.py    From deal with MIT License 6 votes vote down vote up
def handle_bin_op(expr, **kwargs) -> Optional[Token]:
    token_info = dict(line=expr.lineno, col=expr.col_offset)
    if isinstance(expr.op, ast.Div) or expr.op == '/':
        if isinstance(expr.right, astroid.node_classes.NodeNG):
            guesses = infer(expr=expr.right)
            token_info['col'] = expr.right.col_offset
            for guess in guesses:
                if type(guess) is not astroid.Const:
                    continue
                return Token(value=ZeroDivisionError, **token_info)
        if isinstance(expr.right, ast.Num) and expr.right.n == 0:
            token_info['col'] = expr.right.col_offset
            return Token(value=ZeroDivisionError, **token_info)
    return None


# exit() 
Example #5
Source File: test_api.py    From mutatest with MIT License 5 votes vote down vote up
def test_mutate_TypeError_source_file(mock_LocIdx):
    """Mutate with a NoneType source_file property raises a TypeError."""
    genome = Genome()
    with pytest.raises(TypeError):
        _ = genome.mutate(target_idx=mock_LocIdx, mutation_op=ast.Div, write_cache=False) 
Example #6
Source File: onelinerizer.py    From onelinerizer with MIT License 5 votes vote down vote up
def visit_BinOp(self, tree):
        if 'division' in self.futures and isinstance(tree.op, ast.Div):
            return T('{__operator}.truediv({}, {})').format(self.visit(tree.left), self.visit(tree.right))
        return T('({} {} {})').format(self.visit(tree.left), operator_code[type(tree.op)], self.visit(tree.right)) 
Example #7
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def div_operator(d: ast.Div):
    return "/" 
Example #8
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_term_star_6(p):
    '''term_star : term_star SLASH factor'''
    #                      1     2      3
    p[0] = p[1] + [ast.Div(rule=inspect.currentframe().f_code.co_name, **p[2][1]), p[3]] 
Example #9
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_term_star_2(p):
    '''term_star : SLASH factor'''
    #                  1      2
    p[0] = [ast.Div(rule=inspect.currentframe().f_code.co_name, **p[1][1]), p[2]] 
Example #10
Source File: hgawk_grammar.py    From histogrammar-python with Apache License 2.0 5 votes vote down vote up
def p_augassign_4(p):
    '''augassign : SLASHEQUAL'''
    #                       1
    p[0] = ast.Div(rule=inspect.currentframe().f_code.co_name, **p[1][1]) 
Example #11
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 #12
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 #13
Source File: expressions.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def stringify_operation(op: Any) -> str:
        if isinstance(op, ast.Add):
            return '+'
        if isinstance(op, ast.Sub):
            return '-'
        if isinstance(op, ast.Mult):
            return '*'
        if isinstance(op, ast.Div) or isinstance(op, ast.FloorDiv):
            return '/'
        return str(op) 
Example #14
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 #15
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 #16
Source File: _analyze.py    From myhdl with GNU Lesser General Public License v2.1 5 votes vote down vote up
def visit_BinOp(self, node):
        if isinstance(node.op, ast.Div):
            self.raiseError(node, _error.NotSupported, "true division - consider '//'") 
Example #17
Source File: test_api.py    From mutatest with MIT License 5 votes vote down vote up
def test_mutate_ValueError_target(binop_file, mock_LocIdx):
    """Mutate with a target_idx not in the targets raises a ValueError."""
    genome = Genome(binop_file)
    with pytest.raises(ValueError):
        _ = genome.mutate(target_idx=mock_LocIdx, mutation_op=ast.Div, write_cache=False) 
Example #18
Source File: conftest.py    From mutatest with MIT License 4 votes vote down vote up
def binop_expected_locs():
    """Expected target locations for the binop_file fixture in Python 3.7."""
    # Python 3.7
    if sys.version_info < (3, 8):
        return {
            LocIndex(ast_class="BinOp", lineno=6, col_offset=11, op_type=ast.Add),
            LocIndex(ast_class="BinOp", lineno=6, col_offset=18, op_type=ast.Sub),
            LocIndex(ast_class="BinOp", lineno=10, col_offset=11, op_type=ast.Add),
            LocIndex(ast_class="BinOp", lineno=15, col_offset=11, op_type=ast.Div),
        }

    # Python 3.8
    return {
        LocIndex(
            ast_class="BinOp",
            lineno=15,
            col_offset=11,
            op_type=ast.Div,
            end_lineno=15,
            end_col_offset=16,
        ),
        LocIndex(
            ast_class="BinOp",
            lineno=6,
            col_offset=11,
            op_type=ast.Add,
            end_lineno=6,
            end_col_offset=17,
        ),
        LocIndex(
            ast_class="BinOp",
            lineno=10,
            col_offset=11,
            op_type=ast.Add,
            end_lineno=10,
            end_col_offset=16,
        ),
        LocIndex(
            ast_class="BinOp",
            lineno=6,
            col_offset=11,
            op_type=ast.Sub,
            end_lineno=6,
            end_col_offset=21,
        ),
    } 
Example #19
Source File: onelinerizer.py    From onelinerizer with MIT License 4 votes vote down vote up
def visit_AugAssign(self, tree):
        if type(tree.target) is ast.Attribute:
            target_params = ['__target']
            target_args = [self.visit(tree.target.value)]
            target_value = T('__target.{}').format(tree.target.attr)
        elif type(tree.target) is ast.Subscript:
            if type(tree.target.slice) is ast.Slice and tree.target.slice.step is None:
                target_params = ['__target']
                target_args = [self.visit(tree.target.value)]
                if tree.target.slice.lower is not None:
                    target_params.append('__lower')
                    target_args.append(self.visit(tree.target.slice.lower))
                if tree.target.slice.upper is not None:
                    target_params.append('__upper')
                    target_args.append(self.visit(tree.target.slice.upper))
                target_value = T('__target[{}:{}]').format(
                    '' if tree.target.slice.lower is None else '__lower',
                    '' if tree.target.slice.upper is None else '__upper')
            else:
                target_params = ['__target', '__slice']
                target_args = [self.visit(tree.target.value), self.slice_repr(tree.target.slice)]
                target_value = '__target[__slice]'
        elif type(tree.target) is ast.Name:
            target_params = []
            target_args = []
            target_value = self.store_var(tree.target.id)
        else:
            raise SyntaxError('illegal expression for augmented assignment')

        iop = type(tree.op).__name__.lower()
        if iop.startswith('bit'):
            iop = iop[len('bit'):]
        if 'division' in self.futures and isinstance(tree.op, ast.Div):
            iop = 'truediv'
        value = self.visit(tree.value)
        assign = assignment_component(
            T('{after}'), target_value,
            T("{__operator}.i{}({}, {})").format(iop, target_value, value))
        if target_params:
            assign = T('(lambda {}: {})({})').format(
                T(', ').join(target_params),
                assign,
                T(', ').join(target_args))
        return assign 
Example #20
Source File: transformers.py    From mutatest with MIT License 4 votes vote down vote up
def visit_AugAssign(self, node: ast.AugAssign) -> ast.AST:
        """AugAssign is ``-=, +=, /=, *=`` for augmented assignment."""
        self.generic_visit(node)
        log_header = f"visit_AugAssign: {self.src_file}:"

        # custom mapping of string keys to ast operations that can be used
        # in the nodes since these overlap with BinOp types
        aug_mappings = {
            "AugAssign_Add": ast.Add,
            "AugAssign_Sub": ast.Sub,
            "AugAssign_Mult": ast.Mult,
            "AugAssign_Div": ast.Div,
        }

        rev_mappings = {v: k for k, v in aug_mappings.items()}
        idx_op = rev_mappings.get(type(node.op), None)

        # edge case protection in case the mapping isn't known for substitution
        # in that instance, return the node and take no action
        if not idx_op:
            LOGGER.debug(
                "%s (%s, %s): unknown aug_assignment: %s",
                log_header,
                node.lineno,
                node.col_offset,
                type(node.op),
            )
            return node

        node_span = NodeSpan(node)
        idx = LocIndex(
            ast_class="AugAssign",
            lineno=node_span.lineno,
            col_offset=node_span.col_offset,
            op_type=idx_op,
            end_lineno=node_span.end_lineno,
            end_col_offset=node_span.end_col_offset,
        )

        self.locs.add(idx)

        if idx == self.target_idx and self.mutation in aug_mappings and not self.readonly:
            LOGGER.debug("%s mutating idx: %s with %s", log_header, self.target_idx, self.mutation)
            return ast.copy_location(
                ast.AugAssign(
                    target=node.target,
                    op=aug_mappings[self.mutation](),  # awkward syntax to call type from mapping
                    value=node.value,
                ),
                node,
            )

        LOGGER.debug("%s (%s, %s): no mutations applied.", log_header, node.lineno, node.col_offset)
        return node 
Example #21
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)