Python ast 模块,Div() 实例源码

我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用ast.Div()

项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def num_negate(op):
    top = type(op)
    neg = not op.num_negated if hasattr(op, "num_negated") else True
    if top == ast.Add:
        newOp = ast.Sub()
    elif top == ast.Sub:
        newOp = ast.Add()
    elif top in [ast.Mult, ast.Div, ast.Mod, ast.Pow, ast.LShift, 
                 ast.RShift, ast.BitOr, ast.BitXor, ast.BitAnd, ast.FloorDiv]:
        return None # can't negate this
    elif top in [ast.Num, ast.Name]:
        # this is a normal value, so put a - in front of it
        newOp = ast.UnaryOp(ast.USub(addedNeg=True), op)
    else:
        log("astTools\tnum_negate\tUnusual type: " + str(top), "bug")
    transferMetaData(op, newOp)
    newOp.num_negated = neg
    return newOp
项目:py2rb    作者:naitoh    | 项目源码 | 文件源码
def visit_AugAssign(self, node):
        """
        AugAssign(expr target, operator op, expr value)
        """
        # TODO: Make sure that all the logic in Assign also works in AugAssign
        target = self.visit(node.target)
        value = self.visit(node.value)

        if isinstance(node.op, ast.Pow):
            self.write("%s = %s ** %s" % (target, target, value))
        #elif isinstance(node.op, ast.FloorDiv):
        #    #self.write("%s = Math.floor((%s)/(%s));" % (target, target, value))
        #    self.write("%s = (%s/%s)" % (target, target, value))
        elif isinstance(node.op, ast.Div):
            if re.search(r"Numo::", target) or re.search(r"Numo::", value):
                self.write("%s = (%s)/(%s)" % (target, target, value))
            else:
                self.write("%s = (%s)/(%s).to_f" % (target, target, value))
        else:
            self.write("%s %s= %s" % (target, self.get_binary_op(node), value))
项目:py2rb    作者:naitoh    | 项目源码 | 文件源码
def visit_BinOp(self, node):
        if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str):
            left = self.visit(node.left)
            # 'b=%(b)0d and c=%(c)d and d=%(d)d' => 'b=%<b>0d and c=%<c>d and d=%<d>d'
            left = re.sub(r"(.+?%)\((.+?)\)(.+?)", r"\1<\2>\3", left)
            self._dict_format = True
            right = self.visit(node.right)
            self._dict_format = False
            return "%s %% %s" % (left, right)
        left = self.visit(node.left)
        right = self.visit(node.right)

        if isinstance(node.op, ast.Pow):
            return "%s ** %s" % (left, right)
        if isinstance(node.op, ast.Div):
            if re.search(r"Numo::", left) or re.search(r"Numo::", right):
                return "(%s)/(%s)" % (left, right)
            else:
                return "(%s)/(%s).to_f" % (left, right)

        return "(%s)%s(%s)" % (left, self.get_binary_op(node), right)
项目:PYSL    作者:sparkon    | 项目源码 | 文件源码
def eval_numeric_constexpr(node: ast.AST) -> int:
    if isinstance(node, ast.Num):
        return node.n
    if isinstance(node, ast.UnaryOp):
        if isinstance(node.op, ast.UAdd):
            return +eval_numeric_constexpr(node.operand)
        elif isinstance(node.op, ast.USub):
            return -eval_numeric_constexpr(node.operand)
        else:
            return None
    if isinstance(node, ast.BinOp):
        if isinstance(node.op, ast.Add):
            return eval_numeric_constexpr(node.left) + eval_numeric_constexpr(node.right)
        if isinstance(node.op, ast.Sub):
            return eval_numeric_constexpr(node.left) - eval_numeric_constexpr(node.right)
        if isinstance(node.op, ast.Mult):
            return eval_numeric_constexpr(node.left) * eval_numeric_constexpr(node.right)
        if isinstance(node.op, ast.Div):
            return eval_numeric_constexpr(node.left) / eval_numeric_constexpr(node.right)
        return None
