python类UnaryOp()的实例源码

simpleeval.py 文件源码 项目:hazzy 作者: KurtJacobson 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, operators=None, functions=None, names=None):
        """
            Create the evaluator instance.  Set up valid operators (+,-, etc)
            functions (add, random, get_val, whatever) and names. """

        if not operators:
            operators = DEFAULT_OPERATORS
        if not functions:
            functions = DEFAULT_FUNCTIONS
        if not names:
            names = DEFAULT_NAMES

        self.operators = operators
        self.functions = functions
        self.names = names

        self.nodes = {
            ast.Num: self._eval_num,
            ast.Str: self._eval_str,
            ast.Name: self._eval_name,
            ast.UnaryOp: self._eval_unaryop,
            ast.BinOp: self._eval_binop,
            ast.BoolOp: self._eval_boolop,
            ast.Compare: self._eval_compare,
            ast.IfExp: self._eval_ifexp,
            ast.Call: self._eval_call,
            ast.keyword: self._eval_keyword,
            ast.Subscript: self._eval_subscript,
            ast.Attribute: self._eval_attribute,
            ast.Index: self._eval_index,
            ast.Slice: self._eval_slice,
        }

        # py3k stuff:
        if hasattr(ast, 'NameConstant'):
            self.nodes[ast.NameConstant] = self._eval_nameconstant
        elif isinstance(self.names, dict) and "None" not in self.names:
            self.names["None"] = None
operators.py 文件源码 项目:mutpy 作者: mutpy 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def negate_test(self, node):
        not_node = ast.UnaryOp(op=ast.Not(), operand=node.test)
        node.test = not_node
        return node
test_controller.py 文件源码 项目:mutpy 作者: mutpy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_generate_if_node_child(self):
        node = ast.Sub(children=[])
        mutations = [
            self.aor_mutation(node=ast.UnaryOp(children=[node])),
            self.aor_mutation(node=node),
        ]

        changes_to_apply = self.apply_strategy_to_mutations_with_order_2(controller.FirstToLastHOMStrategy, mutations)

        self.assert_num_changesets(changes_to_apply, 2)
        self.assert_num_changeset_entries(changes_to_apply, 0, 1)
        self.assert_mutation_in_changeset_at_position_equals(changes_to_apply, 0, 0, mutations[0])
        self.assert_num_changeset_entries(changes_to_apply, 1, 1)
        self.assert_mutation_in_changeset_at_position_equals(changes_to_apply, 1, 0, mutations[1])
test_ast.py 文件源码 项目:kbe_server 作者: xiaohaoppy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_unaryop(self):
        u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
        self.expr(u, "must have Load context")
rewrite.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def visit_BoolOp(self, boolop):
        res_var = self.variable()
        expl_list = self.assign(ast.List([], ast.Load()))
        app = ast.Attribute(expl_list, "append", ast.Load())
        is_or = int(isinstance(boolop.op, ast.Or))
        body = save = self.statements
        fail_save = self.on_failure
        levels = len(boolop.values) - 1
        self.push_format_context()
        # Process each operand, short-circuting if needed.
        for i, v in enumerate(boolop.values):
            if i:
                fail_inner = []
                # cond is set in a prior loop iteration below
                self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa
                self.on_failure = fail_inner
            self.push_format_context()
            res, expl = self.visit(v)
            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
            expl_format = self.pop_format_context(ast.Str(expl))
            call = ast_Call(app, [expl_format], [])
            self.on_failure.append(ast.Expr(call))
            if i < levels:
                cond = res
                if is_or:
                    cond = ast.UnaryOp(ast.Not(), cond)
                inner = []
                self.statements.append(ast.If(cond, inner, []))
                self.statements = body = inner
        self.statements = save
        self.on_failure = fail_save
        expl_template = self.helper("format_boolop", expl_list, ast.Num(is_or))
        expl = self.pop_format_context(expl_template)
        return ast.Name(res_var, ast.Load()), self.explanation_param(expl)
rewrite.py 文件源码 项目:GSM-scanner 作者: yosriayed 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def visit_UnaryOp(self, unary):
        pattern = unary_map[unary.op.__class__]
        operand_res, operand_expl = self.visit(unary.operand)
        res = self.assign(ast.UnaryOp(unary.op, operand_res))
        return res, pattern % (operand_expl,)
standard.py 文件源码 项目:femtocode 作者: diana-hep 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def pythonast(self, args, tonative=False):
        return ast.UnaryOp(ast.UAdd(), args[0])
standard.py 文件源码 项目:femtocode 作者: diana-hep 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def pythonast(self, args, tonative=False):
        return ast.UnaryOp(ast.USub(), args[0])
standard.py 文件源码 项目:femtocode 作者: diana-hep 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def pythonast(self, args, tonative=False):
        return ast.UnaryOp(ast.Not(), args[0])
obvious.py 文件源码 项目:metapensiero.pj 作者: azazel75 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def Subscript_default(t, x):
    assert isinstance(x.slice, ast.Index)
    v = x.slice.value
    if isinstance(v, ast.UnaryOp) and isinstance(v.op, ast.USub):
        return JSSubscript(
            JSCall(JSAttribute(x.value, 'slice'), [v]),
            JSNum(0))
    return JSSubscript(x.value, v)
obvious.py 文件源码 项目:metapensiero.pj 作者: azazel75 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def UnaryOp(t, x):
    return JSUnaryOp(x.op, x.operand)
builtin_predicate.py 文件源码 项目:selinon 作者: selinon 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def ast(self):
        """Python AST of this predicate (construct transitively for all indirect children as well).

        :return: AST of describing all children predicates
        """
        return ast.UnaryOp(ast.Not(), ast.Expr(value=self._child.ast()))
builtin_predicate.py 文件源码 项目:selinon 作者: selinon 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def ast(self):
        """Python AST of this predicate (construct transitively for all indirect children as well).

        :return: AST of describing all children predicates
        """
        return ast.UnaryOp(ast.Not(), ast.Expr(value=self._child.ast()))
expression.py 文件源码 项目:peval 作者: fjarri 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def handle_UnaryOp(state, node, ctx):
        state, result = peval_call(
            state, ctx, UNARY_OPS[type(node.op)], args=[node.operand])
        if not is_known_value(result):
            state = state.update(temp_bindings=state.temp_bindings.del_(result.func.id))
            result = ast.UnaryOp(op=node.op, operand=result.args[0])
        return state, result
_boolean.py 文件源码 项目:tidy 作者: cyrus- 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def translate_pat_Name_constructor(self, ctx, pat, scrutinee):
        id = pat.id
        if id == "True":
            return (scrutinee, typy.odict())
        elif id == "False":
            return (ast.UnaryOp(op=ast.Not(), operand=scrutinee), typy.odict())
bugbear.py 文件源码 项目:flake8-bugbear 作者: PyCQA 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def visit_UAdd(self, node):
        trailing_nodes = list(map(type, self.node_window[-4:]))
        if trailing_nodes == [ast.UnaryOp, ast.UAdd, ast.UnaryOp, ast.UAdd]:
            originator = self.node_window[-4]
            self.errors.append(
                B002(originator.lineno, originator.col_offset)
            )
        self.generic_visit(node)