项目:PYSL    作者:sparkon    | 项目源码 | 文件源码
def binop_str(op: ast.AST) -> str:
    if isinstance(op, ast.Add):
        return '+'
    if isinstance(op, ast.Sub):
        return '-'
    if isinstance(op, ast.Mult):
        return '*'
    if isinstance(op, ast.Div):
        return '/ '
    if isinstance(op, ast.Mod):
        return '%'
    if isinstance(op, ast.LShift):
        return '<<'
    if isinstance(op, ast.RShift):
        return '>>'
    if isinstance(op, ast.BitOr):
        return '|'
    if isinstance(op, ast.BitXor):
        return '^'
    if isinstance(op, ast.BitAnd):
        return '&'
    if isinstance(op, ast.MatMult):
        return '@'
    error(loc(op), "Invalid binary operator encountered: {0}:{1}. Check supported intrinsics.".format(op.lineno, op.col_offset))
    return 'INVALID_BINOP'
项目:bubblesub    作者:rr-    | 项目源码 | 文件源码
def eval_expr(expr):
    import ast
    import operator as op

    op = {
        ast.Add: op.add,
        ast.Sub: op.sub,
        ast.Mult: op.mul,
        ast.Div: op.truediv,
        ast.Pow: op.pow,
        ast.BitXor: op.xor,
        ast.USub: op.neg,
    }

    def eval_(node):
        if isinstance(node, ast.Num):
            return fractions.Fraction(node.n)
        elif isinstance(node, ast.BinOp):
            return op[type(node.op)](eval_(node.left), eval_(node.right))
        elif isinstance(node, ast.UnaryOp):
            return op[type(node.op)](eval_(node.operand))
        raise TypeError(node)

    return eval_(ast.parse(str(expr), mode='eval').body)
项目:viper    作者:ethereum    | 项目源码 | 文件源码
def parse_unit(item):
    if isinstance(item, ast.Name):
        if item.id not in valid_units:
            raise InvalidTypeException("Invalid base unit", item)
        return {item.id: 1}
    elif isinstance(item, ast.Num) and item.n == 1:
        return {}
    elif not isinstance(item, ast.BinOp):
        raise InvalidTypeException("Invalid unit expression", item)
    elif isinstance(item.op, ast.Mult):
        left, right = parse_unit(item.left), parse_unit(item.right)
        return combine_units(left, right)
    elif isinstance(item.op, ast.Div):
        left, right = parse_unit(item.left), parse_unit(item.right)
        return combine_units(left, right, div=True)
    elif isinstance(item.op, ast.Pow):
        if not isinstance(item.left, ast.Name):
            raise InvalidTypeException("Can only raise a base type to an exponent", item)
        if not isinstance(item.right, ast.Num) or not isinstance(item.right.n, int) or item.right.n <= 0:
            raise InvalidTypeException("Exponent must be positive integer", item)
        return {item.left.id: item.right.n}
    else:
        raise InvalidTypeException("Invalid unit expression", item)


# Parses an expression representing a type. Annotation refers to whether
# the type is to be located in memory or storage
项目:viper    作者:ethereum    | 项目源码 | 文件源码
def aug_assign(self):
        target = self.get_target(self.stmt.target)
        sub = Expr.parse_value_expr(self.stmt.value, self.context)
        if not isinstance(self.stmt.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)):
            raise Exception("Unsupported operator for augassign")
        if not isinstance(target.typ, BaseType):
            raise TypeMismatchException("Can only use aug-assign operators with simple types!", self.stmt.target)
        if target.location == 'storage':
            o = Expr.parse_value_expr(ast.BinOp(left=LLLnode.from_list(['sload', '_stloc'], typ=target.typ, pos=target.pos),
                                    right=sub, op=self.stmt.op, lineno=self.stmt.lineno, col_offset=self.stmt.col_offset), self.context)
            return LLLnode.from_list(['with', '_stloc', target, ['sstore', '_stloc', base_type_conversion(o, o.typ, target.typ)]], typ=None, pos=getpos(self.stmt))
        elif target.location == 'memory':
            o = Expr.parse_value_expr(ast.BinOp(left=LLLnode.from_list(['mload', '_mloc'], typ=target.typ, pos=target.pos),
                                    right=sub, op=self.stmt.op, lineno=self.stmt.lineno, col_offset=self.stmt.col_offset), self.context)
            return LLLnode.from_list(['with', '_mloc', target, ['mstore', '_mloc', base_type_conversion(o, o.typ, target.typ)]], typ=None, pos=getpos(self.stmt))
项目:opyum    作者:Amper    | 项目源码 | 文件源码
def visit_BinOp(self, node: ast.BinOp):
        node = self.generic_visit(node)
        if self._is_numeric_pow(node):
            left, right = node.left, node.right
            degree = (    right.n         if isinstance(right, ast.Num) 
                    else -right.operand.n if isinstance(right.op, ast.USub) 
                    else  right.operand.n )
            degree = int(degree)
            if abs(degree) == 0:
                node = ast.copy_location(ast.Num(n = 1), node)
            elif abs(degree) == 1:
                node = node.left
            elif 2 <= abs(degree) <= self.MAX_DEGREE:
                for _ in range(1, abs(degree)):
                    new_node = ast.BinOp\
                                ( left = left
                                , op = ast.Mult()
                                , right = copy(node.left)
                                )
                    left = new_node = ast.copy_location(new_node, node)
                node = new_node
            else:
                return node
            if degree < 0:
                new_node = ast.BinOp\
                                ( left  = ast.Num(n = 1)
                                , op    = ast.Div()
                                , right = node 
                                )
                node = ast.copy_location(new_node, node)
        return node
项目:ITAP-django    作者:krivers    | 项目源码 | 文件源码
def doBinaryOp(op, l, r):
    """Perform the given AST binary operation on the values"""
    top = type(op)
    if top == ast.Add:
        return l + r
    elif top == ast.Sub:
        return l - r
    elif top == ast.Mult:
        return l * r
    elif top == ast.Div:
        # Don't bother if this will be a really long float- it won't work properly!
        # Also, in Python 3 this is floating division, so perform it accordingly.
        val = 1.0 * l / r
        if (val * 1e10 % 1.0) != 0:
            raise Exception("Repeating Float")
        return val
    elif top == ast.Mod:
        return l % r
    elif top == ast.Pow:
        return l ** r
    elif top == ast.LShift:
        return l << r
    elif top == ast.RShift:
        return l >> r
    elif top == ast.BitOr:
        return l | r
    elif top == ast.BitXor:
        return l ^ r
    elif top == ast.BitAnd:
        return l & r
    elif top == ast.FloorDiv:
        return l // r
项目:py2cpp    作者:mugwort-rc    | 项目源码 | 文件源码
def visit_AugAssign(self, node):
        if node.op.__class__ != ast.FloorDiv:
            return node
        dummy_op = ast.BinOp(left=node.target, op=ast.Div(), right=node.value)
        dummy_int = ast.Name(id="int", ctx=ast.Load())
        dummy_call = ast.Call(func=dummy_int, args=[dummy_op], keywords=[], starargs=None, kwargs=None)
        return ast.Assign(targets=[node.target], value=dummy_call)