gtoken.py 文件源码 项目:googletranslate.popclipext 作者: wizyoung 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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.session.get(self.host)
        # this will be the same as python code after stripping out a reserved word 'var'
        code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
        # unescape special ascii characters such like a \x3d(=)
        if PY3:  # pragma: no cover
            code = code.encode().decode('unicode-escape')
        else:  # pragma: no cover
            code = code.decode('string_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
rewrite.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def visit_Assert(self, assert_):
        """Return the AST statements to replace the ast.Assert instance.

        This re-writes the test of an assertion to provide
        intermediate values and replace it with an if statement which
        raises an assertion error with a detailed explanation in case
        the expression is false.

        """
        if isinstance(assert_.test, ast.Tuple) and self.config is not None:
            fslocation = (self.module_path, assert_.lineno)
            self.config.warn('R1', 'assertion is always true, perhaps '
                              'remove parentheses?', fslocation=fslocation)
        self.statements = []
        self.variables = []
        self.variable_counter = itertools.count()
        self.stack = []
        self.on_failure = []
        self.push_format_context()
        # Rewrite assert into a bunch of statements.
        top_condition, explanation = self.visit(assert_.test)
        # Create failure message.
        body = self.on_failure
        negation = ast.UnaryOp(ast.Not(), top_condition)
        self.statements.append(ast.If(negation, body, []))
        if assert_.msg:
            assertmsg = self.helper('format_assertmsg', assert_.msg)
            explanation = "\n>assert " + explanation
        else:
            assertmsg = ast.Str("")
            explanation = "assert " + explanation
        template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
        msg = self.pop_format_context(template)
        fmt = self.helper("format_explanation", msg)
        err_name = ast.Name("AssertionError", ast.Load())
        exc = ast_Call(err_name, [fmt], [])
        if sys.version_info[0] >= 3:
            raise_ = ast.Raise(exc, None)
        else:
            raise_ = ast.Raise(exc, None, None)
        body.append(raise_)
        # Clear temporary variables by setting them to None.
        if self.variables:
            variables = [ast.Name(name, ast.Store())
                         for name in self.variables]
            clear = ast.Assign(variables, _NameConstant(None))
            self.statements.append(clear)
        # Fix line numbers.
        for stmt in self.statements:
            set_location(stmt, assert_.lineno, assert_.col_offset)
        return self.statements
__init__.py 文件源码 项目:ITAP-django 作者: krivers 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def specialFunctions(cv, old, new):
    if type(old) == type(new) == list:
        log("individualize\tspecialFunctions\tWhy are we comparing lists?: " + str(cv) + ";" + printFunction(old) + ";" + printFunction(new), "bug")
        return cv
    rev = neg = False
    if (hasattr(old, "reversed") and old.reversed and (not hasattr(old, "multCompFixed"))):
        rev = True

    if (hasattr(old, "negated") and old.negated):
        neg = True

    if rev and neg:
        (old, new) = (negate(undoReverse(old)), negate(undoReverse(new)))
    elif rev:
        (old, new) = (undoReverse(old), undoReverse(new))
    elif neg:
        (old, new) = (negate(old), negate(new))
        if type(old) == ast.UnaryOp and type(old.op) == ast.Not and \
            type(new) == ast.UnaryOp and type(new.op) == ast.Not:
            # Just get rid of them
            old = old.operand
            new = new.operand

    if hasattr(old, "num_negated") and old.num_negated:
        origNew = deepcopy(new)
        (old, new) = (num_negate(old), num_negate(new))
        if new == None: # couldn't reverse the new operator
            # To get here, we must have a binary operator. Go up a level and negate the right side
            cvCopy = cv.deepcopy()
            parentSpot = deepcopy(cvCopy.traverseTree(cvCopy.start))
            if type(parentSpot) == ast.BinOp:
                cvCopy.path = cvCopy.path[1:]
                cvCopy.oldSubtree = parentSpot
                cvCopy.newSubtree = deepcopy(parentSpot)
                cvCopy.newSubtree.op = origNew
                cvCopy.newSubtree.right = num_negate(cvCopy.newSubtree.right)
                cvCopy = orderedBinOpSpecialFunction(cvCopy) # just in case
                return cvCopy
            else:
                log("individualize\tspecialFunctions\tWhere are we? " + str(type(parentSpot)), "bug")

    #if (hasattr(old, "inverted") and old.inverted):
    #   (old, new) = (invert(old), invert(new))
    cv.oldSubtree = old
    cv.newSubtree = new
    return cv
transformations.py 文件源码 项目:ITAP-django 作者: krivers 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def areDisjoint(a, b):
    """Are the sets of values that satisfy these two boolean constraints disjoint?"""
    # The easiest way to be disjoint is to have comparisons that cover different areas
    if type(a) == type(b) == ast.Compare:
        aop = a.ops[0]
        bop = b.ops[0]
        aLeft = a.left
        aRight = a.comparators[0]
        bLeft = b.left
        bRight = b.comparators[0]
        alblComp = compareASTs(aLeft, bLeft, checkEquality=True)
        albrComp = compareASTs(aLeft, bRight, checkEquality=True)
        arblComp = compareASTs(aRight, bLeft, checkEquality=True)
        arbrComp = compareASTs(aRight, bRight, checkEquality=True)
        altype = type(aLeft) in [ast.Num, ast.Str]
        artype = type(aRight) in [ast.Num, ast.Str]
        bltype = type(bLeft) in [ast.Num, ast.Str]
        brtype = type(bRight) in [ast.Num, ast.Str]

        if (type(aop) == ast.Eq and type(bop) == ast.NotEq) or \
            (type(bop) == ast.Eq and type(aop) == ast.NotEq):
            # x == y, x != y
            if (alblComp == 0 and arbrComp == 0) or (albrComp == 0 and arblComp == 0):
                return True
        elif type(aop) == type(bop) == ast.Eq:
            if (alblComp == 0 and arbrComp == 0) or (albrComp == 0 and arblComp == 0):
                return False
            # x = num1, x = num2
            elif alblComp == 0 and artype and brtype:
                return True
            elif albrComp == 0 and artype and bltype:
                return True
            elif arblComp == 0 and altype and brtype:
                return True
            elif arbrComp == 0 and altype and bltype:
                return True
        elif (type(aop) == ast.Lt and type(bop) == ast.GtE) or \
            (type(aop) == ast.Gt and type(bop) == ast.LtE) or \
            (type(aop) == ast.LtE and type(bop) == ast.Gt) or \
            (type(aop) == ast.GtE and type(bop) == ast.Lt) or \
            (type(aop) == ast.Is and type(bop) == ast.IsNot) or \
            (type(aop) == ast.IsNot and type(bop) == ast.Is) or \
            (type(aop) == ast.In and type(bop) == ast.NotIn) or \
            (type(aop) == ast.NotIn and type(bop) == ast.In):
            if alblComp == 0 and arbrComp == 0:
                return True
        elif (type(aop) == ast.Lt and type(bop) == ast.LtE) or \
            (type(aop) == ast.Gt and type(bop) == ast.GtE) or \
            (type(aop) == ast.LtE and type(bop) == ast.Lt) or \
            (type(aop) == ast.GtE and type(bop) == ast.Gt):
            if albrComp == 0 and arblComp == 0:
                return True
    elif type(a) == type(b) == ast.BoolOp:
        return False # for now- TODO: when is this not true?
    elif type(a) == ast.UnaryOp and type(a.op) == ast.Not:
        if compareASTs(a.operand, b, checkEquality=True) == 0:
            return True
    elif type(b) == ast.UnaryOp and type(b.op) == ast.Not:
        if compareASTs(b.operand, a, checkEquality=True) == 0:
            return True
    return False


问题


面经


文章

微信
公众号

扫码关注公众号