项目:py2cpp    作者:mugwort-rc    | 项目源码 | 文件源码
def visit_BinOp(self, node):
        if node.op.__class__ != ast.FloorDiv:
            return node
        dummy_op = ast.BinOp(left=node.left, op=ast.Div(), right=node.right)
        dummy_int = ast.Name(id="int", ctx=ast.Load())
        return ast.Call(func=dummy_int, args=[dummy_op], keywords=[], starargs=None, kwargs=None)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def visit_BinOp(self, node):
        if node.op.__class__ in self.operators:
            sympy_class = self.operators[node.op.__class__]
            right = self.visit(node.right)

            if isinstance(node.op, ast.Sub):
                right = ast.UnaryOp(op=ast.USub(), operand=right)
            elif isinstance(node.op, ast.Div):
                right = ast.Call(
                    func=ast.Name(id='Pow', ctx=ast.Load()),
                    args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
                    keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
                    starargs=None,
                    kwargs=None
                )

            new_node = ast.Call(
                func=ast.Name(id=sympy_class, ctx=ast.Load()),
                args=[self.visit(node.left), right],
                keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
                starargs=None,
                kwargs=None
            )

            if sympy_class in ('Add', 'Mul'):
                # Denest Add or Mul as appropriate
                new_node.args = self.flatten(new_node.args, sympy_class)

            return new_node
        return node
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def get_binary_op_str(bin_op_node):
    """Returns the string representation of the binary operator node (e.g. +, -,
    etc.). For some reason astor doesn't implement this???
    """

    if isinstance(bin_op_node, ast.Add):
        return "+"

    elif isinstance(bin_op_node, ast.Sub):
        return "-"

    elif isinstance(bin_op_node, ast.Mult):
        return "*"

    elif isinstance(bin_op_node, ast.Div):
        return "/"

    elif isinstance(bin_op_node, ast.Mod):
        return "%"

    elif isinstance(bin_op_node, ast.Pow):
        return "**"

    elif isinstance(bin_op_node, ast.LShift):
        return "<<"

    elif isinstance(bin_op_node, ast.RShift):
        return ">>"

    else:
        raise ValueError("No string defined for binary operator node %s" % \
            bin_op_node.__class__.__name__)
项目:python2c    作者:Kcrong    | 项目源码 | 文件源码
def get_op_string(op_class):
        return {
            ast.Add: '+',
            ast.Sub: '-',
            ast.Div: '/',
            ast.Mult: '*'
        }[op_class.__class__]

    # For expr code
项目:Typpete    作者:caterinaurban    | 项目源码 | 文件源码
def binary_operation_type(left_type, op, right_type, lineno, solver):
    """Infer the type of a binary operation result"""
    if isinstance(op, ast.Add):
        inference_func = _infer_add
    elif isinstance(op, ast.Mult):
        inference_func = _infer_mult
    elif isinstance(op, ast.Div):
        inference_func = _infer_div
    elif isinstance(op, (ast.BitOr, ast.BitXor, ast.BitAnd)):
        return _infer_bitwise(left_type, right_type, op, lineno, solver)
    else:
        return _infer_arithmetic(left_type, right_type, op, lineno, solver)

    return inference_func(left_type, right_type, lineno, solver)
项目:mutpy    作者:mutpy    | 项目源码 | 文件源码
def mutate_Mult_to_Div(self, node):
        if self.should_mutate(node):
            return ast.Div()
        raise MutationResign()
项目:mutpy    作者:mutpy    | 项目源码 | 文件源码
def mutate_FloorDiv_to_Div(self, node):
        if self.should_mutate(node):
            return ast.Div()
        raise MutationResign()
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def pythonast(self, args, tonative=False):
        return ast.BinOp(args[0], ast.Div(), ast.Call(ast.Name("float", ast.Load()), [args[1]], [], None, None))
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def pythonast(self, args, tonative=False):
        arg, = args
        justlog = ast.Call(ast.Attribute(ast.Name("$math", ast.Load()), "log", ast.Load()), [arg], [], None, None)
        if self.base == math.e:
            if tonative:
                return justlog
            else:
                return ast.IfExp(ast.Compare(arg, [ast.Gt()], [ast.Num(0)]), justlog, ast.Num(-inf))
        else:
            scaled = ast.BinOp(justlog, ast.Div(), ast.Num(math.log(self.base)))
            if tonative:
                return scaled
            else:
                return ast.IfExp(ast.Compare(arg, [ast.Gt()], [ast.Num(0)]), scaled, ast.Num(-inf))
项目:tidy    作者:cyrus-    | 项目源码 | 文件源码
def syn_BinOp(self, ctx, e):
        op = e.op
        if isinstance(op, ast.Div):
            ctx.ana(e.right, ieee)
            return ieee
        else:
            ctx.ana(e.right, self)
            return self
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def visit_BinOp(self, node):
        if node.op.__class__ in self.operators:
            sympy_class = self.operators[node.op.__class__]
            right = self.visit(node.right)
            left = self.visit(node.left)
            if isinstance(node.left, ast.UnaryOp) and (isinstance(node.right, ast.UnaryOp) == 0) and sympy_class in ('Mul',):
                left, right = right, left
            if isinstance(node.op, ast.Sub):
                right = ast.UnaryOp(op=ast.USub(), operand=right)
            if isinstance(node.op, ast.Div):
                if isinstance(node.left, ast.UnaryOp):
                    if isinstance(node.right,ast.UnaryOp):
                        left, right = right, left
                    left = ast.Call(
                    func=ast.Name(id='Pow', ctx=ast.Load()),
                    args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
                    keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
                    starargs=None,
                    kwargs=None
                )
                else:
                    right = ast.Call(
                    func=ast.Name(id='Pow', ctx=ast.Load()),
                    args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))],
                    keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
                    starargs=None,
                    kwargs=None
                )

            new_node = ast.Call(
                func=ast.Name(id=sympy_class, ctx=ast.Load()),
                args=[left, right],
                keywords=[ast.keyword(arg='evaluate', value=ast.Name(id='False', ctx=ast.Load()))],
                starargs=None,
                kwargs=None
            )

            if sympy_class in ('Add', 'Mul'):
                # Denest Add or Mul as appropriate
                new_node.args = self.flatten(new_node.args, sympy_class)

            return new_node
        return node
项目:femtocode    作者:diana-hep    | 项目源码 | 文件源码
def _aslimit(value, lc):
        if isinstance(value, string_types):
            module = ast.parse(value)
            if isinstance(module, ast.Module) and len(module.body) == 1 and isinstance(module.body[0], ast.Expr):
                def restrictedeval(expr):
                    if isinstance(expr, ast.Num):
                        return expr.n

                    elif isinstance(expr, ast.Name) and expr.id == "inf":
                        return femtocode.typesystem.inf

                    elif isinstance(expr, ast.Name) and expr.id == "pi":
                        return math.pi

                    elif isinstance(expr, ast.UnaryOp) and isinstance(expr.op, ast.USub):
                        return -restrictedeval(expr.operand)

                    elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Add):
                        return restrictedeval(expr.left) + restrictedeval(expr.right)

                    elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Sub):
                        return restrictedeval(expr.left) - restrictedeval(expr.right)

                    elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Mult):
                        return restrictedeval(expr.left) * restrictedeval(expr.right)

                    elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Div):
                        return restrictedeval(expr.left) / restrictedeval(expr.right)

                    elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Pow):
                        return restrictedeval(expr.left) ** restrictedeval(expr.right)

                    elif isinstance(expr, ast.Call) and isinstance(expr.func, ast.Name) and expr.func.id == "almost" and len(expr.args) == 1 and len(expr.keywords) == 0 and expr.kwargs is None and expr.starargs is None:
                        return femtocode.typesystem.almost(restrictedeval(expr.args[0]))

                    else:
                        raise DatasetDeclaration.Error(lc, "couldn't parse as a min/max/least/most limit: {0}".format(value))

                return restrictedeval(module.body[0].value)

        elif isinstance(value, (int, long, float)):
            return value

        elif isinstance(value, femtocode.typesystem.almost) and isinstance(value.real, (int, long, float)):
            return value

        else:
            raise DatasetDeclaration.Error(lc, "unrecognized type for min/max/least/most limit: {0}".format(value))